diff --git a/rse/plugins/org.eclipse.rse.core/.cvsignore b/rse/plugins/org.eclipse.rse.core/.cvsignore new file mode 100644 index 00000000000..ba077a4031a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.core/.cvsignore @@ -0,0 +1 @@ +bin diff --git a/rse/plugins/org.eclipse.rse.files.ui/.classpath b/rse/plugins/org.eclipse.rse.files.ui/.classpath new file mode 100644 index 00000000000..751c8f2e504 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/rse/plugins/org.eclipse.rse.files.ui/.cvsignore b/rse/plugins/org.eclipse.rse.files.ui/.cvsignore new file mode 100644 index 00000000000..ba077a4031a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/.cvsignore @@ -0,0 +1 @@ +bin diff --git a/rse/plugins/org.eclipse.rse.files.ui/.project b/rse/plugins/org.eclipse.rse.files.ui/.project new file mode 100644 index 00000000000..dd7880b80d0 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/.project @@ -0,0 +1,28 @@ + + + org.eclipse.rse.files.ui + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/rse/plugins/org.eclipse.rse.files.ui/META-INF/MANIFEST.MF b/rse/plugins/org.eclipse.rse.files.ui/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..f7abcb33f40 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/META-INF/MANIFEST.MF @@ -0,0 +1,34 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %plugin.name +Bundle-SymbolicName: org.eclipse.rse.files.ui;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Activator: org.eclipse.rse.files.ui.Activator +Bundle-Localization: plugin +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.rse.services, + org.eclipse.core.resources, + org.eclipse.ui.ide, + org.eclipse.ui.views, + org.eclipse.debug.core, + org.eclipse.ui.workbench.texteditor, + org.eclipse.jface.text, + org.eclipse.search, + org.eclipse.compare, + org.eclipse.rse.subsystems.shells.core, + org.eclipse.rse.subsystems.files.core, + org.eclipse.rse.ui +Eclipse-LazyStart: true +Export-Package: org.eclipse.rse.files.ui, + org.eclipse.rse.files.ui.actions, + org.eclipse.rse.files.ui.compare, + org.eclipse.rse.files.ui.dialogs, + org.eclipse.rse.files.ui.propertypages, + org.eclipse.rse.files.ui.resources, + org.eclipse.rse.files.ui.search, + org.eclipse.rse.files.ui.view, + org.eclipse.rse.files.ui.widgets, + org.eclipse.rse.files.ui.wizards +Bundle-Vendor: Eclipse.org +Bundle-ClassPath: files_ui.jar diff --git a/rse/plugins/org.eclipse.rse.files.ui/about.html b/rse/plugins/org.eclipse.rse.files.ui/about.html new file mode 100644 index 00000000000..6f6b96c4c87 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/about.html @@ -0,0 +1,22 @@ + + + +About + + + +

About This Content

+ +

February 24, 2005

+

License

+ +

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available at http://www.eclipse.org/legal/epl-v10.html. +For purposes of the EPL, "Program" will mean the Content.

+ +

If you did not receive this Content directly from the Eclipse Foundation, the Content is being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content.

+ + + \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/build.properties b/rse/plugins/org.eclipse.rse.files.ui/build.properties new file mode 100644 index 00000000000..000d4a08dce --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/build.properties @@ -0,0 +1,14 @@ +bin.includes = META-INF/,\ + plugin.xml,\ + about.html,\ + icons/,\ + plugin.properties,\ + files_ui.jar +src.includes = icons/,\ + plugin.properties,\ + plugin.xml,\ + META-INF/,\ + about.html +source.files_ui.jar = src/ +jars.compile.order = files_ui.jar +output.files_ui.jar = bin/ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/system_search.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/system_search.gif new file mode 100644 index 00000000000..e8038543cd5 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/system_search.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfile.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfile.gif new file mode 100644 index 00000000000..a966159d95a Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfile.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfiles_obj.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfiles_obj.gif new file mode 100644 index 00000000000..9d35f172823 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfiles_obj.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfileslive_obj.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfileslive_obj.gif new file mode 100644 index 00000000000..5d568697977 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfileslive_obj.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfolder.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfolder.gif new file mode 100644 index 00000000000..5ae555a346c Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemfolder.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systeminfo.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systeminfo.gif new file mode 100644 index 00000000000..745b884ff03 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systeminfo.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocal_obj.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocal_obj.gif new file mode 100644 index 00000000000..d60c188caa9 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocal_obj.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocallive_obj.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocallive_obj.gif new file mode 100644 index 00000000000..ba10dec0a5d Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemlocallive_obj.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdrive.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdrive.gif new file mode 100644 index 00000000000..fd426343bb6 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdrive.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdriveopen.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdriveopen.gif new file mode 100644 index 00000000000..2171f7c382a Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemrootdriveopen.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemsearchresult.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemsearchresult.gif new file mode 100644 index 00000000000..77bbe12aa84 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/obj16/systemsearchresult.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/archive_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/archive_ovr.gif new file mode 100644 index 00000000000..b4810679346 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/archive_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/binary_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/binary_ovr.gif new file mode 100644 index 00000000000..16fee8680a8 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/binary_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_binary_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_binary_ovr.gif new file mode 100644 index 00000000000..99c6243529f Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_binary_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_ovr.gif new file mode 100644 index 00000000000..13077f940ab Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exec_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exscript_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exscript_ovr.gif new file mode 100644 index 00000000000..17d61ba5054 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/exscript_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/shared_objunix_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/shared_objunix_ovr.gif new file mode 100644 index 00000000000..e79e16de8de Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/shared_objunix_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/sharedlib_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/sharedlib_ovr.gif new file mode 100644 index 00000000000..04e5d9a3f70 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/sharedlib_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/symblclnk_ovr.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/symblclnk_ovr.gif new file mode 100644 index 00000000000..7e0fe3c48a1 Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/symblclnk_ovr.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/virtual_tsk.gif b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/virtual_tsk.gif new file mode 100644 index 00000000000..d645261813d Binary files /dev/null and b/rse/plugins/org.eclipse.rse.files.ui/icons/full/ovr16/virtual_tsk.gif differ diff --git a/rse/plugins/org.eclipse.rse.files.ui/plugin.properties b/rse/plugins/org.eclipse.rse.files.ui/plugin.properties new file mode 100644 index 00000000000..6639a841c11 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/plugin.properties @@ -0,0 +1,44 @@ +################################################################################ +# Copyright (c) 2006 IBM Corporation. All rights reserved. +# This program and the accompanying materials are made available under the terms +# of the Eclipse Public License v1.0 which accompanies this distribution, and is +# available at http://www.eclipse.org/legal/epl-v10.html +# +# Initial Contributors: +# The following IBM employees contributed to the Remote System Explorer +# component that contains this file: David McKnight, Kushal Munir, +# Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, +# Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. +# +# Contributors: +# {Name} (company) - description of contribution. +################################################################################ + +plugin.name = RSE Files UI + +PreferencePage.UniversalFiles = Files +PreferencePage.Cache = File Cache + + +RemotePropertyPage.File.Info = Info +PropertyPage.EnvVariables = Environment Variables + +PropertyPage.ServerLauncherSettings = Server Launcher Settings +PropertyPage.ServerConnectionSecurity = Server Connection Security +PropertyPage.Service = Service + +# Decorators +LinkDecorator.label=Link Decorator +LibraryDecorator.label=Library Decorator +JavaExecutableDecorator.label=Java Executable Decorator +BinaryExecutableDecorator.label=Binary Executable Decorator +VirtualObjectDecorator.label=Virtual Object Decorator +ScriptExecutableDecorator.label=Script Executable Decorator +VirtualObjectDecorator.label=Virtual Object Decorator +SubSystemErrorDecorator.label=SubSystem Error Decorator + + +Search.Page = Remote Search +searchMenu.label = Se&arch +Remote.Search = &Remote... +Remote.Search.tooltip = Opens Remote Search dialog page for text and file searching on remote systems \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/plugin.xml b/rse/plugins/org.eclipse.rse.files.ui/plugin.xml new file mode 100644 index 00000000000..ce75c3a92ac --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/plugin.xml @@ -0,0 +1,320 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/Activator.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/Activator.java new file mode 100644 index 00000000000..67ff24f5937 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/Activator.java @@ -0,0 +1,152 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; + +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.core.runtime.Platform; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemRemoteEditManager; +import org.eclipse.rse.files.ui.resources.SystemUniversalTempFileListener; +import org.eclipse.rse.files.ui.view.RemoteFileSubsystemFactoryAdapterFactory; +import org.eclipse.rse.files.ui.view.SystemViewFileAdapterFactory; +import org.eclipse.rse.files.ui.view.SystemViewSearchResultAdapterFactory; +import org.eclipse.rse.files.ui.view.SystemViewSearchResultSetAdapterFactory; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + + +/** + * The main plugin class to be used in the desktop. + */ +public class Activator extends AbstractUIPlugin { + + //The shared instance. + private static Activator plugin; + + private static SystemUniversalTempFileListener _tempFileListener; + + private SystemViewFileAdapterFactory svfaf; // for fastpath + private SystemViewSearchResultSetAdapterFactory svsaf; // for fastpath + private SystemViewSearchResultAdapterFactory svsraf; // for fastpath + + /** + * The constructor. + */ + public Activator() { + plugin = this; + } + + /** + * This method is called upon plug-in activation + */ + public void start(BundleContext context) throws Exception { + super.start(context); + + // refresh the remote edit project at plugin startup, to ensure + // it's never closed + SystemRemoteEditManager.getDefault().refreshRemoteEditProject(); + + + int eventMask = IResourceChangeEvent.POST_CHANGE; + IWorkspace ws = SystemBasePlugin.getWorkspace(); + + + + + IAdapterManager manager = Platform.getAdapterManager(); + + svfaf = new SystemViewFileAdapterFactory(); + svfaf.registerWithManager(manager); + + + + svsaf = new SystemViewSearchResultSetAdapterFactory(); + svsaf.registerWithManager(manager); + + svsraf = new SystemViewSearchResultAdapterFactory(); + svsraf.registerWithManager(manager); + + RemoteFileSubsystemFactoryAdapterFactory rfssfaf = new RemoteFileSubsystemFactoryAdapterFactory(); + rfssfaf.registerWithManager(manager); + + // universal temp file listener + _tempFileListener = SystemUniversalTempFileListener.getListener(); + // add listener for temp files + ws.addResourceChangeListener(_tempFileListener, eventMask); + } + + /** + * This method is called when the plug-in is stopped + */ + public void stop(BundleContext context) throws Exception + { + super.stop(context); + + IWorkspace ws = SystemBasePlugin.getWorkspace(); + ws.removeResourceChangeListener(_tempFileListener); + _tempFileListener = null; + plugin = null; + + + + } + + /** + * Returns the shared instance. + */ + public static Activator getDefault() { + return plugin; + } + + /** + * Returns an image descriptor for the image file at the given + * plug-in relative path. + * + * @param path the path + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String path) { + return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.rse.files.ui", path); + } + + /** + * For pathpath access to our adapters for remote universal file objects. Exploits the knowledge we use singleton adapters. + */ + public SystemViewFileAdapterFactory getSystemViewFileAdapterFactory() + { + return svfaf; + } + + /** + * For pathpath access to our adapters for searchable result output objects. Exploits the knowledge we use singleton adapters. + */ + public SystemViewSearchResultSetAdapterFactory getSystemViewSearchResultSetAdapterFactory() + { + return svsaf; + } + + /** + * For pathpath access to our adapters for searchable result output objects. Exploits the knowledge we use singleton adapters. + */ + public SystemViewSearchResultAdapterFactory getSystemViewSearchResultAdapterFactory() + { + return svsraf; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.java new file mode 100644 index 00000000000..604ff550b03 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.java @@ -0,0 +1,291 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; + +import org.eclipse.osgi.util.NLS; + +public class FileResources extends NLS +{ + private static String BUNDLE_NAME = "org.eclipse.rse.files.ui.FileResources"; + + public static String RESID_FILES_PREFERENCES_BUFFER; + public static String RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_LABEL; + public static String RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_LABEL; + public static String RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_TOOLTIP; + public static String RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_TOOLTIP; + + public static String ResourceNavigator_openWith; + public static String RSEOperation_message; + + // --- File Editors --- + public static String FileEditorPreference_fileTypes; + public static String FileEditorPreference_add; + public static String FileEditorPreference_remove; + public static String FileEditorPreference_associatedEditors; + public static String FileEditorPreference_addEditor; + public static String FileEditorPreference_removeEditor; + public static String FileEditorPreference_default; + public static String FileEditorPreference_existsTitle; + public static String FileEditorPreference_existsMessage; + public static String FileEditorPreference_defaultLabel; + public static String FileEditorPreference_contentTypesRelatedLink; + public static String FileEditorPreference_isLocked; + + public static String FileExtension_fileTypeMessage; + public static String FileExtension_fileTypeLabel; + public static String FileExtension_shellTitle; + public static String FileExtension_dialogTitle; + + public static String DefaultEditorDescription_name; + + // EXTRACT ARCHIVE TO DIALOG... + public static String RESID_EXTRACTTO_TITLE; + public static String RESID_EXTRACTTO_PROMPT; + + // COMBINE ARCHIVES DIALOG... + public static String RESID_COMBINE_TITLE; + public static String RESID_COMBINE_PROMPT; + public static String RESID_COMBINE_NAME_LABEL; + public static String RESID_COMBINE_NAME_TOOLTIP; + public static String RESID_COMBINE_TYPE_LABEL; + public static String RESID_COMBINE_TYPE_TOOLTIP; + + // CONVERT ARCHIVE DIALOG... + public static String RESID_CONVERT_TITLE; + public static String RESID_CONVERT_PROMPT; + public static String RESID_CONVERT_LOCATION; + public static String RESID_CONVERT_NAMEANDTYPE; + + // ADD TO ARCHIVE DIALOG... + public static String RESID_ADDTOARCHIVE_TITLE; + public static String RESID_ADDTOARCHIVE_PROMPT; + public static String RESID_ADDTOARCHIVE_LOCATION; + public static String RESID_ADDTOARCHIVE_NAMEANDTYPE; + public static String RESID_ADDTOARCHIVE_SAVEPATH_LABEL; + public static String RESID_ADDTOARCHIVE_SAVEPATH_TOOLTIP; + public static String RESID_ADDTOARCHIVE_RELATIVETO_LABEL; + public static String RESID_ADDTOARCHIVE_RELATIVETO_TOOLTIP; + + // NEW FILE WIZARD... + public static String RESID_NEWFILE_TITLE; + public static String RESID_NEWFILE_PAGE1_TITLE; + public static String RESID_NEWFILE_PAGE1_DESCRIPTION; + public static String RESID_NEWFILE_NAME_LABEL; + public static String RESID_NEWFILE_NAME_TOOLTIP; + public static String RESID_NEWFILE_FOLDER_LABEL; + public static String RESID_NEWFILE_FOLDER_TIP; + public static String RESID_NEWFILE_CONNECTIONNAME_LABEL; + public static String RESID_NEWFILE_CONNECTIONNAME_TIP; + + // NEW FOLDER WIZARD... + public static String RESID_NEWFOLDER_TITLE; + public static String RESID_NEWFOLDER_PAGE1_TITLE; + public static String RESID_NEWFOLDER_PAGE1_DESCRIPTION; + public static String RESID_NEWFOLDER_NAME_LABEL; + public static String RESID_NEWFOLDER_NAME_TOOLTIP; + public static String RESID_NEWFOLDER_FOLDER_LABEL; + public static String RESID_NEWFOLDER_FOLDER_TIP; + public static String RESID_NEWFOLDER_CONNECTIONNAME_LABEL; + public static String RESID_NEWFOLDER_CONNECTIONNAME_TIP; + + // --------------------------------------------------- + // PREFERENCES FOR UNIVERSAL FILE SYSTEM ... + // --------------------------------------------------- + + public static String RESID_PREF_UNIVERSAL_FILES_TITLE; + public static String RESID_PREF_UNIVERSAL_SHOWHIDDEN_LABEL; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_TABLECOL_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_TABLECOL_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_TOOLTIP; + + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_LABEL; + public static String RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_TOOLTIP; + + // Search constants + // Search dialog constants + // search string controls + public static String RESID_SEARCH_STRING_LABEL_LABEL; + public static String RESID_SEARCH_STRING_LABEL_TOOLTIP; + + public static String RESID_SEARCH_STRING_COMBO_TOOLTIP; + + public static String RESID_SEARCH_CASE_BUTTON_LABEL; + public static String RESID_SEARCH_CASE_BUTTON_TOOLTIP; + + public static String RESID_SEARCH_STRING_HINT_LABEL; + public static String RESID_SEARCH_STRING_HINT_TOOLTIP; + + public static String RESID_SEARCH_STRING_REGEX_LABEL; + public static String RESID_SEARCH_STRING_REGEX_TOOLTIP; + + // file name controls + public static String RESID_SEARCH_FILENAME_LABEL_LABEL; + public static String RESID_SEARCH_FILENAME_LABEL_TOOLTIP; + public static String RESID_SEARCH_FILENAME_COMBO_TOOLTIP; + public static String RESID_SEARCH_FILENAME_BROWSE_LABEL; + public static String RESID_SEARCH_FILENAME_BROWSE_TOOLTIP; + + public static String RESID_SEARCH_FILENAME_HINT_LABEL; + public static String RESID_SEARCH_FILENAME_HINT_TOOLTIP; + + public static String RESID_SEARCH_FILENAME_REGEX_LABEL; + public static String RESID_SEARCH_FILENAME_REGEX_TOOLTIP; + + // folder name controls + public static String RESID_SEARCH_FOLDERNAME_LABEL_LABEL; + public static String RESID_SEARCH_FOLDERNAME_LABEL_TOOLTIP; + + public static String RESID_SEARCH_FOLDERNAME_COMBO_TOOLTIP; + + public static String RESID_SEARCH_FOLDERNAME_BROWSE_LABEL; + public static String RESID_SEARCH_FOLDERNAME_BROWSE_TOOLTIP; + + // advanced search controls + public static String RESID_SEARCH_INCLUDE_ARCHIVES_LABEL; + public static String RESID_SEARCH_INCLUDE_ARCHIVES_TOOLTIP; + + public static String RESID_SEARCH_INCLUDE_SUBFOLDERS_LABEL; + public static String RESID_SEARCH_INCLUDE_SUBFOLDERS_TOOLTIP; + + // advanced search filters + public static String RESID_SEARCH_CONNECTIONNAMELABEL_LABEL; + public static String RESID_SEARCH_CONNECTIONNAMELABEL_TOOLTIP; + + public static String RESID_SEARCH_TARGETGROUP_LABEL; + public static String RESID_SEARCH_TARGETGROUP_TOOLTIP; + + public static String RESID_SEARCH_COLUMNSGROUP_LABEL; + public static String RESID_SEARCH_COLUMNSGROUP_TOOLTIP; + + public static String RESID_SEARCH_ALLCOLUMNSLABEL_LABEL; + public static String RESID_SEARCH_ALLCOLUMNSLABEL_TOOLTIP; + + public static String RESID_SEARCH_BETWEENLABEL_LABEL; + public static String RESID_SEARCH_ANDLABEL_LABEL; + public static String RESID_SEARCH_EOLLABEL_LABEL; + public static String RESID_SEARCH_FIRSTCOLUMN_TOOLTIP; + public static String RESID_SEARCH_SECONDCOLUMN_TOOLTIP; + public static String RESID_SEARCH_BOTHCOLUMNSLABEL_TOOLTIP; + public static String RESID_SEARCH_STARTCOLUMNLABEL_TOOLTIP; + + public static String RESID_SEARCH_MESSAGE_SEARCHING; + public static String RESID_SEARCH_MESSAGE_ONEMATCH; + public static String RESID_SEARCH_MESSAGE_MULTIPLEMATCHES; + + // Resource conflict dlg constants + public static String RESID_CONFLICT_SAVE_TITLE; + public static String RESID_CONFLICT_SAVE_MESSAGE; + public static String RESID_CONFLICT_SAVE_OVERWRITEREMOTE; + public static String RESID_CONFLICT_SAVE_REPLACELOCAL; + public static String RESID_CONFLICT_SAVE_SAVETODIFFERENT; + + public static String RESID_CONFLICT_DOWNLOAD_TITLE; + public static String RESID_CONFLICT_DOWNLOAD_MESSAGE_LOCALCHANGED; + public static String RESID_CONFLICT_DOWNLOAD_MESSAGE_REMOTECHANGED; + public static String RESID_CONFLICT_DOWNLOAD_REPLACELOCAL; + public static String RESID_CONFLICT_DOWNLOAD_OPENWITHLOCAL; + + // RSE Cache Preferences + public static String RESID_PREF_CACHE_DESCRIPTION; + public static String RESID_PREF_CACHE_CLEAR; + public static String RESID_PREF_CACHE_CLEAR_LABEL; + public static String RESID_PREF_CACHE_CLEAR_TOOLTIP; + public static String RESID_PREF_CACHE_MAX_CACHE_SIZE_LABEL; + public static String RESID_PREF_CACHE_MAX_CACHE_SIZE_DESCRIPTION; + public static String RESID_PREF_CACHE_MAX_CACHE_SIZE_TOOLTIP; + public static String RESID_PREF_CACHE_CLEAR_WARNING_LABEL; + public static String RESID_PREF_CACHE_CLEAR_WARNING_DESCRIPTION; + + // SUPERTRANSFER PROGRESS MONITOR CONSTANTS + public static String RESID_SUPERTRANSFER_PROGMON_MAIN; + public static String RESID_SUPERTRANSFER_PROGMON_SUBTASK_CREATE; + public static String RESID_SUPERTRANSFER_PROGMON_SUBTASK_POPULATE; + + public static String RESID_SUPERTRANSFER_PROGMON_SUBTASK_TRANSFER; + public static String RESID_SUPERTRANSFER_PROGMON_SUBTASK_EXTRACT; + public static String RESID_SUPERTRANSFER_PROGMON_ARCHIVE; + + // SUPERTRANSFER PREFERENCES PAGE CONSTANTS + public static String RESID_SUPERTRANSFER_PREFS_ENABLE; + public static String RESID_SUPERTRANSFER_PREFS_TYPE_LABEL; + public static String RESID_SUPERTRANSFER_PREFS_TYPE_TOOLTIP; + + // Compare with menu item + public static String ACTION_COMPAREWITH_EACH_LABEL; + public static String ACTION_COMPAREWITH_EACH_TOOLTIP; + + public static String ACTION_COMPAREWITH_HISTORY_LABEL; + public static String ACTION_COMPAREWITH_HISTORY_TOOLTIP; + + // Replace with menu item + public static String ACTION_REPLACEWITH_HISTORY_LABEL; + public static String ACTION_REPLACEWITH_HISTORY_TOOLTIP; + + // Archive Menu Items + public static String ACTION_EXTRACT_LABEL; + public static String ACTION_EXTRACT_SUB_LABEL; + public static String ACTION_EXTRACT_TOOLTIP; + public static String ACTION_EXTRACT_TO_LABEL; + public static String ACTION_EXTRACT_TO_TOOLTIP; + + public static String ACTION_COMBINE_LABEL; + public static String ACTION_COMBINE_TOOLTIP; + + public static String ACTION_CONVERT_LABEL; + public static String ACTION_CONVERT_TOOLTIP; + + public static String ACTION_ADDTOARCHIVE_LABEL; + public static String ACTION_ADDTOARCHIVE_TOOLTIP; + + // Project menu item + public static String RESID_OPEN_FROM_ASSOCIATED_PROJECT; + + // Other Actions + public static String ACTION_NEWFOLDER_LABEL; + public static String ACTION_NEWFOLDER_TOOLTIP; + + public static String ACTION_SELECT_DIRECTORY_LABEL; + public static String ACTION_SELECT_DIRECTORY_TOOLTIP; + + public static String ACTION_SELECT_FILE_LABEL; + public static String ACTION_SELECT_FILE_TOOLTIP; + + static + { + // load message values from bundle file + NLS.initializeMessages(BUNDLE_NAME, FileResources.class); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.properties b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.properties new file mode 100644 index 00000000000..577c791bae7 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/FileResources.properties @@ -0,0 +1,282 @@ +################################################################################ +# Copyright (c) 2006 IBM Corporation. All rights reserved. +# This program and the accompanying materials are made available under the terms +# of the Eclipse Public License v1.0 which accompanies this distribution, and is +# available at http://www.eclipse.org/legal/epl-v10.html +# +# Initial Contributors: +# The following IBM employees contributed to the Remote System Explorer +# component that contains this file: David McKnight, Kushal Munir, +# Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, +# Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. +# +# Contributors: +# {Name} (company) - description of contribution. +################################################################################ + +# NLS_MESSAGEFORMAT_NONE + +RESID_FILES_PREFERENCES_BUFFER=File Transfer Buffer Size +RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_LABEL=Download (KB) +RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_LABEL=Upload (KB) +RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_TOOLTIP=Maximum size of buffer to use while sending files from the host to the client +RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_TOOLTIP=Maximum size of the buffer to use while sending files from the client to the host + +ResourceNavigator_openWith = Open Wit&h +RSEOperation_message = Remote Systems Explorer Operation + +# --- File Editors --- +FileEditorPreference_fileTypes = File &types: +FileEditorPreference_add = &Add... +FileEditorPreference_remove = &Remove +FileEditorPreference_associatedEditors = Associated &editors: +FileEditorPreference_addEditor = A&dd... +FileEditorPreference_removeEditor = Re&move +FileEditorPreference_default = De&fault +FileEditorPreference_existsTitle = File Type Exists +FileEditorPreference_existsMessage = An entry already exists for that file type +FileEditorPreference_defaultLabel = (default) +FileEditorPreference_contentTypesRelatedLink = See ''{0}'' for content-type based file associations. +FileEditorPreference_isLocked = {0} (locked by ''{1}'' content type) + +FileExtension_fileTypeMessage = Enter file type to add: (*.doc or report.doc for example) +FileExtension_fileTypeLabel = File &type: +FileExtension_shellTitle = New File Type +FileExtension_dialogTitle = Define a New File Type + +DefaultEditorDescription_name = &Default Editor + +#============================================================= +# NEW FILE WIZARD... +#============================================================= +RESID_NEWFILE_TITLE=New File +RESID_NEWFILE_PAGE1_TITLE=Remote File +RESID_NEWFILE_PAGE1_DESCRIPTION=Create a New File +RESID_NEWFILE_FOLDER_LABEL=Folder name +RESID_NEWFILE_FOLDER_TIP=Folder in which the new file will be created +RESID_NEWFILE_CONNECTIONNAME_LABEL=Connection name +RESID_NEWFILE_CONNECTIONNAME_TIP=Connection name where the new file will be created +RESID_NEWFILE_NAME_LABEL=File name +RESID_NEWFILE_NAME_TOOLTIP=Enter a file name for the new file + +#============================================================= +# NEW FOLDER WIZARD... +#============================================================= +RESID_NEWFOLDER_TITLE=New Folder +RESID_NEWFOLDER_PAGE1_TITLE=Remote Folder +RESID_NEWFOLDER_PAGE1_DESCRIPTION=Create a New Folder +RESID_NEWFOLDER_CONNECTIONNAME_LABEL=Connection name +RESID_NEWFOLDER_CONNECTIONNAME_TIP=Connection name where the new folder will be created +RESID_NEWFOLDER_NAME_LABEL=Folder name +RESID_NEWFOLDER_NAME_TOOLTIP=Enter a folder name for the new folder +RESID_NEWFOLDER_FOLDER_LABEL=Folder name +RESID_NEWFOLDER_FOLDER_TIP=Folder in which the new folder will be created + +############################################################## +# Preference pages for universal file system +############################################################## +RESID_PREF_UNIVERSAL_FILES_TITLE=File System Preferences +RESID_PREF_UNIVERSAL_SHOWHIDDEN_LABEL=Show hidden files + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_LABEL=File types: +RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_TOOLTIP=List of file types + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_TABLECOL_LABEL=Type +RESID_PREF_UNIVERSAL_FILES_FILETYPES_TABLECOL_TOOLTIP=Type + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_LABEL=Add... +RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_TOOLTIP=Add a file type + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_LABEL=Remove +RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_TOOLTIP=Remove selected file type + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_LABEL=File Transfer Mode +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TOOLTIP=Mode of file transfer for selected file type + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_LABEL=Binary +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_TOOLTIP=Transfer as binary file + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_LABEL=Text +RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_TOOLTIP=Transfer as text file + +RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_LABEL=Default File Transfer Mode +RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_TOOLTIP=Default mode of file transfer for unspecified file types + +################################################################################### +############################ Remote Search ############################## +################################################################################### +RESID_SEARCH_STRING_LABEL_LABEL= Search string (leave empty for file search): +RESID_SEARCH_STRING_LABEL_TOOLTIP= String to be searched +RESID_SEARCH_STRING_COMBO_TOOLTIP= Enter or select search string +RESID_SEARCH_CASE_BUTTON_LABEL= Case sensitive +RESID_SEARCH_CASE_BUTTON_TOOLTIP= Specify whether case should be considered during search +RESID_SEARCH_STRING_HINT_LABEL= (* = any string, ? = any character, \\ = escape for literals: * ? \\) +RESID_SEARCH_STRING_HINT_TOOLTIP= Special characters allowed in search string +RESID_SEARCH_STRING_REGEX_LABEL= Regular expression +RESID_SEARCH_STRING_REGEX_TOOLTIP= Specify whether search string is a regular expression +RESID_SEARCH_FILENAME_LABEL_LABEL= File name patterns: +RESID_SEARCH_FILENAME_LABEL_TOOLTIP= File name patterns +RESID_SEARCH_FILENAME_COMBO_TOOLTIP= Enter or select file name patterns +RESID_SEARCH_FILENAME_BROWSE_LABEL= Browse... +RESID_SEARCH_FILENAME_BROWSE_TOOLTIP= Opens a dialog to select or enter file types +RESID_SEARCH_FILENAME_HINT_LABEL= Patterns are separated by comma (* = any string, ? = any character) +RESID_SEARCH_FILENAME_HINT_TOOLTIP= Special characters allowed in file name patterns +RESID_SEARCH_FILENAME_REGEX_LABEL= Regular expression +RESID_SEARCH_FILENAME_REGEX_TOOLTIP= Specify whether file name pattern is a regular expression +RESID_SEARCH_FOLDERNAME_LABEL_LABEL= Folder: +RESID_SEARCH_FOLDERNAME_LABEL_TOOLTIP= Folder path +RESID_SEARCH_FOLDERNAME_COMBO_TOOLTIP= Identifies the folder in which to search. It is fully qualified including the connection name, as in connection:/path/folder +RESID_SEARCH_FOLDERNAME_BROWSE_LABEL= Browse... +RESID_SEARCH_FOLDERNAME_BROWSE_TOOLTIP= Opens a dialog to select a folder +RESID_SEARCH_INCLUDE_ARCHIVES_LABEL= Search archive files +RESID_SEARCH_INCLUDE_ARCHIVES_TOOLTIP= Specify whether archive files such as zip, jar and tar files should also be searched +RESID_SEARCH_INCLUDE_SUBFOLDERS_LABEL= Search subfolders +RESID_SEARCH_INCLUDE_SUBFOLDERS_TOOLTIP= Specify whether subfolders should also be searched +RESID_SEARCH_CONNECTIONNAMELABEL_LABEL= Connection name: +RESID_SEARCH_CONNECTIONNAMELABEL_TOOLTIP= Connection name +RESID_SEARCH_TARGETGROUP_LABEL= Target +RESID_SEARCH_TARGETGROUP_TOOLTIP= Specify search target +RESID_SEARCH_COLUMNSGROUP_LABEL= Columns +RESID_SEARCH_COLUMNSGROUP_TOOLTIP= Specify columns +RESID_SEARCH_ALLCOLUMNSLABEL_LABEL= All columns +RESID_SEARCH_ALLCOLUMNSLABEL_TOOLTIP= Search all columns +RESID_SEARCH_BETWEENLABEL_LABEL= Between +RESID_SEARCH_ANDLABEL_LABEL= and +RESID_SEARCH_EOLLABEL_LABEL= and end of line +RESID_SEARCH_FIRSTCOLUMN_TOOLTIP= Specify start column +RESID_SEARCH_SECONDCOLUMN_TOOLTIP= Specify end column +RESID_SEARCH_BOTHCOLUMNSLABEL_TOOLTIP= Search between specified columns +RESID_SEARCH_STARTCOLUMNLABEL_TOOLTIP= Search between specified column and end of line + +# Search dialog +RESID_SEARCH_MESSAGE_SEARCHING= Searching... +RESID_SEARCH_MESSAGE_ONEMATCH= %1 match +RESID_SEARCH_MESSAGE_MULTIPLEMATCHES= %1 matches + +################################################################################## +############################ Resource Conflict Dlgs ######################### +################################################################################## +RESID_CONFLICT_SAVE_TITLE= Save Conflict +RESID_CONFLICT_SAVE_MESSAGE= This file has changed on the remote system since it was opened. +RESID_CONFLICT_SAVE_OVERWRITEREMOTE= Overwrite the remote file. +RESID_CONFLICT_SAVE_REPLACELOCAL= Replace contents of editor with remote file. Pending changes will be lost. +RESID_CONFLICT_SAVE_SAVETODIFFERENT= Save the contents of the editor to a different remote file. + +RESID_CONFLICT_DOWNLOAD_TITLE= Local Changes Pending +RESID_CONFLICT_DOWNLOAD_MESSAGE_LOCALCHANGED= This file has pending changes that have not been saved to the remote system. +RESID_CONFLICT_DOWNLOAD_MESSAGE_REMOTECHANGED= This file has pending changes that have not been saved to the remote system and the file has changed on the remote system. +RESID_CONFLICT_DOWNLOAD_REPLACELOCAL= Replace pending changes with remote file +RESID_CONFLICT_DOWNLOAD_OPENWITHLOCAL= Open editor with pending changes + +#============================================================== +# REMOTE FILE SYSTEM CACHE PREFERENCE PAGE +#============================================================= +RESID_PREF_CACHE_DESCRIPTION=When RSE is used for editing, the remote files are cached. Use this page to clear or limit the size of the file cache. +RESID_PREF_CACHE_CLEAR=Clear +RESID_PREF_CACHE_CLEAR_LABEL=Clear cached files +RESID_PREF_CACHE_CLEAR_TOOLTIP=Delete remote files that have been cached in the local workspace +RESID_PREF_CACHE_MAX_CACHE_SIZE_LABEL=Maximum cache size (MB) +RESID_PREF_CACHE_MAX_CACHE_SIZE_DESCRIPTION=Enter the maxium size space that can be used by the cache +RESID_PREF_CACHE_MAX_CACHE_SIZE_TOOLTIP=Enter the maxium size space that can be used by the cache +RESID_PREF_CACHE_CLEAR_WARNING_LABEL=Note: +RESID_PREF_CACHE_CLEAR_WARNING_DESCRIPTION=Clearing the cache closes all open remote files + +#============================================================= +# SUPERTRANSFER PROGRESS MONITOR +#============================================================= +RESID_SUPERTRANSFER_PROGMON_MAIN=Compressed copy... +RESID_SUPERTRANSFER_PROGMON_SUBTASK_CREATE=Creating temp archive +RESID_SUPERTRANSFER_PROGMON_SUBTASK_POPULATE=Populating temp archive +RESID_SUPERTRANSFER_PROGMON_SUBTASK_TRANSFER=Transferring temp archive +RESID_SUPERTRANSFER_PROGMON_SUBTASK_EXTRACT=Extracting temp archive +RESID_SUPERTRANSFER_PROGMON_ARCHIVE=archive + +#============================================================= +# SUPERTRANSFER PREFERENCE PAGE +#============================================================= +RESID_SUPERTRANSFER_PREFS_ENABLE=Enable fast folder transfer using data compression +RESID_SUPERTRANSFER_PREFS_TYPE_LABEL=Archive type +RESID_SUPERTRANSFER_PREFS_TYPE_TOOLTIP=Select an archive type to use for the transfer + +################################################################################## +############################ Compare menu item ############################# +################################################################################## +ACTION_COMPAREWITH_EACH_LABEL= Each Other +ACTION_COMPAREWITH_EACH_TOOLTIP= Compare remote resources to each other +ACTION_COMPAREWITH_HISTORY_LABEL= Local History... +ACTION_COMPAREWITH_HISTORY_TOOLTIP= Compare the local edition history of this resource + +################################################################################## +############################ Replace menu item ############################# +################################################################################## +ACTION_REPLACEWITH_HISTORY_LABEL= Local History... +ACTION_REPLACEWITH_HISTORY_TOOLTIP= Replace the remote file with a previous edition from it's local history + +################################################################################## +############################ Archive menu items ############################# +################################################################################## +ACTION_EXTRACT_LABEL=Extract +ACTION_EXTRACT_SUB_LABEL=Extract to %1 +ACTION_EXTRACT_TOOLTIP=Extract archive to current directory +ACTION_EXTRACT_TO_LABEL=Extract to... +ACTION_EXTRACT_TO_TOOLTIP=Extract archive to a specified directory + +ACTION_COMBINE_LABEL=Combine... +ACTION_COMBINE_TOOLTIP=Combine archives into a single archive + +ACTION_CONVERT_LABEL=Convert... +ACTION_CONVERT_TOOLTIP=Convert archives into another archive type + +ACTION_ADDTOARCHIVE_LABEL=Add To Archive... +ACTION_ADDTOARCHIVE_TOOLTIP=Add files to a new or existing archive + +################################################################################## +############################ Project menu item ############################# +################################################################################## +RESID_OPEN_FROM_ASSOCIATED_PROJECT=Open from Associated Project (&1) + +#============================================================= +# EXTRACT ARCHIVE TO DIALOG... +#============================================================= +RESID_EXTRACTTO_TITLE=Extract To +RESID_EXTRACTTO_PROMPT=Choose the destination for the contents of archive &1 + +#============================================================= +# COMBINE ARCHIVES DIALOG... +#============================================================= +RESID_COMBINE_TITLE=Combine Archives +RESID_COMBINE_PROMPT=Choose the destination for the combined archives +RESID_COMBINE_NAME_LABEL=Archive name +RESID_COMBINE_NAME_TOOLTIP=Enter a file name for the combined/converted archive +RESID_COMBINE_TYPE_LABEL=Archive type +RESID_COMBINE_TYPE_TOOLTIP=Select an archive type for the combined/converted archive + +#============================================================= +# CONVERT ARCHIVE DIALOG... +#============================================================= +RESID_CONVERT_TITLE=Convert Archive +RESID_CONVERT_PROMPT=Source archive: &1 +RESID_CONVERT_LOCATION=Select a destination folder for the converted copy of the archive: +RESID_CONVERT_NAMEANDTYPE=Select a new name and type for the converted copy of the archive: + +#============================================================= +# ADD TO ARCHIVE DIALOG... +#============================================================= +RESID_ADDTOARCHIVE_TITLE=Add to Archive +RESID_ADDTOARCHIVE_PROMPT=Choose a destination archive for the selected files, or create a new archive +RESID_ADDTOARCHIVE_LOCATION=Select a destination folder for the new archive, or the location of an existing archive: +RESID_ADDTOARCHIVE_NAMEANDTYPE=Select a name and type for the new archive, or enter an existing archive's name and type: +RESID_ADDTOARCHIVE_SAVEPATH_LABEL=Save full path info +RESID_ADDTOARCHIVE_SAVEPATH_TOOLTIP=Choose whether or not to preserve the full path of the selected files relative to each other when they are added to the archive. +RESID_ADDTOARCHIVE_RELATIVETO_LABEL=Save full path info relative to: +RESID_ADDTOARCHIVE_RELATIVETO_TOOLTIP=Choose the common directory from which relative paths will be determined. + +#============================================================= +# ACTIONS... +#============================================================= +ACTION_NEWFOLDER_LABEL=Folder +ACTION_NEWFOLDER_TOOLTIP=Create a new Folder +ACTION_SELECT_DIRECTORY_LABEL=Browse... +ACTION_SELECT_DIRECTORY_TOOLTIP=Select folder from remote system +ACTION_SELECT_FILE_LABEL=Browse... +ACTION_SELECT_FILE_TOOLTIP=Select file from remote system \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemAddFileListener.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemAddFileListener.java new file mode 100644 index 00000000000..a4dc3e6359c --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemAddFileListener.java @@ -0,0 +1,53 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; + +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; + +/** + * This is an interface used by the actions SystemSelectRemoteFileAction and SystemSelectRemoteFolderAction + * actions classes (and the dialog and form used by these) and enable the dialog's OK button to + * be replaced with an Add button. When the user selects and object or presses Add, the caller + * is informed and able to display a resulting message in the dialog's message line,and affect + * the enabled state of the Add button. + *

+ * If you call the enableAddButton method you must pass an object that implements this interface. + * The dialog will call you back when the user presses the Add button, so you can take + * appropriate action. + */ +public interface ISystemAddFileListener +{ + + /** + * The user has pressed the Add button. + * Do something appropriate with the request. + *

+ * If this action fails for some reason, or you wish to display a completion + * message, return message text that will be displayed in the dialog's message + * line. Else, return null. + */ + public Object addButtonPressed(IHost selectedConnection, IRemoteFile[] selectedObjects); + /** + * The user has selected a file or folder. Is this valid to be added? + *

+ * If so, return null. If not, return a string to display on the + * message line indicating why it is not valid, such as it already has + * been added. + */ + public Object okToEnableAddButton(IHost selectedConnection, IRemoteFile[] selectedObjects); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileConstants.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileConstants.java new file mode 100644 index 00000000000..3472d28d764 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileConstants.java @@ -0,0 +1,159 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; + +// TODO is this file still used or necessary? + +/** + * Constants used throughout the System plugin + */ +public interface ISystemFileConstants +{ +// public static final String PLUGIN_ID ="com.ibm.etools.systems"; + public static final String PLUGIN_ID ="org.eclipse.rse.files.ui"; + public static final String PREFIX = PLUGIN_ID+".files."; + // Icons + public static final String ICON_DIR = "icons"; + public static final String ICON_PATH = java.io.File.separator + ICON_DIR + java.io.File.separator; + public static final String ICON_SUFFIX = "Icon"; + public static final String ICON_EXT = ".gif"; + + // Resource Bundle ids + public static final String RESID_PREFIX = PREFIX+"ui."; + + // ------------------- + // DEFAULT FILTERS... + // ------------------- + public static final String RESID_FILTER_ROOTS = RESID_PREFIX + "RootsFileFilter.label"; + public static final String RESID_FILTER_ROOTFILES = RESID_PREFIX + "RootFileFilter.label"; + public static final String RESID_FILTER_ROOTFOLDERS= RESID_PREFIX + "RootFolderFilter.label"; + public static final String RESID_FILTER_DRIVES = RESID_PREFIX + "DrivesFileFilter.label"; + public static final String RESID_FILTER_HOME = RESID_PREFIX + "HomeFileFilter.label"; + public static final String RESID_FILTER_USERHOME = RESID_PREFIX + "UserHomeFileFilter.label"; + public static final String RESID_FILTER_MYHOME = RESID_PREFIX + "MyHomeFileFilter.label"; + // ------------------------- + // MISCELLANEOUS... + // ------------------------- + public static final String RESID_PROPERTY_FILE_FILTER_VALUE = RESID_PREFIX + "FileFilterProperty.value"; + + // ------------------------- + // WIZARDS... + // ------------------------- + + // New System File Filter wizard... + public static final String RESID_NEWFILEFILTER_PAGE1_TITLE = RESID_PREFIX+"NewFileFilter.page1.title"; + public static final String RESID_NEWFILEFILTER_PAGE1_DESCRIPTION = RESID_PREFIX+"NewFileFilter.page1.description"; + public static final String RESID_FILEFILTER_ROOT = RESID_PREFIX+"filefilter."; + public static final String RESID_FILEFILTER_NAME_ROOT = RESID_FILEFILTER_ROOT+"name."; + public static final String RESID_FILEFILTER_FOLDER_ROOT = RESID_FILEFILTER_ROOT+"folder."; + public static final String RESID_FILEFILTER_FILE_ROOT = RESID_FILEFILTER_ROOT+"file."; + public static final String RESID_FILEFILTER_STRING_ROOT = RESID_FILEFILTER_ROOT+"strings."; + + // New Filter String wizard... + public static final String RESID_NEWFILTERSTRING_TITLE = RESID_PREFIX+"NewFilterString.title"; + public static final String RESID_NEWFILTERSTRING_PAGE1_TITLE = RESID_PREFIX+"NewFilterString.page1.title"; + public static final String RESID_NEWFILTERSTRING_PAGE1_DESCRIPTION = RESID_PREFIX+"NewFilterString.page1.description"; + + // File Filter String Re-Usable form (used in dialog and wizard) + public static final String RESID_FILEFILTERSTRING_ROOT = RESID_PREFIX+"filefilterstring."; + public static final String RESID_FILEFILTERSTRING_FOLDER_ROOT = RESID_FILEFILTERSTRING_ROOT+"folder."; + public static final String RESID_FILEFILTERSTRING_FILE_ROOT = RESID_FILEFILTERSTRING_ROOT+"file."; + public static final String RESID_FILEFILTERSTRING_INCFOLDERS_ROOT = RESID_FILEFILTERSTRING_ROOT+"include.folders."; + public static final String RESID_FILEFILTERSTRING_INCFILES_ROOT = RESID_FILEFILTERSTRING_ROOT+"include.files."; + public static final String RESID_FILEFILTERSTRING_INCFILESONLY_ROOT = RESID_FILEFILTERSTRING_ROOT+"include.filesonly."; + public static final String RESID_FILEFILTERSTRING_BYFILENAME_ROOT = RESID_FILEFILTERSTRING_ROOT+"include.byfilename."; + public static final String RESID_FILEFILTERSTRING_BYFILETYPES_ROOT= RESID_FILEFILTERSTRING_ROOT+"include.byfiletypes."; + public static final String RESID_FILEFILTERSTRING_TYPES_ROOT = RESID_FILEFILTERSTRING_ROOT+"types."; + public static final String RESID_FILEFILTERSTRING_SELECTTYPES_ROOT= RESID_FILEFILTERSTRING_ROOT+"selectTypes."; + public static final String RESID_FILEFILTERSTRING_TEST_ROOT = RESID_FILEFILTERSTRING_ROOT+"test."; + // ------------------------- + // DIALOGS... + // ------------------------- + // Change System File Filter dialog... + public static final String RESID_CHGFILEFILTER_TITLE = RESID_PREFIX+"ChgFileFilter.title"; + // Change System File Filter String dialog... + public static final String RESID_CHGFILEFILTERSTRING_TITLE = RESID_PREFIX+"ChgFileFilterString.title"; + + // Select Directory dialog... + public static final String RESID_SELECTDIRECTORY_TITLE = RESID_PREFIX+"SelectDirectory.title"; + public static final String RESID_SELECTDIRECTORY_VERBAGE = RESID_PREFIX+"SelectDirectory.verbage."; + public static final String RESID_SELECTDIRECTORY_SELECT = RESID_PREFIX+"SelectDirectory.select."; + // Select File dialog... + public static final String RESID_SELECTFILE_TITLE = RESID_PREFIX+"SelectFile.title"; + public static final String RESID_SELECTFILE_VERBAGE = RESID_PREFIX+"SelectFile.verbage."; + public static final String RESID_SELECTFILE_SELECT = RESID_PREFIX+"SelectFile.select."; + + // Prompt for home folder dialog... + public static final String RESID_HOMEPROMPT_TITLE = RESID_PREFIX+"HomePrompt.title"; + public static final String RESID_HOMEPROMPT_VERBAGE = RESID_PREFIX+"HomePrompt.verbage."; + public static final String RESID_HOMEPROMPT_PROMPT_ROOT = RESID_PREFIX+"HomePrompt.prompt."; + + // ------------------------- + // ACTIONS... + // ------------------------- + public static final String ACTION_ID = RESID_PREFIX + "action."; + + public static final String ACTION_NEWFILEFILTER = ACTION_ID + "NewFilter"; + public static final String ACTION_NEWNESTEDFILEFILTER= ACTION_ID + "NewNestedFilter"; + public static final String ACTION_UPDATEFILEFILTER = ACTION_ID + "UpdateFilter"; + + public static final String ACTION_NEWFILEFILTERSTRING = ACTION_ID + "NewFilterString"; + public static final String ACTION_ADDFILEFILTERSTRING = ACTION_ID + "AddFilterString"; + public static final String ACTION_UPDATEFILEFILTERSTRING = ACTION_ID + "UpdateFilterString"; + public static final String ACTION_SELECTFILETYPES = ACTION_ID + "SelectFileTypes"; + + // ------------------------- + // WIDGETS... + // ------------------------- + public static final String WIDGET_ID = RESID_PREFIX + "widget."; + + public static final String WIDGET_FOLDER_ROOT = WIDGET_ID + "directory."; + public static final String WIDGET_BROWSE_ROOT = WIDGET_ID + "browse."; + + + // ------------------------- + // PROPERTY PAGES... + // ------------------------- + public static final String RESID_PP_FILE_ROOT = RESID_PREFIX+"pp.file."; + public static final String RESID_PP_FILE_TITLE = RESID_PP_FILE_ROOT+"title"; + public static final String RESID_PP_FILE_TYPE_ROOT = RESID_PP_FILE_ROOT+"type."; + public static final String RESID_PP_FILE_TYPE_FILE_VALUE = RESID_PP_FILE_ROOT+"type.file.value"; + public static final String RESID_PP_FILE_TYPE_FOLDER_VALUE = RESID_PP_FILE_ROOT+"type.folder.value"; + public static final String RESID_PP_FILE_TYPE_ROOT_VALUE = RESID_PP_FILE_ROOT+"type.root.value"; + public static final String RESID_PP_FILE_NAME_ROOT = RESID_PP_FILE_ROOT+"name."; + public static final String RESID_PP_FILE_PATH_ROOT = RESID_PP_FILE_ROOT+"path."; + public static final String RESID_PP_FILE_SIZE_ROOT = RESID_PP_FILE_ROOT+"size."; + public static final String RESID_PP_FILE_SIZE_VALUE = RESID_PP_FILE_ROOT+"size.value"; + public static final String RESID_PP_FILE_MODIFIED_ROOT = RESID_PP_FILE_ROOT+"modified."; + public static final String RESID_PP_FILE_READONLY_ROOT = RESID_PP_FILE_ROOT+"readonly."; + public static final String RESID_PP_FILE_READABLE_ROOT = RESID_PP_FILE_ROOT+"readable."; + public static final String RESID_PP_FILE_WRITABLE_ROOT = RESID_PP_FILE_ROOT+"writable."; + public static final String RESID_PP_FILE_HIDDEN_ROOT = RESID_PP_FILE_ROOT+"hidden."; + + + // ------------------------------- + // Enter or select file form + // ------------------------------- + public static final String RESID_ENTER_OR_SELECT_FILE_PREFIX = RESID_PREFIX + "EnterOrSelectFile."; + public static final String RESID_ENTER_OR_SELECT_FILE_TITLE = RESID_ENTER_OR_SELECT_FILE_PREFIX + "title"; + public static final String RESID_ENTER_OR_SELECT_FILE_VERBAGE_LABEL = RESID_ENTER_OR_SELECT_FILE_PREFIX + "verbage.label"; + public static final String RESID_ENTER_OR_SELECT_FILE_ENTER_LABEL = RESID_ENTER_OR_SELECT_FILE_PREFIX + "enter.label"; + public static final String RESID_ENTER_OR_SELECT_FILE_ENTER_TOOLTIP = RESID_ENTER_OR_SELECT_FILE_PREFIX + "enter.tooltip"; + public static final String RESID_ENTER_OR_SELECT_FILE_SELECT_TOOLTIP = RESID_ENTER_OR_SELECT_FILE_PREFIX + "select.tooltip"; + public static final String RESID_ENTER_OR_SELECT_FILE_FILE_LABEL = RESID_ENTER_OR_SELECT_FILE_PREFIX + "file.label"; + public static final String RESID_ENTER_OR_SELECT_FILE_FILE_TOOLTIP = RESID_ENTER_OR_SELECT_FILE_PREFIX + "file.tooltip"; +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileMessages.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileMessages.java new file mode 100644 index 00000000000..3781fa65c8c --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/ISystemFileMessages.java @@ -0,0 +1,36 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; +/** + * Keys into the core plugin's resource bundle for error messages related + * to the remote file system framework. + */ +public interface ISystemFileMessages +{ + //public static final String PLUGIN_ID ="org.eclipse.rse.ui"; + //public static final String PLUGIN_ID =ISystemMessages.PLUGIN_ID; + // Message prefix + //public static final String FILEMSG_PREFIX = PLUGIN_ID+".ui.filemsg."; + + // Messages + //public static final String FILEMSG_VALIDATE_PREFIX = FILEMSG_PREFIX + "Validate."; + + public static final String FILEMSG_VALIDATE_FILEFILTERSTRING_EMPTY = "RSEF1006"; + public static final String FILEMSG_VALIDATE_FILEFILTERSTRING_NOTUNIQUE= "RSEF1007"; + public static final String FILEMSG_VALIDATE_FILEFILTERSTRING_NOTVALID = "RSEF1008"; + public static final String FILEMSG_VALIDATE_FILEFILTERSTRING_NOINCLUDES = "RSEF1009"; +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileFilterStringEditPane.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileFilterStringEditPane.java new file mode 100644 index 00000000000..ebaa67f3d8a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileFilterStringEditPane.java @@ -0,0 +1,823 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; + +import java.util.Vector; + +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.core.subsystems.ISubSystemConfiguration; +import org.eclipse.rse.files.ui.actions.SystemSelectFileTypesAction; +import org.eclipse.rse.files.ui.widgets.SystemFileWidgetHelpers; +import org.eclipse.rse.files.ui.widgets.SystemRemoteFolderCombo; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.ISystemFilterPoolManagerProvider; +import org.eclipse.rse.filters.ISystemFilterPoolReferenceManagerProvider; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSubSystemConfiguration; +import org.eclipse.rse.subsystems.files.core.util.ValidatorFileFilterString; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.actions.SystemTestFilterStringAction; +import org.eclipse.rse.ui.filters.SystemFilterStringEditPane; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.validators.ISystemValidator; +import org.eclipse.rse.ui.validators.ValidatorPathName; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + +/** + * The edit pane for page 1 of the New File Filter wizard. + * Prompts for the details of a single file filter string. + */ +public class SystemFileFilterStringEditPane + extends SystemFilterStringEditPane implements ISystemMessages +{ + // GUI widgets + protected Button filesOnlyCheckBox; + //protected Button testButton; + protected Button subsetByFileNameRadioButton, subsetByFileTypesRadioButton; + protected Button selectTypesButton; + protected Label labelFile, labelTypes; + protected Text textFile, textTypes; + protected SystemRemoteFolderCombo folderCombo; + // limits + protected int filterFileLength = 256; + protected int filterPathLength = 256; + // validators + protected ISystemValidator pathValidator = new ValidatorPathName(); + protected ISystemValidator fileValidator; + // inputs + protected boolean caseSensitive = false; + //protected boolean showTestButton = true; + protected String[] inputFilterStrings; + // state + protected boolean noValidation = false; + protected boolean callerInstanceOfWizardPage, callerInstanceOfSystemPromptDialog; + protected boolean skipUniquenessChecking; + protected boolean calledFromVerify; + protected boolean dontStealFocus; + protected RemoteFileSubSystemConfiguration inputSubsystemFactory = null; + + // actions + protected SystemTestFilterStringAction testAction = null; + protected SystemSelectFileTypesAction typesAction = null; + + + /** + * Constructor for SystemFileFilterStringEditPane. + * @param shell + */ + public SystemFileFilterStringEditPane(Shell shell) + { + super(shell); + } + + // ------------------------------ + // INPUT/CONFIGURATION METHODS... + // ------------------------------ + /** + * Set the contextual system filter pool reference manager provider. Will be non-null if the + * current selection is a reference to a filter pool or filter, or a reference manager + * provider (eg subsystem). + *

+ * Intercept of parent so we can extract the isCaseSensitive() value. + */ + public void setSystemFilterPoolReferenceManagerProvider(ISystemFilterPoolReferenceManagerProvider provider) + { + super.setSystemFilterPoolReferenceManagerProvider(provider); + if (provider != null) + caseSensitive = ((ISubSystem)provider).getSubSystemConfiguration().isCaseSensitive(); + } + /** + * Set the contextual system filter pool manager provider. Will be non-null if the + * current selection is a filter pool or filter or reference to either, or a manager + * provider itself (eg, subsystem factory). + *

+ * Intercept of parent so we can extract the isCaseSensitive() value. + */ + public void setSystemFilterPoolManagerProvider(ISystemFilterPoolManagerProvider provider) + { + super.setSystemFilterPoolManagerProvider(provider); + if (provider != null) + caseSensitive = ((ISubSystemConfiguration)provider).isCaseSensitive(); + } + + /** + * Call this to override the text limit for the filter name, from the default of 40. + */ + public void setFilterFileLength(int max) + { + filterFileLength = max; + if (textFile != null) + textFile.setTextLimit(max); + } + /** + * Call this to override the text limit for the filter name, from the default of 40. + */ + public void setFilterPathLength(int max) + { + filterPathLength = max; + if (folderCombo != null) + folderCombo.setTextLimit(max); + } + /** + * Existing strings are used to aid in uniqueness validation. + */ + public void setExistingStrings(String[] existingStrings, boolean caseSensitive) + { + this.inputFilterStrings = existingStrings; + this.caseSensitive = caseSensitive; + } + + // ------------------------------ + // LIFECYCLE METHODS... + // ------------------------------ + + /** + * Populate the pane with the GUI widgets + * @param parent + * @return Control + */ + public Control createContents(Composite parent) + { + int gridColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, gridColumns); + + // directory prompt + String historyKey = null; + if (refProvider != null) + historyKey = ((ISubSystem)refProvider).getSubSystemConfiguration().getId()+".filterStringDialog"; // unique to us + else + historyKey = "files.filterStringDialog"; // unique to us + + boolean readonly = false; + folderCombo = SystemFileWidgetHelpers.createFolderCombo(composite_prompts, null, gridColumns, historyKey, readonly); + folderCombo.setShowNewConnectionPrompt(false); + SystemWidgetHelpers.setHelp(folderCombo, SystemPlugin.HELPPREFIX+"ffsd0001"); + SystemWidgetHelpers.createLabel(composite_prompts," ",gridColumns); // FILLER + + // parent folder prompt + //textFolder = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, rb, RESID_FILEFILTERSTRING_FOLDER_ROOT); + + // "Subset by file name filter" radiobutton + subsetByFileNameRadioButton = SystemWidgetHelpers.createRadioButton(composite_prompts, null, SystemFileResources.RESID_FILEFILTERSTRING_BYFILENAME_LABEL, SystemFileResources.RESID_FILEFILTERSTRING_BYFILENAME_TOOLTIP); + //SystemWidgetHelpers.setHelp(subsetByFileNameRadioButton, SystemPlugin.HELPPREFIX+"ffsd0002", SystemPlugin.HELPPREFIX+"ffsd0003"); + SystemWidgetHelpers.setHelp(subsetByFileNameRadioButton, SystemPlugin.HELPPREFIX+"ffsd0002"); + updateGridData(subsetByFileNameRadioButton, gridColumns); + + // File name prompt + //textFile = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, rb, RESID_FILEFILTERSTRING_FILE_ROOT); + String indent = " "; + String temp = SystemWidgetHelpers.appendColon(SystemFileResources.RESID_FILEFILTERSTRING_FILE_LABEL); + labelFile = SystemWidgetHelpers.createLabel(composite_prompts, indent+temp); + labelFile.setToolTipText(SystemFileResources.RESID_FILEFILTERSTRING_FILE_TOOLTIP); + textFile = SystemWidgetHelpers.createTextField(composite_prompts, null); + textFile.setToolTipText(SystemFileResources.RESID_FILEFILTERSTRING_FILE_TOOLTIP); + //SystemWidgetHelpers.setHelp(textFile, SystemPlugin.HELPPREFIX+"ffsd0003",SystemPlugin.HELPPREFIX+"ffsd0002"); + SystemWidgetHelpers.setHelp(textFile, SystemPlugin.HELPPREFIX+"ffsd0003"); + updateGridData(textFile, gridColumns-1); + textFile.setText("*"); + + + // "Subset by file types filter" radiobutton + subsetByFileTypesRadioButton = SystemWidgetHelpers.createRadioButton(composite_prompts, null, SystemFileResources.RESID_FILEFILTERSTRING_BYFILETYPES_LABEL, SystemFileResources.RESID_FILEFILTERSTRING_BYFILETYPES_TOOLTIP); + //SystemWidgetHelpers.setHelp(subsetByFileTypesRadioButton, SystemPlugin.HELPPREFIX+"ffsd0004", SystemPlugin.HELPPREFIX+"ffsd0005"); + SystemWidgetHelpers.setHelp(subsetByFileTypesRadioButton, SystemPlugin.HELPPREFIX+"ffsd0004"); + updateGridData(subsetByFileTypesRadioButton, gridColumns); + + // File types prompt + Composite typesGroup = SystemWidgetHelpers.createComposite(composite_prompts, 3); + //SystemWidgetHelpers.setHelp(typesGroup, SystemPlugin.HELPPREFIX+"ffsd0005",SystemPlugin.HELPPREFIX+"ffsd0004"); + SystemWidgetHelpers.setHelp(typesGroup, SystemPlugin.HELPPREFIX+"ffsd0005"); + GridLayout layout = (GridLayout)typesGroup.getLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + updateGridData(typesGroup, gridColumns); + temp = SystemWidgetHelpers.appendColon(SystemFileResources.RESID_FILEFILTERSTRING_TYPES_LABEL); + labelTypes = SystemWidgetHelpers.createLabel(typesGroup, indent+temp); + labelTypes.setToolTipText(SystemFileResources.RESID_FILEFILTERSTRING_TYPES_TOOLTIP); + textTypes = SystemWidgetHelpers.createReadonlyTextField(typesGroup); + textTypes.setToolTipText(SystemFileResources.RESID_FILEFILTERSTRING_TYPES_TOOLTIP); + updateGridData(textTypes, 1); + selectTypesButton = SystemWidgetHelpers.createPushButton(typesGroup, null, SystemFileResources.RESID_FILEFILTERSTRING_SELECTTYPES_LABEL, SystemFileResources.RESID_FILEFILTERSTRING_SELECTTYPES_TOOLTIP); + GridData data = (GridData)selectTypesButton.getLayoutData(); + data.grabExcessHorizontalSpace = false; + data.horizontalAlignment = GridData.FILL; + + + /* + // Include Folders check box + subdirCheckBox = SystemWidgetHelpers.createCheckBox(composite_prompts, gridColumns, null, + rb, RESID_FILEFILTERSTRING_INCFOLDERS_ROOT); + subdirCheckBox.addSelectionListener(this); + + // Include Files check box + fileCheckBox = SystemWidgetHelpers.createCheckBox(composite_prompts, gridColumns, null, + rb, RESID_FILEFILTERSTRING_INCFILES_ROOT); + fileCheckBox.addSelectionListener(this); + */ + + // Show Files Only check box + SystemWidgetHelpers.createLabel(composite_prompts," ",gridColumns); // FILLER + filesOnlyCheckBox = SystemWidgetHelpers.createCheckBox(composite_prompts, gridColumns, null, + SystemFileResources.RESID_FILEFILTERSTRING_INCFILESONLY_LABEL, SystemFileResources.RESID_FILEFILTERSTRING_INCFILESONLY_TOOLTIP); + SystemWidgetHelpers.setHelp(filesOnlyCheckBox, SystemPlugin.HELPPREFIX+"ffsd0006"); + + // Test button + /* + if (showTestButton) + { + SystemWidgetHelpers.createLabel(composite_prompts," ",gridColumns); // FILLER + SystemWidgetHelpers.createLabel(composite_prompts," ",gridColumns); // FILLER + createTestButton(composite_prompts, RESID_FILEFILTERSTRING_TEST_ROOT); + SystemWidgetHelpers.setHelp(testButton, SystemPlugin.HELPPREFIX+"ffsd0007"); + updateGridData(testButton, gridColumns); + } + */ + + folderCombo.setFocus(); + + if (refProvider != null) + inputSubsystemFactory = (RemoteFileSubSystemConfiguration)((ISubSystem)refProvider).getSubSystemConfiguration(); + else if (provider != null) + inputSubsystemFactory = (RemoteFileSubSystemConfiguration)provider; + pathValidator = inputSubsystemFactory.getPathValidator(); + fileValidator = inputSubsystemFactory.getFileFilterStringValidator(); + if (refProvider != null) + folderCombo.setSystemConnection(((ISubSystem)refProvider).getHost()); + else if (inputSubsystemFactory != null) + folderCombo.setSystemTypes(inputSubsystemFactory.getSystemTypes()); + folderCombo.setSubSystem((IRemoteFileSubSystem)refProvider); + folderCombo.setTextLimit(filterPathLength); + textFile.setTextLimit(filterFileLength); + + resetFields(); + doInitializeFields(); + + folderCombo.addModifyListener( + new ModifyListener() { + public void modifyText(ModifyEvent e) { + validateFolderInput(); + } + } + ); + textFile.addModifyListener( + new ModifyListener() { + public void modifyText(ModifyEvent e) { + validateFileInput(); + } + } + ); + + subsetByFileNameRadioButton.addSelectionListener(this); + subsetByFileTypesRadioButton.addSelectionListener(this); + selectTypesButton.addSelectionListener(this); + filesOnlyCheckBox.addSelectionListener(this); + + return composite_prompts; + } + private void updateGridData(Control widget, int gridColumns) + { + GridData data = (GridData)widget.getLayoutData(); + data.horizontalSpan = gridColumns; + data.grabExcessHorizontalSpace = true; + data.horizontalAlignment = GridData.FILL; + } + + /** + * Return the control to recieve initial focus. Should be overridden if you override createContents + */ + public Control getInitialFocusControl() + { + return folderCombo.getCombo(); + } + + /** + * Override of parent. + * Called after reset fields, at first create time or when input is reset to a non-null value. + */ + protected void doInitializeFields() + { + if (folderCombo == null) + return; + //if (refProvider == null) + //SystemPlugin.logError("Programming Error: input subsystem is not set for SystemFileFilterStringEditPane",null); + + if (inputFilterString != null) + { + RemoteFileFilterString rffs = new RemoteFileFilterString(inputSubsystemFactory, inputFilterString); + String defaultPath = rffs.getPath(); + folderCombo.setText((defaultPath==null) ? "" : defaultPath); + String defaultFile = rffs.getFile(); + textFile.setText((defaultFile==null) ? "" : defaultFile); + String defaultTypes = rffs.getTypesAsString(); + textTypes.setText((defaultTypes==null) ? "" : defaultTypes); + boolean defaultIncludeFilesOnly = rffs.getShowFiles() && !rffs.getShowSubDirs(); + boolean defaultSubsetByFileName = !rffs.getFilterByTypes(); + // set appropriate radio button for subset type + subsetByFileNameRadioButton.setSelection(defaultSubsetByFileName); + subsetByFileTypesRadioButton.setSelection(!defaultSubsetByFileName); + filesOnlyCheckBox.setSelection(defaultIncludeFilesOnly); + enableFields(defaultSubsetByFileName); + } + } + /** + * This is called in the change filter dialog when the user selects "new", or selects another string. + * You must override this if you override createContents. Be sure to test if the contents have even been created yet! + */ + protected void resetFields() + { + if (folderCombo == null) + return; + folderCombo.setText(""); + textFile.setText("*"); + textTypes.setText(""); + subsetByFileNameRadioButton.setSelection(true); + subsetByFileTypesRadioButton.setSelection(false); + filesOnlyCheckBox.setSelection(false); + enableFields(true); + } + + /** + * Must be overridden if createContents is overridden. + *

+ * This is called by the isComplete, to decide if the default information + * is complete enough to enable finish. It doesn't do validation, that will be done when + * finish is pressed. + */ + protected boolean areFieldsComplete() + { + if (folderCombo == null) + return false; + else + { + boolean filterGiven = false; + boolean subsetByFileName = false; + String fileNameText = null; + + if (subsetByFileNameRadioButton.getSelection()) { + fileNameText = textFile.getText().trim(); + filterGiven = fileNameText.length() > 0; + subsetByFileName = true; + } + else { + filterGiven = textTypes.getText().trim().length() > 0; + subsetByFileName = false; + } + + String folderText = folderCombo.getText().trim(); + + if (inputSubsystemFactory != null) { + + // KM: defect 53009. + // if input subsystem factory is Unix, then we can not allow empty path + if (inputSubsystemFactory.isUnixStyle()) { + return folderText.length() > 0 && filterGiven; + } + // otherwise, if it is Windows + else { + + // check if folder path is empty + if (folderText.length() == 0) { + + // KM: defect 53210 + // if folder path empty, only valid filter is subset by file name and it + // must be wild card + if (subsetByFileName) { + return fileNameText.equals("*"); + } + // if we are not subsetting by file name, it is not valid + else { + return false; + } + } + // if folder path is not empty, we just make sure a subset is given + else { + return filterGiven; + } + } + } + // otherwise don't care about folder path + else { + return filterGiven; + } + } + } + /** + * Enable/disable fields dependent on radiobuttons + */ + private void enableFields(boolean byFileName) + { + labelTypes.setEnabled(!byFileName); + //textTypes.setEnabled(!byFileName); + selectTypesButton.setEnabled(!byFileName); + labelFile.setEnabled(byFileName); + textFile.setEnabled(byFileName); + } + + /** + * Get the action to run when "Select Types..." is pressed by the user + */ + protected SystemSelectFileTypesAction getSelectTypesAction() + { + if (typesAction == null) + typesAction = new SystemSelectFileTypesAction(selectTypesButton.getShell()); + return typesAction; + } + + + /** + * Completes processing of the wizard page or dialog. If this + * method returns true, the wizard/dialog will close; + * otherwise, it will stay active. + * + * @return error, if there is one + */ + public SystemMessage verify() + { + errorMessage = null; + Control controlInError = null; + calledFromVerify = true; + skipEventFiring = true; + + errorMessage = validateFolderInput(); + if (errorMessage != null) + controlInError = folderCombo; + + if (errorMessage == null) + { + if (subsetByFileNameRadioButton.getSelection()) + errorMessage = validateFileInput(); + else + { + if (textTypes.getText().trim().length() == 0) + { + errorMessage = SystemPlugin.getPluginMessage(FILEMSG_ERROR_NOFILETYPES); + } + } + controlInError = textFile; + } + if ((errorMessage == null) && (inputFilterStrings!=null) && !skipUniquenessChecking) + { + boolean notUnique = false; + String currFilterString = getFilterString(); + if (containsFilterString(currFilterString)) + notUnique = true; + if (notUnique) + { + errorMessage = SystemPlugin.getPluginMessage(FILEMSG_VALIDATE_FILEFILTERSTRING_NOTUNIQUE).makeSubstitution(currFilterString); + } + controlInError = textFile; + } + + if (errorMessage != null) + { + if (!dontStealFocus) + controlInError.setFocus(); + } + else + folderCombo.updateHistory(true); + + calledFromVerify = false; + skipEventFiring = false; + fireChangeEvent(errorMessage); + return errorMessage; + } + + /* + * + */ + private boolean containsFilterString(String newString) + { + if (inputFilterStrings == null) + return false; + else + { + for (int idx=0; idxISystemValidator object. + * If the ISystemValidator reports an error the error message is displayed + * in the Dialog's message line. + */ + protected SystemMessage validateFileInput() + { + if (noValidation || ignoreChanges) + return null; + + errorMessage = null; + + // first validate file name + if (fileValidator != null) + { + if (fileValidator instanceof ValidatorFileFilterString) + { + ValidatorFileFilterString fv = (ValidatorFileFilterString)fileValidator; + fv.setIsFileName(true); + } + + errorMessage = fileValidator.validate(textFile.getText().trim()); + } + + // if there is no error message, then validate that folder name is correct + // this fires a change event + if (errorMessage == null) { + errorMessage = validateFolderInput(); + } + // otherwise, simply fire change event + else { + fireChangeEvent(errorMessage); + } + + return errorMessage; + } + /** + * This hook method is called whenever the text changes in the input field. + * The default implementation delegates the request to an ISystemValidator object. + * If the ISystemValidator reports an error the error message is displayed + * in the Dialog's message line. + */ + protected SystemMessage validateFolderInput() + { + if (noValidation || ignoreChanges) + return null; + errorMessage= null; + + String folderComboText = folderCombo.getText().trim(); + + // first check if folder path is empty + if (folderComboText.length() == 0) { + + // KM: defect 53009. + // If the input subsystem factory is Unix, we do not allow empty folder path. + // Note that for Windows, it is perfectly valid to have an empty folder path, + // which indicates that the filter will resolve to show all the drives + if (inputSubsystemFactory != null) { + + if (inputSubsystemFactory.isUnixStyle()) { + + // let error message come from path validator + if (pathValidator != null) { + errorMessage = pathValidator.validate(folderComboText); + } + // no path validator, so just use default path empty message + else { + errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_PATH_EMPTY); + } + } + // KM: defect 53210 + // for Windows, check that subset by file name is selected + // and that it is wild card character + else { + + if (!subsetByFileNameRadioButton.getSelection() || !textFile.getText().trim().equals("*")) { + + // let error message come from path validator + if (pathValidator != null) { + errorMessage = pathValidator.validate(folderComboText); + } + // no path validator, so just use default path empty message + else { + errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_VALIDATE_PATH_EMPTY); + } + } + } + } + } + // otherwise go through path validator + else if (pathValidator != null) { + errorMessage = pathValidator.validate(folderComboText); + } + + fireChangeEvent(errorMessage); + return errorMessage; + } + + // ------------------------------ + // DATA EXTRACTION METHODS + // ------------------------------ + + /** + * Get the filter string in its current form. + * This should be overridden if createContents is overridden. + */ + public String getFilterString() + { + if (folderCombo == null) + return inputFilterString; + String folder = folderCombo.getText().trim(); + boolean subsetByFileName = subsetByFileNameRadioButton.getSelection(); + String file = null; + if (subsetByFileName) + file = textFile.getText().trim(); + else + file = textTypes.getText().trim(); + boolean showFilesOnly = filesOnlyCheckBox.getSelection(); + boolean showSubDirs = !showFilesOnly; //subdirCheckBox.getSelection(); + boolean showFiles = true; //fileCheckBox.getSelection(); + RemoteFileFilterString rffs = new RemoteFileFilterString(inputSubsystemFactory, folder, file); + rffs.setShowSubDirs(showSubDirs); + rffs.setShowFiles(showFiles); + //System.out.println("internalGetFilterString: showSubDirs = " + showSubDirs + ", showFiles = " + showFiles); + //System.out.println("... resulting string: " + rffs.toString()); + return rffs.toString(); + } + + // ------------------ + // EVENT LISTENERS... + // ------------------ + + /** + * User has selected something + */ + public void widgetSelected(SelectionEvent event) + { + Object src = event.getSource(); + dontStealFocus = true; + /* + else if (src == subdirCheckBox) + validateFileInput(); + else if (src == fileCheckBox) + validateFileInput(); + */ + if (src == filesOnlyCheckBox) + { + verify(); + } + else if (src == subsetByFileNameRadioButton) + { + verify(); + enableFields(true); + textFile.setFocus(); + } + else if (src == subsetByFileTypesRadioButton) + { + verify(); + enableFields(false); + selectTypesButton.setFocus(); + } + else if (src == selectTypesButton) + { + SystemSelectFileTypesAction typesAction = getSelectTypesAction(); + String typesString = textTypes.getText().trim(); + typesAction.setTypes(typesString); + typesAction.run(); + if (!typesAction.wasCancelled()) + { + typesString = typesAction.getTypesString(); + textTypes.setText(typesString); + dontStealFocus = false; + verify(); + } + } + dontStealFocus = false; + } + + /** + * Called by us or by owning dialog when common Test button is pressed + */ + public void processTest(Shell shell) + { + if (refProvider == null) + { + SystemBasePlugin.logWarning("Programming Error: input subsystem is not set"); + return; + } + skipUniquenessChecking = true; + if (verify() == null) + { + SystemTestFilterStringAction testAction = new SystemTestFilterStringAction(getShell()); + testAction.setSubSystem((ISubSystem)refProvider); + testAction.setFilterString(getFilterString()); + try + { + testAction.run(); + } + catch (Exception exc) + { + + SystemMessage msg = SystemMessageDialog.getExceptionMessage(getShell(), exc); + fireChangeEvent(msg); + } + } + skipUniquenessChecking = false; + } + + // ------------------------ + // STATIC HELPER METHODS... + // ------------------------ + + /** + * Reusable method to return a name validator for creating/update a file system filter string + * @param filter The system filter to which we are adding/updating a filter string. + * @param filterString The current filter object on updates. Can be null for new string. Used + * to remove from the existing string list the current filter string. + */ + public static ValidatorFileFilterString getFileFilterStringValidator(ISystemFilter filter, String filterString) + { + Vector v = filter.getFilterStringsVector(); + if (filterString != null) + v.removeElement(filterString); + IRemoteFileSubSystemConfiguration ssFactory = (IRemoteFileSubSystemConfiguration)filter.getProvider(); + ValidatorFileFilterString validator = new ValidatorFileFilterString(ssFactory,v); + return validator; + } + + /** + * Reusable method to return a name validator for creating/update a file system filter string. + * No unique checking. + */ + public static ValidatorFileFilterString getFileFilterStringValidator(IRemoteFileSubSystemConfiguration ssFactory) + { + return new ValidatorFileFilterString(ssFactory); + } + + /** + * If the file filter string is in new mode, and we have a non-Unix system, then if + * the folder name is empty and other fields are at default, we do not allow an implicit + * save through changing of filter string or pressing Ok button in the change filter pane. + * If in new mode for non-Unix system, and the user hasn't changed the other fields, + * we force user to use the Create button to create the filter string explicitly. + * @see org.eclipse.rse.ui.filters.SystemFilterStringEditPane#canSaveImplicitly() + */ + public boolean canSaveImplicitly() { + + // KM: defect 53009. + // check if subsystem factory is non Unix and we're in new mode + if (newMode && inputSubsystemFactory != null && !inputSubsystemFactory.isUnixStyle()) { + + // check that folder combo is empty + String folderComboText = folderCombo.getText().trim(); + + // if so, return false if other fields haven't changed + // So a user is not able to save with an empty folder path without + // explicitly pressing Create. + // Note that if we're changing an existing filter string, a user can save + // implicitly (i.e. without pressing Apply), by changing the filter + // string selection in the filter string list in SystemChangeFilterPane + // or by pressing Ok with pending changes. Same goes for a new filter + // string for which the user has changed the subset by file name + // or subset by file type fields. KM: defect 53210 + if (folderComboText.length() == 0 && + subsetByFileNameRadioButton.getSelection() && + textFile.getText().trim().equals("*")) { + return false; + } + else { + return super.canSaveImplicitly(); + } + } + else { + return super.canSaveImplicitly(); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileTreeAndListGroup.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileTreeAndListGroup.java new file mode 100644 index 00000000000..78f12cd849b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/SystemFileTreeAndListGroup.java @@ -0,0 +1,169 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileEmpty; +import org.eclipse.swt.widgets.Composite; + + + + +/** + * This is a private-use subclass of the internal Eclipse ResourceTreeAndListGroup + * composite widget. This is for selecting multiple local or remote files. It contains + * a checkbox tree on the left for selecting the folder, and a checkbox list on the + * right for selecting the files. + *

+ * We subclass this to add some slight additional functionality, including support for + * refreshing the contents. + */ +public class SystemFileTreeAndListGroup extends org.eclipse.ui.internal.ide.dialogs.ResourceTreeAndListGroup +{ + private Object rootObject = null; + private Object lastSelectedElement = null; + private ISelectionProvider selectionProvider = null; + // CONSTANTS + private static final RemoteFileEmpty EMPTYROOT = new RemoteFileEmpty(); + + /** + * Constructor when there is initial content + * @param parent org.eclipse.swt.widgets.Composite + * @param rootObject java.lang.Object + * @param treeContentProvider supplies the folders for the tree + * @param treeLabelProvider supplies the names and icons of the folders for the tree + * @param listContentProvider supplies the files for the tree + * @param listLabelProvider supplies the names and icons for the files for the list + * @param style int + * @param width int + * @param height int + */ + public SystemFileTreeAndListGroup(Composite parent,Object rootObject, + ITreeContentProvider treeContentProvider, ILabelProvider treeLabelProvider, + IStructuredContentProvider listContentProvider, ILabelProvider listLabelProvider, + int style,int width,int height) + { + // DKM - API change + //super(parent, rootObject, treeContentProvider, treeLabelProvider, + // listContentProvider, listLabelProvider, style, width, height); + super(parent, rootObject, treeContentProvider, treeLabelProvider, + listContentProvider, listLabelProvider, style, true); + + this.rootObject = rootObject; + } + /** + * Constructor when there is no initial content + * @param parent org.eclipse.swt.widgets.Composite + * @param treeContentProvider supplies the folders for the tree + * @param treeLabelProvider supplies the names and icons of the folders for the tree + * @param listContentProvider supplies the files for the tree + * @param listLabelProvider supplies the names and icons for the files for the list + * @param style int + * @param width int + * @param height int + */ + public SystemFileTreeAndListGroup(Composite parent, + ITreeContentProvider treeContentProvider, ILabelProvider treeLabelProvider, + IStructuredContentProvider listContentProvider, ILabelProvider listLabelProvider, + int style,int width,int height) + { + this(parent, EMPTYROOT, treeContentProvider, treeLabelProvider, + listContentProvider, listLabelProvider, style, width, height); + } + + + // does not work! The viewers are private, and the create methods don't return them!! + /** + * Create this group's list viewer. + * Override of parent so we can record locally the list viewer widget. + * + protected void createListViewer(Composite parent, int width, int height) + { + listViewer = super.createListViewer(parent, width, height); + return listViewer; + }*/ + + /** + * Refesh all the contents of the checkbox viewers + */ + public void refresh() + { + if (! (rootObject instanceof RemoteFileEmpty) ) + { + Object oldRoot = rootObject; + setRoot(EMPTYROOT); + setRoot(oldRoot); + /* + if ((selectionProvider!=null) && (oldRoot instanceof RemoteFileRootImpl)) + { + RemoteFileRootImpl root = (RemoteFileRootImpl)oldRoot; + IRemoteFile rootFile = root.getRootFile(); + if (rootFile != null) + super.selectionChanged(new SelectionChangedEvent(selectionProvider, + new StructuredSelection(oldRoot))); + } + */ + } + } + + /** + * Refesh the contents of the file-selection checkbox viewer. + */ + public void refreshFiles() + { + if (lastSelectedElement != null) + populateListViewer(lastSelectedElement); + } + + /** + * Handle the selection of an item in the tree viewer. + * Intercept of parent so we can record the last selected tree node. + * @param selection ISelection + */ + public void selectionChanged(SelectionChangedEvent event) + { + IStructuredSelection selection = (IStructuredSelection) event.getSelection(); + lastSelectedElement = selection.getFirstElement(); + selectionProvider = event.getSelectionProvider(); + super.selectionChanged(event); + } + + /** + * Set the root of the widget to be new Root. Regenerate all of the tables and lists from this + * value. + * Intercept of parent so we can refresh internal variables. + * @param newRoot + */ + public void setRoot(Object newRoot) + { + lastSelectedElement = null; + rootObject = newRoot; + super.setRoot(newRoot); + } + + /** + * Clear the contents + */ + public void clearAll() + { + setRoot(EMPTYROOT); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemAbstractRemoteFilePopupMenuExtensionAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemAbstractRemoteFilePopupMenuExtensionAction.java new file mode 100644 index 00000000000..83c71ed7f2b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemAbstractRemoteFilePopupMenuExtensionAction.java @@ -0,0 +1,141 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import java.util.Iterator; + +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.actions.SystemAbstractPopupMenuExtensionAction; +import org.eclipse.ui.IObjectActionDelegate; + + +/** + * This is a base class to simplify the creation of actions supplied via the + * com.ibm.etools.systems.core.popupMenus extension point, targeting remote files + * and/or remote folders. + *

+ * The only method you must implement is {@link #run()}. + * You may optionally override {@link #getEnabled(Object[])} + *

+ * Convenience methods available in this class: + *

+ *

+ * See also the convenience methods available in the parent class {@link SystemAbstractPopupMenuExtensionAction} + * + * @see org.eclipse.rse.ui.view.ISystemRemoteElementAdapter + * @see org.eclipse.rse.ui.dialogs.SystemPromptDialog + */ +public abstract class SystemAbstractRemoteFilePopupMenuExtensionAction + extends SystemAbstractPopupMenuExtensionAction + implements IObjectActionDelegate +{ + + /** + * Constructor + */ + public SystemAbstractRemoteFilePopupMenuExtensionAction() + { + super(); + } + + // ---------------------------------- + // OVERRIDABLE METHODS FROM PARENT... + // ---------------------------------- + + /** + * The user has selected this action. This is where the actual code for the action goes. + */ + public abstract void run(); + + /** + * The user has selected one or more objects. This is an opportunity to enable/disable + * this action based on the current selection. + *

+ * The default implementation of this method returns false if all the objects are not of + * type IRemoteFile. + */ + public boolean getEnabled(Object[] currentlySelected) + { + for (int idx=0; idx= 0; i--) + { + if (lcp.charAt(i) == separator) + { + relpaths.add(lcp.substring(0, i+1)); + } + } + String[] results = new String[relpaths.size()]; + for (int i = 0; i < relpaths.size(); i++) + { + results[i] = (String) relpaths.get(i); + } + return results; + } + + protected String getLowestCommonPath(String str1, String str2, boolean caseSensitive) + { + int maxLength = Math.min(str1.length(), str2.length()); + + for (int i = maxLength; i >= 0; i--) + { + if (str1.regionMatches(!caseSensitive, 0, str2, 0, i)) + { + return str1.substring(0, i); + } + } + return ""; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileAction.java new file mode 100644 index 00000000000..4fcaccc2aad --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileAction.java @@ -0,0 +1,52 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +/** + * Open a remote file as read-only + */ +public class SystemBrowseFileAction extends SystemEditFileAction { + + + /** + * Constructor for SystemBrowseFileAction. + * @param text + * @param tooltip + * @param image + * @param parent + * @param editorId + */ + public SystemBrowseFileAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId) { + super(text, tooltip, image, parent, editorId); + } + + /** + * @see org.eclipse.rse.files.ui.actions.SystemEditFileAction#process(IRemoteFile) + */ + protected void process(IRemoteFile remoteFile) { + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile, _editorId); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell(), true); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileLineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileLineAction.java new file mode 100644 index 00000000000..a12d7619eff --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemBrowseFileLineAction.java @@ -0,0 +1,55 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +/** + * Open a remote file as read-only + */ +public class SystemBrowseFileLineAction extends SystemEditFileLineAction { + + + /** + * Constructor for SystemBrowseFileAction. + * @param text + * @param tooltip + * @param image + * @param parent + * @param editorId + * @param line + */ + public SystemBrowseFileLineAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId, + IRemoteFile remoteFile, int line, int charStart, int charEnd) { + super(text, tooltip, image, parent, editorId, remoteFile, line, charStart, charEnd); + } + + /** + * @see org.eclipse.rse.files.ui.actions.SystemEditFileAction#process(IRemoteFile) + */ + protected void process(IRemoteFile remoteFile) { + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile, _editorId); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell(), true); + handleGotoLine(); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCombineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCombineAction.java new file mode 100644 index 00000000000..00d61787dc0 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCombineAction.java @@ -0,0 +1,172 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.CombineDialog; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class SystemCombineAction extends SystemExtractToAction { + + public SystemCombineAction(Shell parent) + { + super(parent, FileResources.ACTION_COMBINE_LABEL, FileResources.ACTION_COMBINE_TOOLTIP); + setHelp(SystemPlugin.HELPPREFIX + "actn0120"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_COMBINE_ID)); + + } + + public void run() + { + boolean repeat = true; + while (repeat) + { + IRemoteFile firstSelection = (IRemoteFile) _selected.get(0); + String title = FileResources.RESID_COMBINE_TITLE; + CombineDialog dialog = new CombineDialog(getShell(), title); + if (dialog == null) + return; + dialog.setNeedsProgressMonitor(false); + + dialog.setMessage(FileResources.RESID_COMBINE_PROMPT); + dialog.setShowNewConnectionPrompt(true); + dialog.setShowPropertySheet(true, false); + dialog.setSystemTypes(systemTypes); + + dialog.setPreSelection(firstSelection); + + dialog.setBlockOnOpen(true); + + int rc = dialog.open(); + + // if (rc != 0) NOT RELIABLE! + boolean cancelled = false; + if (dialog.wasCancelled()) cancelled = true; + + IRemoteFile destination = null; + IRemoteFileSubSystem destSS = null; + if (!cancelled) + { + destination = (IRemoteFile) dialog.getOutputObject(); + destSS = destination.getParentRemoteFileSubSystem(); + } + else + { + return; + } + if (destination == null) + { + System.out.println("blah"); + } + + if (ArchiveHandlerManager.isVirtual(destination.getAbsolutePath())) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COMBINETO_VIRTUAL_DEST); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + continue; + } + + if (destinationInSource(destination)) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DEST_NOT_IN_SOURCE); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + continue; + } + + try + { + if (!destination.exists()) destSS.createFile(destination); + } + catch (SystemMessageException e) + { + System.out.println(e.getMessage()); + } + for (int i = 0; i < _selected.size(); i++) + { + IRemoteFile selection = (IRemoteFile) _selected.get(i); + IRemoteFileSubSystem sourceSS = selection.getParentRemoteFileSubSystem(); + + IRunnableContext runnableContext = getRunnableContext(_parent); + String nextName = selection.getName(); + int j = nextName.lastIndexOf("."); + if (j != -1) + { + nextName = nextName.substring(0, j); + } + String nextDest = destination.getAbsolutePath() + ArchiveHandlerManager.VIRTUAL_SEPARATOR + nextName; + IRemoteFile nextDestination = null; + try + { + while (destSS.getRemoteFileObject(nextDest).exists()) + { + nextDest = nextDest + "1"; + } + nextDestination = destSS.getRemoteFileObject(nextDest); + destSS.createFolder(nextDestination); + } + catch (SystemMessageException e) + { + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), e.getSystemMessage()); + dlg.open(); + return; + } + + ExtractRunnable runnable = new ExtractRunnable(selection, nextDestination); + try + { + // currently we don't run this in a thread because + // in some cases dialogs are launched in the operation + // (widgets can only be legally used on the main thread) + runnableContext.run(false, true, runnable); // inthread, cancellable, IRunnableWithProgress + } + catch (java.lang.reflect.InvocationTargetException exc) + { + } + catch (java.lang.InterruptedException e) + { + } + } + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + registry.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, destination, destination.getParentPath(), destSS, null, null); + registry.fireEvent(new SystemResourceChangeEvent(destination, ISystemResourceChangeEvents.EVENT_REFRESH, destination.getParentPath())); + repeat = false; + } + return; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareFilesAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareFilesAction.java new file mode 100644 index 00000000000..a7d6acdf2ca --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareFilesAction.java @@ -0,0 +1,121 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.compare.CompareConfiguration; +import org.eclipse.compare.CompareUI; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.compare.SystemCompareInput; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.swt.widgets.Shell; + + + +/** + * Compare two remote files + */ +public class SystemCompareFilesAction extends SystemBaseAction +{ + + + private List _selected; + + /** + * Constructor for SystemCompareFilesAction + * @param parent + */ + public SystemCompareFilesAction(Shell parent) + { + super(FileResources.ACTION_COMPAREWITH_EACH_LABEL, parent); + setToolTipText(FileResources.ACTION_COMPAREWITH_EACH_TOOLTIP); + _selected = new ArrayList(); + allowOnMultipleSelection(true); + } + + /** + * Compare two remote files + */ + public void run() + { + CompareConfiguration cc = new CompareConfiguration(); + cc.setProperty("org.eclipse.compare.internal.CONFIRM_SAVE_PROPERTY", new Boolean(false)); + SystemCompareInput fInput = new SystemCompareInput(cc); + + for (int i = 0; i < _selected.size(); i++) + { + IRemoteFile file = (IRemoteFile) _selected.get(i); + SystemEditableRemoteFile ef = new SystemEditableRemoteFile(file); + fInput.addRemoteEditable(ef); + } + + CompareUI.openCompareEditor(fInput); + } + + /** + * Called when the selection changes in the systems view. This determines + * the input object for the command and whether to enable or disable + * the action. + * + * @param selection the current seleciton + * @return whether to enable or disable the action + */ + public boolean updateSelection(IStructuredSelection selection) + { + _selected.clear(); + boolean enable = false; + + Iterator e = ((IStructuredSelection) selection).iterator(); + while (e.hasNext()) + { + Object selected = e.next(); + + if (selected != null && selected instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) selected; + if (file.isFile()) + { + _selected.add(file); + if (_selected.size() == 2) + { + enable = true; + } + else + { + enable = false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + + return enable; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareWithEditionAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareWithEditionAction.java new file mode 100644 index 00000000000..61dab8f9260 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCompareWithEditionAction.java @@ -0,0 +1,38 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.compare.internal.ICompareContextIds; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.swt.widgets.Shell; + + + +public class SystemCompareWithEditionAction extends SystemEditionAction +{ + + public SystemCompareWithEditionAction(Shell parent) + { + super(parent, + FileResources.ACTION_COMPAREWITH_HISTORY_LABEL, + FileResources.ACTION_COMPAREWITH_HISTORY_TOOLTIP, + "org.eclipse.compare.internal.CompareWithEditionAction", + false); + + this.fHelpContextId= ICompareContextIds.COMPARE_WITH_EDITION_DIALOG; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemConvertAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemConvertAction.java new file mode 100644 index 00000000000..aab9317462d --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemConvertAction.java @@ -0,0 +1,180 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.CombineDialog; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.swt.widgets.Shell; + + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class SystemConvertAction extends SystemExtractToAction { + + public SystemConvertAction(Shell parent) + { + super(parent, FileResources.ACTION_CONVERT_LABEL, FileResources.ACTION_CONVERT_TOOLTIP); + setHelp(SystemPlugin.HELPPREFIX + "actn0121"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_CONVERT_ID)); + + } + + public void run() + { + for (int i = 0; i < _selected.size(); i++) + { + IRemoteFile selection = (IRemoteFile) _selected.get(i); + String title = FileResources.RESID_CONVERT_TITLE; + CombineDialog dialog = new CombineDialog(getShell(), title, true); + if (dialog == null) + return; + dialog.setNeedsProgressMonitor(false); + String message = SystemMessage.sub(FileResources.RESID_CONVERT_PROMPT, "&1", selection.getAbsolutePath()); + dialog.setMessage(message); + dialog.setShowNewConnectionPrompt(true); + dialog.setShowPropertySheet(true, false); + dialog.setSystemTypes(systemTypes); + + dialog.setPreSelection(selection); + + dialog.setBlockOnOpen(true); + dialog.setHelp(SystemPlugin.HELPPREFIX + "cnvd0000"); + dialog.setShowLocationPrompt(true); + dialog.setLocationPrompt(FileResources.RESID_CONVERT_LOCATION); + dialog.setNameAndTypePrompt(FileResources.RESID_CONVERT_NAMEANDTYPE); + dialog.setSelectionValidator(this); + + int rc = dialog.open(); + + // if (rc != 0) NOT RELIABLE! + boolean cancelled = false; + if (dialog.wasCancelled()) cancelled = true; + + IRemoteFile destination = null; + IRemoteFileSubSystem destSS = null; + if (!cancelled) + { + destination = (IRemoteFile) dialog.getOutputObject(); + destSS = destination.getParentRemoteFileSubSystem(); + } + else + { + return; + } + if (destination == null) + { + System.out.println("blah"); + } + + if (ArchiveHandlerManager.isVirtual(destination.getAbsolutePath())) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_CONVERTTO_VIRTUAL_DEST); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + i--; + continue; + } + if (!destination.canWrite()) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DEST_TARGET_READONLY); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + i--; + continue; + } + if (selection.isAncestorOf(destination)) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DEST_NOT_IN_SOURCE); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + i--; + continue; + } + + try + { + if (destination.exists()) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_UPLOAD_FILE_EXISTS); + msg.makeSubstitution(destination.getName()); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + boolean ok = dlg.openQuestionNoException(); + if (ok) + { + if (destination.getAbsolutePath().equals(selection.getAbsolutePath())) + { + continue; + } + destSS.delete(destination, null); + } + else + { + i--; + continue; + } + } + destSS.createFile(destination); + } + catch (SystemMessageException e) + { + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), e.getSystemMessage()); + dlg.open(); + continue; + } + IRemoteFileSubSystem sourceSS = selection.getParentRemoteFileSubSystem(); + + IRunnableContext runnableContext = getRunnableContext(_parent); + + ExtractRunnable runnable = new ExtractRunnable(selection, destination); + try + { + // currently we don't run this in a thread because + // in some cases dialogs are launched in the operation + // (widgets can only be legally used on the main thread) + runnableContext.run(false, true, runnable); // inthread, cancellable, IRunnableWithProgress + } + catch (java.lang.reflect.InvocationTargetException exc) + { + } + catch (java.lang.InterruptedException e) + { + } + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + registry.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, destination, destination.getParentPath(), destSS, null, null); + registry.fireEvent(new SystemResourceChangeEvent(destination, ISystemResourceChangeEvents.EVENT_REFRESH, destination.getParentPath())); + } + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCopyRemoteFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCopyRemoteFileAction.java new file mode 100644 index 00000000000..0baaec720d5 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCopyRemoteFileAction.java @@ -0,0 +1,493 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import java.util.Iterator; +import java.util.Vector; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.files.ui.resources.SystemRemoteEditManager; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.util.ValidatorFileUniqueName; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.rse.ui.actions.SystemBaseCopyAction; +import org.eclipse.rse.ui.dialogs.SystemRenameSingleDialog; +import org.eclipse.rse.ui.dialogs.SystemSimpleContentElement; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.SystemView; +import org.eclipse.swt.widgets.Shell; + + +/** + * Copy selected files and folders action. + */ +public class SystemCopyRemoteFileAction extends SystemBaseCopyAction + implements ISystemMessages, IValidatorRemoteSelection +{ + protected IRemoteFile targetFolder, targetFileOrFolder = null; + protected IRemoteFile firstSelection = null; + protected IRemoteFile firstSelectionParent = null; + protected IRemoteFile[] files; + protected Vector copiedFiles = new Vector(); + protected IHost sourceConnection; + protected IRemoteFileSubSystem ss; + + /** + * Constructor + */ + public SystemCopyRemoteFileAction(Shell shell) + { + this(shell, MODE_COPY); + } + /** + * Constructor for subclass + */ + SystemCopyRemoteFileAction(Shell shell, int mode) + { + super(shell, mode); + setHelp(SystemPlugin.HELPPREFIX+"actn0110"); + setDialogHelp(SystemPlugin.HELPPREFIX+"dcrf0000"); + } + + /** + * Reset. This is a re-run of this action + */ + protected void reset() + { + //System.out.println("inside remote file copy reset()"); + super.reset(); + targetFolder = null; + targetFileOrFolder = null; + firstSelection = null; + firstSelectionParent = null; + files = null; + copiedFiles = new Vector(); + sourceConnection = null; + ss = null; + } + + /** + * We override from parent to do unique checking... + *

+ * We simply ensure every selected object is an IRemoteFile + *

+ * @see SystemBaseAction#updateSelection(IStructuredSelection) + */ + public boolean updateSelection(IStructuredSelection selection) + { + boolean enable = true; + Iterator e= ((IStructuredSelection) selection).iterator(); + while (enable && e.hasNext()) + { + Object selectedObject = e.next(); + if (!(selectedObject instanceof IRemoteFile)) + enable = false; + } + return enable; + } + + // -------------------------- + // PARENT METHOD OVERRIDES... + // -------------------------- + + /** + * @see SystemBaseCopyAction#checkForCollision(Shell, IProgressMonitor, Object, Object, String) + * @param shell Window to host dialog + * @param monitor Usually not needed + * @param targetContainer will be the IRemoteFile folder selected to copy into + * @param oldObject will be the IRemoteFile object currently being copied + * @param oldName will be the name of the IRemoteFile object currently being copied + */ + protected String checkForCollision(Shell shell, IProgressMonitor monitor, + Object targetContainer, Object oldObject, String oldName) + { + String newName = oldName; + + try { + targetFolder = (IRemoteFile)targetContainer; + ss = targetFolder.getParentRemoteFileSubSystem(); + targetFileOrFolder = ss.getRemoteFileObject(targetFolder, oldName); + + + //SystemPlugin.logInfo("CHECKING FOR COLLISION ON '"+srcFileOrFolder.getAbsolutePath() + "' IN '" +targetFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...TARGET FILE: '"+tgtFileOrFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...target.exists()? "+tgtFileOrFolder.exists()); + if (targetFileOrFolder.exists()) + { + //monitor.setVisible(false); wish we could! + + // we no longer have to set the validator here... the common rename dialog we all now use queries the input + // object's system view adaptor for its name validator. See getNameValidator in SystemViewRemoteFileAdapter. phil + ValidatorFileUniqueName validator = null; // new ValidatorFileUniqueName(shell, targetFolder, srcFileOrFolder.isDirectory()); + //SystemCollisionRenameDialog dlg = new SystemCollisionRenameDialog(shell, validator, oldName); + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(shell, true, targetFileOrFolder, validator); // true => copy-collision-mode + dlg.open(); + if (!dlg.wasCancelled()) + newName = dlg.getNewName(); + else + newName = null; + } + } catch (SystemMessageException e) { + SystemBasePlugin.logError("SystemCopyRemoteFileAction.checkForCollision()", e); + } + + return newName; + } + + + /** + * @see SystemBaseCopyAction#doCopy(IProgressMonitor, Object, Object, String) + * @param monitor Usually not needed + * @param targetContainer will be the IRemoteFile folder selected to copy into + * @param oldObject will be the IRemoteFile object currently being copied + * @param newName will be the new name to give the oldObject on copy + */ + protected boolean doCopy(IProgressMonitor monitor, Object targetContainer, Object oldObject, String newName) + throws Exception + { + targetFolder = (IRemoteFile)targetContainer; + IRemoteFile srcFileOrFolder = (IRemoteFile)oldObject; + + IHost targetConnection = targetFolder.getSystemConnection(); + IHost srcConnection = srcFileOrFolder.getSystemConnection(); + + boolean ok = false; + if (targetConnection == srcConnection) + { + ss = targetFolder.getParentRemoteFileSubSystem(); + + + ok = ss.copy(srcFileOrFolder, targetFolder, newName, null); + if (!ok) + { + SystemMessage msg = SystemPlugin.getPluginMessage(FILEMSG_COPY_FILE_FAILED); + msg.makeSubstitution(srcFileOrFolder.getName()); + throw new SystemMessageException(msg); + } + else + { + String sep = targetFolder.getSeparator(); + String targetFolderName = targetFolder.getAbsolutePath(); + if (!targetFolderName.endsWith(sep)) + copiedFiles.addElement(targetFolderName+sep+newName); + else + copiedFiles.addElement(targetFolderName+newName); + } + } + // DKM - for cross system copy + else + { + IRemoteFileSubSystem targetFS = targetFolder.getParentRemoteFileSubSystem(); + IRemoteFileSubSystem srcFS = srcFileOrFolder.getParentRemoteFileSubSystem(); + String newPath = targetFolder.getAbsolutePath() + "/" + newName; + if (srcFileOrFolder.isFile()) + { + SystemRemoteEditManager mgr = SystemRemoteEditManager.getDefault(); + // if remote edit project doesn't exist, create it + if (!mgr.doesRemoteEditProjectExist()) + mgr.getRemoteEditProject(); + + StringBuffer path = new StringBuffer(mgr.getRemoteEditProjectLocation().makeAbsolute().toOSString()); + path = path.append("/" + srcFS.getSystemProfileName() + "/" + srcFS.getHostAliasName() + "/"); + + String absolutePath = srcFileOrFolder.getAbsolutePath(); + + + int colonIndex = absolutePath.indexOf(IPath.DEVICE_SEPARATOR); + + if (colonIndex != -1) + { + if (colonIndex == 0) + { + absolutePath = absolutePath.substring(1); + } + else if (colonIndex == (absolutePath.length() - 1)) + { + absolutePath = absolutePath.substring(0, colonIndex); + } + else + { + absolutePath = absolutePath.substring(0, colonIndex) + absolutePath.substring(colonIndex + 1); + } + } + + path = path.append(absolutePath); + + String tempFile = path.toString(); + + srcFS.download(srcFileOrFolder, tempFile, null); + targetFS.upload(tempFile, newPath, null); + } + else + { + + IRemoteFile newTargetFolder = targetFS.getRemoteFileObject(newPath); + targetFS.createFolder(newTargetFolder); + IRemoteFile[] children = srcFS.listFoldersAndFiles(srcFileOrFolder); + if (children != null) + { + for (int i = 0; i < children.length; i++) + { + IRemoteFile child = children[i]; + monitor.subTask("copying " + child.getName()); + doCopy(monitor, newTargetFolder, child, child.getName()); + monitor.worked(1); + } + } + } + } + + return ok; + } + + + /** + * Required parent class abstract method. + * Does not apply to us as we supply our own dialog for the copy-target + */ + protected SystemSimpleContentElement getTreeModel() + { + return null; + } + /** + * Required parent class abstract method. + * Does not apply to us as we supply our own dialog for the copy-target + */ + protected SystemSimpleContentElement getTreeInitialSelection() + { + return null; + } + + /** + * @see SystemBaseCopyAction#getOldObjects() + * Returns an array of IRemoteFile objects + */ + protected Object[] getOldObjects() + { + return getSelectedFiles(); + } + + /** + * @see SystemBaseCopyAction#getOldNames() + */ + protected String[] getOldNames() + { + IRemoteFile[] files = getSelectedFiles(); + String[] names = new String[files.length]; + for (int idx=0; idx 1) + reset(); + //return new SystemSimpleCopyDialog(parent, getPromptString(), mode, this, getTreeModel(), getTreeInitialSelection()); + String dlgTitle = (mode==MODE_COPY ? SystemResources.RESID_COPY_TITLE : SystemResources.RESID_MOVE_TITLE); + SystemSelectRemoteFileOrFolderDialog dlg = new SystemSelectRemoteFileOrFolderDialog(shell,dlgTitle,SystemSelectRemoteFileOrFolderDialog.FOLDER_MODE); + dlg.setNeedsProgressMonitor(true); + dlg.setMessage(getPromptString()); + dlg.setShowNewConnectionPrompt(false); + dlg.setShowPropertySheet(true, false); + firstSelection = getFirstSelectedFile(); + sourceConnection = firstSelection.getSystemConnection(); + dlg.setSystemConnection(sourceConnection); + if (mode==MODE_MOVE) + dlg.setSelectionValidator(this); + //SystemPlugin.logInfo("Calling getParentRemoteFile for '"+firstSelection.getAbsolutePath()+"'"); + firstSelectionParent = firstSelection.getParentRemoteFile(); + /* + if (firstSelectionParent != null) + SystemPlugin.logInfo("Result of getParentRemoteFile: '"+firstSelectionParent.getAbsolutePath()+"'"); + else + SystemPlugin.logInfo("Result of getParentRemoteFile: null"); + */ + dlg.setPreSelection(firstSelectionParent); + + // our title now reflects multiple selection. If single change it. + IStructuredSelection sel = getSelection(); + //System.out.println("size = "+sel.size()); + if (sel.size() == 1) + { + String singleTitle = null; + if (mode == MODE_COPY) + singleTitle = SystemResources.RESID_COPY_SINGLE_TITLE; + else + singleTitle = SystemResources.RESID_MOVE_SINGLE_TITLE; + //System.out.println("..."+singleTitle); + if (!singleTitle.startsWith("Missing")) // TODO: remove test after next mri rev + dlg.setTitle(singleTitle); + } + return dlg; + } + + /** + * Override this method if you supply your own copy/move target dialog. + * Return the user-selected target or null if cancelled + */ + protected Object getTargetContainer(Dialog dlg) + { + SystemSelectRemoteFileOrFolderDialog cpyDlg = (SystemSelectRemoteFileOrFolderDialog)dlg; + Object targetContainer = null; + if (!cpyDlg.wasCancelled()) + targetContainer = cpyDlg.getSelectedObject(); + return targetContainer; + } + + /** + * Called after all the copy/move operations end, be it successfully or not. + * Your opportunity to display completion or do post-copy selections/refreshes + */ + public void copyComplete() + { + if (copiedFiles.size() == 0) + return; + + // refresh all instances of this parent, and all affected filters... + ISubSystem fileSS = targetFolder.getParentRemoteFileSubSystem(); + Viewer originatingViewer = null; + if (getViewer() instanceof Viewer) + { + originatingViewer = (Viewer)getViewer(); + if (!targetFolder.getAbsolutePath().equals(firstSelectionParent.getAbsolutePath())) + { + // we select the first instance of the target folder now so that the copied members will be selected in it + // after it is refreshed via the remote_resource_created event. + if (originatingViewer instanceof SystemView) + { + boolean selectedOk = ((SystemView)originatingViewer).selectRemoteObjects(targetFolder.getAbsolutePath(), fileSS, null); + //System.out.println(targetFolder.getAbsolutePath()+" selectedOK? " + selectedOk); + //if (selectedOk) + // return; + } + } + } + SystemPlugin.getTheSystemRegistry().fireRemoteResourceChangeEvent( + ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, copiedFiles, targetFolder.getAbsolutePath(), fileSS, null, originatingViewer); + + /* Old release 1.0 way... + // did they copy to the same parent? Just refresh that parent, whatever it is... + if (targetFolder.getAbsolutePath().equals(firstSelectionParent.getAbsolutePath())) + { + Viewer v = getViewer(); + if (v instanceof ISystemTree) + { + SystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + ISystemTree tree = (ISystemTree)v; + Object parent = tree.getSelectedParent(); + if (parent == null) + return; + if (parent instanceof IRemoteFile) + // refresh parent in all views... + sr.fireEvent( + new org.eclipse.rse.model.SystemResourceChangeEvent( + parent,ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, null) + ); + else + // refresh parent in all views... + sr.fireEvent( + new org.eclipse.rse.model.SystemResourceChangeEvent( + parent,ISystemResourceChangeEvent.EVENT_REFRESH, null) + ); + // select new files in this view only + sr.fireEvent((ISystemResourceChangeListener)v, + new org.eclipse.rse.model.SystemResourceChangeEvent( + copiedFiles,ISystemResourceChangeEvent.EVENT_SELECT_REMOTE, targetFolder) + ); + } + } + // they copied somewhere else... a little more work... + else + { + // refresh target folder in all views, but only select new files in this view... + org.eclipse.rse.model.SystemResourceChangeEvent event = + new org.eclipse.rse.model.SystemResourceChangeEvent( + targetFolder,ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, copiedFiles); + event.setOriginatingViewer(getViewer()); + sr.fireEvent(event); + } + */ + } + + // ------------------ + // PRIVATE METHODS... + // ------------------ + + /** + * Get the currently selected IRemoteFile objects + */ + protected IRemoteFile[] getSelectedFiles() + { + if (files == null) + { + IStructuredSelection selection = (IStructuredSelection)getSelection(); + files = new IRemoteFile[selection.size()]; + Iterator i = selection.iterator(); + int idx=0; + while (i.hasNext()) + { + files[idx++] = (IRemoteFile)i.next(); + } + } + return files; + } + /** + * Get the first selected file or folder + */ + protected IRemoteFile getFirstSelectedFile() + { + if (files == null) + getSelectedFiles(); + if (files.length > 0) + return files[0]; + else + return null; + } + + /** + * The user has selected a remote object. Return null if OK is to be enabled, or a SystemMessage + * if it is not to be enabled. The message will be displayed on the message line. + *

+ * This is overridden in SystemMoveRemoteFileAction + */ + public SystemMessage isValid(IHost selectedConnection, Object[] selectedObjects, ISystemRemoteElementAdapter[] remoteAdaptersForSelectedObjects) + { + return null; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCreateEditActions.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCreateEditActions.java new file mode 100644 index 00000000000..97992c79270 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemCreateEditActions.java @@ -0,0 +1,271 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.text.Collator; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.resources.UniversalFileTransferUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.ISystemContextMenuConstants; +import org.eclipse.rse.ui.SystemMenuManager; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemSeparatorAction; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + +/** + * Class for creating edit actions + * @deprecated - use SystemRemoteFileOpenWithMenu now + * + */ +public class SystemCreateEditActions +{ + + + protected IEditorRegistry registry; + + /* + * Compares the labels from two IEditorDescriptor objects + */ + private static final Comparator comparer = new Comparator() { + private Collator collator = Collator.getInstance(); + + public int compare(Object arg0, Object arg1) { + String s1 = ((IEditorDescriptor)arg0).getLabel(); + String s2 = ((IEditorDescriptor)arg1).getLabel(); + return collator.compare(s1, s2); + } + }; + + /** + * Constructor for CreateEditActions + */ + public SystemCreateEditActions() { + super(); + registry = PlatformUI.getWorkbench().getEditorRegistry(); + } + + /** + * Create edit actions + */ + public void create(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) + { + + if (selection.size() <= 0) + return; + + // create basic open + createForAnySelection(menu, selection, shell, menuGroup); + + + // create open with-> + if (selection.size() == 1) + { + createForSingleSelection(menu, selection.getFirstElement(), shell, menuGroup); + } + else + { // editing is only allowed when there is only one selection + return; + } + } + + public void createForAnySelection(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) + { + String label = SystemResources.ACTION_CASCADING_OPEN_LABEL; + String tooltip = SystemResources.ACTION_CASCADING_OPEN_TOOLTIP; + SystemEditFilesAction action = new SystemEditFilesAction(label, tooltip, shell); + + // add action + menu.add(ISystemContextMenuConstants.GROUP_OPEN, action); + } + + + protected IEditorRegistry getEditorRegistry() + { + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); + } + + protected IEditorDescriptor getDefaultTextEditor() + { + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); + } + /** + * Create actions when one file has been selected. + */ + public void createForSingleSelection(SystemMenuManager menu, Object element, Shell shell, String menuGroup) { + IRemoteFile remoteFile = null; + + if ((element == null) || !(element instanceof IRemoteFile)) { + return; + } + else { + remoteFile = (IRemoteFile)element; + } + + IEditorDescriptor defaultEditor = getDefaultTextEditor(); + + IEditorDescriptor preferredEditor = getPreferredEditor(remoteFile); // may be null + + Object[] editors = registry.getEditors(remoteFile.getName()); + Collections.sort(Arrays.asList(editors), comparer); + + boolean defaultFound = false; + + //Check that we don't add it twice. This is possible + //if the same editor goes to two mappings. + ArrayList alreadyMapped = new ArrayList(); + + for (int i = 0; i < editors.length; i++) { + + IEditorDescriptor editor = (IEditorDescriptor) editors[i]; + + if (!alreadyMapped.contains(editor)) { + + createEditAction(menu, shell, remoteFile, editor, preferredEditor); + + // remember if we find default text editor + if (defaultEditor != null && editor.getId().equals(defaultEditor.getId())) { + defaultFound = true; + } + + alreadyMapped.add(editor); + } + } + + // only add a separator if there are associated editors + if (editors.length > 0) { + SystemSeparatorAction sep = new SystemSeparatorAction(shell); + menu.add(ISystemContextMenuConstants.GROUP_OPENWITH, sep); + } + + // add default text editor if it was not already associated + if (!defaultFound && defaultEditor != null) { + createEditAction(menu, shell, remoteFile, defaultEditor, preferredEditor); + } + + // add system editor (should never be null) + IEditorDescriptor descriptor = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + createEditAction(menu, shell, remoteFile, descriptor, preferredEditor); + + /* DKM - 56067 + // add system in-place editor (can be null) + descriptor = registry.findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); + + if (descriptor != null) { + createEditAction(menu, shell, remoteFile, descriptor, preferredEditor); + } + */ + + // TODO: default action + // createDefaultEditAction(menu, file); + } + + /** + * Creates an edit action for a specific editor. If the editor is the preferred editor, then it is selected. + * @param menu the menu manager. + * @param shell the shell. + * @param remoteFile the remote file. + * @param descriptor the editor descriptor. + * @param preferredEditor the descriptor of the preferred editor, or null. + */ + private void createEditAction(SystemMenuManager menu, Shell shell, IRemoteFile remoteFile, IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) { + String editorId = descriptor.getId(); + + String label = descriptor.getLabel(); + ImageDescriptor image = getImageDescriptor(remoteFile, descriptor); + + // create action + SystemEditFileAction action = new SystemEditFileAction(label, label, image, IAction.AS_RADIO_BUTTON, shell, editorId); + + // check if editor is the preferred editor + boolean isPreferred = preferredEditor != null && editorId.equals(preferredEditor.getId()); + + // mark action as checked or not + action.setChecked(isPreferred); + + // add action + menu.add(ISystemContextMenuConstants.GROUP_OPENWITH, action); + } + + + /** + * Returns the preferred editor for the remote file. If the remote file has a cached local resource, + * then returns the default editor associated with that resource, by calling IDE.getDefaultEditor(IFile). + * Otherwise, get the default editor associated with that remote file name from the editor registry. + * @param remoteFile the remote file. + * @return the preferred editor for the remote file, or null if none. + */ + private IEditorDescriptor getPreferredEditor(IRemoteFile remoteFile) { + + IFile localFile = getLocalResource(remoteFile); + + if (localFile == null) { + return registry.getDefaultEditor(remoteFile.getName()); + } + else { + return IDE.getDefaultEditor(localFile); + } + } + + /** + * Get the local cache of the remote file, or null if none. + * @param remoteFile the remote file. + * @return the local cached resource, or null if none. + */ + private IFile getLocalResource(IRemoteFile remoteFile) + { + return (IFile)UniversalFileTransferUtility.getTempFileFor(remoteFile); + } + + /** + * Returns the image descriptor for the given editor descriptor. If the editor descriptor is + * null, returns the image descriptor for the remote file name. + * @param remoteFile the remote file. + */ + private ImageDescriptor getImageDescriptor(IRemoteFile remoteFile, IEditorDescriptor editorDesc) { + ImageDescriptor imageDesc = null; + + if (editorDesc == null) { + imageDesc = registry.getImageDescriptor(remoteFile.getName()); + } + else { + imageDesc = editorDesc.getImageDescriptor(); + } + + if (imageDesc == null) { + + if (editorDesc.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) + imageDesc = registry.getSystemExternalEditorImageDescriptor(remoteFile.getName()); + } + + return imageDesc; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDoubleClickEditAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDoubleClickEditAction.java new file mode 100644 index 00000000000..0da3b5e3f42 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDoubleClickEditAction.java @@ -0,0 +1,97 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; + + +public class SystemDoubleClickEditAction extends SystemBaseAction +{ + + + + private Object element; + + /** + * Constructor for SystemDoubleClickEditAction + */ + public SystemDoubleClickEditAction(Object element) + { + super(null, null); + this.element = element; + } + + protected IEditorRegistry getEditorRegistry() + { + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); + } + + protected IEditorDescriptor getDefaultTextEditor() + { + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); + } + /** + * @see SystemBaseAction#run() + */ + public void run() + { + + IRemoteFile remoteFile = null; + + if ((element == null) || !(element instanceof IRemoteFile)) + return; + else + remoteFile = (IRemoteFile) element; + + /* DKM - use Eclipse default, instead + // open LPEX editor on double click if remote file is a text file + if (remoteFile.isText()) { + IEditorRegistry registry = WorkbenchPlugin.getDefault().getEditorRegistry(); + IEditorDescriptor descriptor = registry.findEditor(ISystemTextEditorConstants.SYSTEM_TEXT_EDITOR_ID); + String id = descriptor.getId(); + SystemEditFileAction editAction = new SystemEditFileAction(null, null, null, null, id); + editAction.setSelection(new StructuredSelection(element)); + editAction.run(); + } + else { // open the system editor on double click if remote file is a text file + SystemEditFilePlatformAction platformEditAction = new SystemEditFilePlatformAction(null, null, null, null); + platformEditAction.setSelection(new StructuredSelection(element)); + platformEditAction.run(); + } + */ + + // DKM, use Eclipse default + String fileName = remoteFile.getName(); + IEditorRegistry registry = getEditorRegistry(); + IEditorDescriptor descriptor = registry.getDefaultEditor(fileName); + if (descriptor == null) + { + descriptor = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + + } + String id = descriptor.getId(); + SystemEditFileAction editAction = new SystemEditFileAction(null, null, null, null, id); + editAction.setSelection(new StructuredSelection(element)); + editAction.run(); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDownloadConflictAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDownloadConflictAction.java new file mode 100644 index 00000000000..2116c36dfeb --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemDownloadConflictAction.java @@ -0,0 +1,293 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.window.Window; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.rse.ui.dialogs.SystemPromptDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + +/** + * This is the default action used to handle download conflicts + */ +public class SystemDownloadConflictAction extends SystemBaseAction implements Runnable +{ + + /** + * This is the default dialog used to handle download conflicts + */ + protected class DownloadConflictDialog extends SystemPromptDialog implements ISystemMessages + { + private Button _keepLocalButton; + private Button _replaceLocalButton; + + private boolean _keepLocal; + private String _openLocalText; + private String _replaceText; + private String _dialogText; + private String _helpId; + + /** + * Constructor. + * @param shell the parent shell of the dialog + * @param remoteNewer indicates whether the remote file has changed since it was last downloaded + */ + public DownloadConflictDialog(Shell shell, boolean remoteNewer) + { + super(shell, FileResources.RESID_CONFLICT_DOWNLOAD_TITLE); + } + + /** + * Return whether the user decided to keep the local cached file + * @returns the whether the user decided to keep the local cached file + */ + public boolean keepLocal() + { + return _keepLocal; + } + + /** + * Called when a button is pressed in the dialog + */ + protected void buttonPressed(int buttonId) + { + setReturnCode(buttonId); + _keepLocal = _keepLocalButton.getSelection(); + close(); + } + + /** + * Creates the dialog content + */ + public Control createInner(Composite parent) + { + Image image = getShell().getDisplay().getSystemImage(SWT.ICON_QUESTION); + + Composite c = new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + c.setLayout(layout); + c.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Composite m = new Composite(c, SWT.NONE); + + GridLayout mlayout = new GridLayout(); + mlayout.numColumns = 2; + m.setLayout(mlayout); + m.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Label label = new Label(m, 0); + image.setBackground(label.getBackground()); + label.setImage(image); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_BEGINNING)); + + Text text = new Text(m, SWT.WRAP | SWT.MULTI); + text.setEditable(false); + text.setText(_dialogText); + + Composite options = new Composite(c, SWT.NONE); + GridLayout olayout = new GridLayout(); + olayout.numColumns = 1; + options.setLayout(olayout); + options.setLayoutData(new GridData(GridData.FILL_BOTH)); + + _replaceLocalButton = new Button(options, SWT.RADIO); + _replaceLocalButton.setText(_replaceText); + _replaceLocalButton.setSelection(true); + + _keepLocalButton = new Button(options, SWT.RADIO); + _keepLocalButton.setText(_openLocalText); + + setHelp(); + return c; + } + + /** + * Returns the initial focus control + * @return the initial focus control + */ + protected Control getInitialFocusControl() + { + enableOkButton(true); + return _replaceLocalButton; + } + + private void setHelp() + { + setHelp(_helpId); + } + + /** + * Sets the help id for this dialog + * @param id the help id + */ + public void setHelpId(String id) + { + _helpId= id; + } + + /** + * Sets the dialog message + * @param dialogText the dialog message + */ + public void setDialogText(String dialogText) + { + _dialogText = dialogText; + } + + /** + * Sets the dialog action message for replacing the local file with the remote file + * @param replaceText the dialog action message for replacing the local file + */ + public void setReplaceText(String replaceText) + { + _replaceText = replaceText; + } + + /** + * Sets the dialog action message for keeping the local file + * @param openLocalText the dialog action message for keeping the local file + */ + public void setOpenLocalText(String openLocalText) + { + _openLocalText = openLocalText; + } + + } + + protected IFile _tempFile; + protected boolean _remoteNewer; + protected int _state; + + public static final int REPLACE_WITH_REMOTE = 0; + public static final int OPEN_WITH_LOCAL = 1; + public static final int CANCELLED = 2; + + /** + * Constructor. + * @param tempFile the cached local file that is in conflict with the remote file + * @param remoteNewer indicates whether the remote file has changed since it was last downloaded + */ + public SystemDownloadConflictAction(IFile tempFile, boolean remoteNewer) + { + super(FileResources.RESID_CONFLICT_DOWNLOAD_TITLE, null); + _tempFile = tempFile; + _remoteNewer = remoteNewer; + } + + /** + * Constructor. + * @param title the title for the action + * @param tempFile the cached local file that is in conflict with the remote file + * @param remoteNewer indicates whether the remote file has changed since it was last downloaded + */ + public SystemDownloadConflictAction(String title, IFile tempFile, boolean remoteNewer) + { + super(title, null); + _tempFile = tempFile; + _remoteNewer = remoteNewer; + } + + /** + * Returns the action taken in response to the conflict. The state may be one of the following: + *

+ * @return the response to the conflict + */ + public int getState() + { + return _state; + } + + /** + * Returns the dialog used to prompt a user on how to resolve a conflict. + * @returns the dialog + */ + protected DownloadConflictDialog getConflictDialog() + { + DownloadConflictDialog dlg = new DownloadConflictDialog(SystemBasePlugin.getActiveWorkbenchShell(), _remoteNewer); + + if (_remoteNewer) + { + dlg.setDialogText(FileResources.RESID_CONFLICT_DOWNLOAD_MESSAGE_REMOTECHANGED); + } + else + { + dlg.setDialogText(FileResources.RESID_CONFLICT_DOWNLOAD_MESSAGE_LOCALCHANGED); + } + + dlg.setReplaceText(FileResources.RESID_CONFLICT_DOWNLOAD_REPLACELOCAL); + dlg.setOpenLocalText(FileResources.RESID_CONFLICT_DOWNLOAD_OPENWITHLOCAL); + dlg.setHelpId(SystemPlugin.HELPPREFIX + "lcdl0000"); + return dlg; + } + + /** + * Called when this action is invoked + */ + public void run() + { + setShell(SystemPlugin.getTheSystemRegistry().getShell()); + SystemIFileProperties properties = new SystemIFileProperties(_tempFile); + + DownloadConflictDialog cnfDialog = getConflictDialog(); + if (cnfDialog.open() == Window.OK) + { + // does user want to open local or replace local with remote? + if (cnfDialog.keepLocal()) + { + // user wants to keep the local version + // don't synchronize with server, save that for the save operation + _state = OPEN_WITH_LOCAL; + } + else + { + // user wants to replace local copy with the remote version + _state = REPLACE_WITH_REMOTE; + } + + } + else + { + _state = CANCELLED; + + // cancelled dialog, so no remote synchronization + // set dirty flag! + properties.setDirty(true); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileAction.java new file mode 100644 index 00000000000..140f5cdea6a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileAction.java @@ -0,0 +1,89 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.ISystemRemoteEditConstants; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.swt.widgets.Shell; + + + +public class SystemEditFileAction extends SystemBaseAction implements ISystemRemoteEditConstants { + + + protected String _editorId; + + /** + * Constructor for SystemEditFileAction + */ + public SystemEditFileAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId) { + super(text, tooltip, null, image, parent); + init(); + _editorId = editorId; + } + + /** + * Constructor for SystemEditFileAction + */ + public SystemEditFileAction(String text, String tooltip, ImageDescriptor image, int style, Shell parent, String editorId) { + super(text, tooltip, null, image, style, parent); + init(); + _editorId = editorId; + } + + /** + * Initialize the action + */ + private void init() { + allowOnMultipleSelection(false); + } + + + /** + * @see SystemBaseAction#run + */ + public void run() { + IStructuredSelection selection = getSelection(); + + if (selection.size() != 1) + return; + + Object element = getFirstSelection(); + + if (element == null) + return; + else if (!(element instanceof IRemoteFile)) + return; + + process((IRemoteFile)element); + } + + + /** + * Process the object: download file, open in editor, etc. + */ + protected void process(IRemoteFile remoteFile) { + + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile, _editorId); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell()); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileInPlaceAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileInPlaceAction.java new file mode 100644 index 00000000000..348501facbf --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileInPlaceAction.java @@ -0,0 +1,89 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.resources.ISystemRemoteEditConstants; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.swt.widgets.Shell; + + +public class SystemEditFileInPlaceAction extends SystemBaseAction implements ISystemRemoteEditConstants { + + + + private SystemPlugin plugin; + + + /** + * Constructor for SystemEditFileAction + */ + public SystemEditFileInPlaceAction(String text, String tooltip, ImageDescriptor image, Shell parent) { + super(text, tooltip, image, parent); + init(); + } + + + /** + * Initialize the action + */ + private void init() { + allowOnMultipleSelection(false); + + // set the context menu group here seems to have no affect + // had to add it in the group in the adapter + // setContextMenuGroup(ISystemContextMenuConstants.GROUP_OPENWITH); + + plugin = SystemPlugin.getDefault(); + } + + + /** + * @see SystemBaseAction#run + */ + public void run() { + + IStructuredSelection selection = getSelection(); + + if (selection.size() != 1) + return; + + Object element = getFirstSelection(); + + if (element == null) + return; + else if (!(element instanceof IRemoteFile)) + return; + + process((IRemoteFile)element); + } + + + /** + * Process the object: download file, open in editor, etc. + */ + private void process(IRemoteFile remoteFile) { + + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile); + editableFile.openInSystemEditor(SystemBasePlugin.getActiveWorkbenchShell()); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileLineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileLineAction.java new file mode 100644 index 00000000000..b417cc51de4 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFileLineAction.java @@ -0,0 +1,126 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + + + +public class SystemEditFileLineAction extends SystemEditFileAction { + + + protected IRemoteFile _remoteFile; + protected int _line, _charStart, _charEnd; + + /** + * Constructor for SystemEditFileAction. + */ + public SystemEditFileLineAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId, IRemoteFile remoteFile, int line, int charStart, int charEnd) { + super(text, tooltip, image, parent, editorId); + _line = line; + _remoteFile = remoteFile; + _charStart = charStart; + _charEnd = charEnd; + } + + public void run() { + process(_remoteFile); + } + + /** + * Process the object: download file, open in editor, etc. + */ + protected void process(IRemoteFile remoteFile) { + super.process(remoteFile); + handleGotoLine(); + } + + protected void handleGotoLine() { + handleGotoLine(_remoteFile, _line, _charStart, _charEnd); + } + + public static void handleGotoLine(IRemoteFile remoteFile, int line, int charStart, int charEnd) { + + if (line > 0) { + + IWorkbench desktop = PlatformUI.getWorkbench(); + IWorkbenchPage persp = desktop.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = null; + String fileName = remoteFile.getAbsolutePath(); + IEditorReference[] editors = persp.getEditorReferences(); + + for (int i = 0; i < editors.length; i++) { + + IEditorReference ref = editors[i]; + IEditorPart editorp = ref.getEditor(false); + + if (editorp != null) { + + IEditorInput einput = editorp.getEditorInput(); + + if (einput instanceof IFileEditorInput) { + + IFileEditorInput input = (IFileEditorInput) einput; + IFile efile = input.getFile(); + + SystemIFileProperties properties = new SystemIFileProperties(efile); + String comparePath = properties.getRemoteFilePath(); + + if (comparePath != null && (comparePath.replace('\\','/').equals(fileName.replace('\\','/')))) { + + editor = editorp; + persp.bringToTop(editor); + + try { + IMarker marker = createMarker(efile, line, charStart, charEnd); + IDE.gotoMarker(editor, marker); + } + catch (CoreException e) { + SystemBasePlugin.logError("Error occured in handleGotoLine", e); + } + } + } + } + } + } + } + + protected static IMarker createMarker(IFile file, int line, int charStart, int charEnd) throws CoreException { + IMarker marker = file.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + + return marker; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilePlatformAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilePlatformAction.java new file mode 100644 index 00000000000..b6d5c99aede --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilePlatformAction.java @@ -0,0 +1,89 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.resources.ISystemRemoteEditConstants; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.swt.widgets.Shell; + + +public class SystemEditFilePlatformAction extends SystemBaseAction implements ISystemRemoteEditConstants { + + + + private SystemPlugin plugin; + + + /** + * Constructor for SystemEditFileAction + */ + public SystemEditFilePlatformAction(String text, String tooltip, ImageDescriptor image, Shell parent) { + super(text, tooltip, image, parent); + init(); + } + + + /** + * Initialize the action + */ + private void init() { + allowOnMultipleSelection(false); + + // set the context menu group here seems to have no affect + // had to add it in the group in the adapter + // setContextMenuGroup(ISystemContextMenuConstants.GROUP_OPENWITH); + + plugin = SystemPlugin.getDefault(); + } + + + /** + * @see SystemBaseAction#run + */ + public void run() { + + IStructuredSelection selection = getSelection(); + + if (selection.size() != 1) + return; + + Object element = getFirstSelection(); + + if (element == null) + return; + else if (!(element instanceof IRemoteFile)) + return; + + process((IRemoteFile)element); + } + + + /** + * Process the object: download file, open in editor, etc. + */ + private void process(IRemoteFile remoteFile) { + + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile); + editableFile.openInSystemEditor(SystemBasePlugin.getActiveWorkbenchShell()); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilesAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilesAction.java new file mode 100644 index 00000000000..8ee95c13696 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditFilesAction.java @@ -0,0 +1,118 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.util.Iterator; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.ISystemRemoteEditConstants; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.files.ui.resources.UniversalFileTransferUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + + +public class SystemEditFilesAction extends SystemBaseAction implements ISystemRemoteEditConstants { + + + private IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); + + /** + * Constructor for SystemEditFilesAction + */ + public SystemEditFilesAction(String text, String tooltip, Shell parent) + { + super(text, tooltip, parent); + init(); + } + + + + /** + * Initialize the action + */ + private void init() + { + allowOnMultipleSelection(true); + } + + /** + * Get the local cache of the remote file, or null if none. + * @param remoteFile the remote file. + * @return the local cached resource, or null if none. + */ + private IFile getLocalResource(IRemoteFile remoteFile) + { + return (IFile)UniversalFileTransferUtility.getTempFileFor(remoteFile); + } + + protected IEditorDescriptor getDefaultEditor(IRemoteFile remoteFile) + { + IFile localFile = getLocalResource(remoteFile); + + if (localFile == null) { + return registry.getDefaultEditor(remoteFile.getName()); + } + else { + return IDE.getDefaultEditor(localFile); + } + } + + /** + * @see SystemBaseAction#run + */ + public void run() { + + IStructuredSelection selection = getSelection(); + + Iterator iterator = selection.iterator(); + while (iterator.hasNext()) + { + Object obj = iterator.next(); + if (obj instanceof IRemoteFile) + { + process((IRemoteFile)obj); + } + } + } + + + + /** + * Process the object: download file, open in editor, etc. + */ + protected void process(IRemoteFile remoteFile) + { + String editorId = null; + IEditorDescriptor des = getDefaultEditor(remoteFile); + if (des != null) + { + editorId = des.getId(); + } + + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile, editorId); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell()); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditProjectFileLineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditProjectFileLineAction.java new file mode 100644 index 00000000000..67ba2cddb00 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditProjectFileLineAction.java @@ -0,0 +1,194 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector; +import org.eclipse.debug.core.sourcelookup.containers.ProjectSourceContainer; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.resources.RemoteSourceLookupDirector; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteCommandShell; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteError; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteOutput; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.part.FileEditorInput; + + + + +public class SystemEditProjectFileLineAction extends SystemEditFileAction { + + + protected IRemoteFile _remoteFile; + protected IRemoteOutput _output; + + /** + * Constructor for SystemEditFileAction + */ + public SystemEditProjectFileLineAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId, + IRemoteFile remoteFile, IRemoteOutput output) + { + super(text, tooltip, image, parent, editorId); + + _output = output; + _remoteFile = remoteFile; + } + + public void run() + { + process(); + } + + + + /** + * Process the object: download file, open in editor, etc. + */ + protected void process() + { + openWorkspaceFile(_remoteFile, _output); + } + + + protected IEditorRegistry getEditorRegistry() + { + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); + } + + protected IEditorDescriptor getDefaultTextEditor() + { + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); + } + /** + * Open workspace file associated with IRemoteCommandShell. If there is no associated project + * return. + * @param remoteFile + * @param output + * @return + */ + protected boolean openWorkspaceFile(IRemoteFile remoteFile, IRemoteOutput output) + { + IRemoteCommandShell cmd = (IRemoteCommandShell)(output.getParent()); + IProject associatedProject = cmd.getAssociatedProject(); + if (associatedProject != null) + { + ProjectSourceContainer container = new ProjectSourceContainer(associatedProject, false); + ISourceLookupDirector director = new RemoteSourceLookupDirector(); + container.init(director); + try + { + Object[] matches = container.findSourceElements(remoteFile.getName()); + for (int i = 0; i < matches.length; i++) + { + //System.out.println("match="+matches[i]); + } + + if (matches.length == 1) + { + IFile localMatch = (IFile)matches[0]; + + + + IWorkbenchPage activePage = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + + FileEditorInput finput = new FileEditorInput(localMatch); + + IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(remoteFile.getName()); + if (desc == null) + { + desc = getDefaultTextEditor(); + } + String editorid = desc.getId(); + + IEditorPart editor = activePage.openEditor(finput, editorid); + + int line = output.getLine(); + int charStart = output.getCharStart(); + int charEnd = output.getCharEnd(); + + try + { + IMarker marker = null; + + // DKM - should we? this will populate the Problems view..but resources are actually remote + if (output instanceof IRemoteError) + { + IRemoteError error = (IRemoteError)output; + String type = error.getType(); + + marker = localMatch.createMarker(IMarker.TEXT); + + if (type.equals("error")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } + else if (type.equals("warning")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); + } + else if (type.equals("informational")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO); + } + + marker.setAttribute(IMarker.MESSAGE, output.getText()); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + + } + else + { + marker = localMatch.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + } + IDE.gotoMarker(editor, marker); + + + } + catch (CoreException e) + { + e.printStackTrace(); + } + return true; + } + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + return false; + } +} + \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditionAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditionAction.java new file mode 100644 index 00000000000..f87980c60e3 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemEditionAction.java @@ -0,0 +1,380 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.ResourceBundle; + +import org.eclipse.compare.EditionSelectionDialog; +import org.eclipse.compare.HistoryItem; +import org.eclipse.compare.IStreamContentAccessor; +import org.eclipse.compare.ITypedElement; +import org.eclipse.compare.ResourceNode; +import org.eclipse.compare.internal.CompareUIPlugin; +import org.eclipse.compare.internal.Utilities; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFileState; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.services.clientserver.SystemEncodingUtil; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.actions.WorkspaceModifyOperation; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + + +public class SystemEditionAction extends SystemBaseAction +{ + + /** + * Implements the IStreamContentAccessor and ITypedElement protocols + * for a Document. + */ + class DocumentBufferNode implements ITypedElement, IStreamContentAccessor + { + + private IDocument fDocument; + private IFile fFile; + + DocumentBufferNode(IDocument document, IFile file) + { + fDocument = document; + fFile = file; + } + + public String getName() + { + return fFile.getName(); + } + + public String getType() + { + return fFile.getFileExtension(); + } + + public Image getImage() + { + return null; + } + + public InputStream getContents() + { + return new ByteArrayInputStream(fDocument.get().getBytes()); + } + } + + private List _selected; + private boolean fReplaceMode; + private String fBundleName; + protected boolean fPrevious = false; + protected String fHelpContextId; + + SystemEditionAction(Shell parent, String title, String tooltip, String bundleName, boolean replaceMode) + { + super(title, parent); + setToolTipText(tooltip); + + fReplaceMode = replaceMode; + fBundleName = bundleName; + _selected = new ArrayList(); + } + + + /** + * Called when the selection changes in the systems view. This determines + * the input object for the command and whether to enable or disable + * the action. + * + * @param selection the current seleciton + * @return whether to enable or disable the action + */ + public boolean updateSelection(IStructuredSelection selection) + { + boolean enable = false; + _selected.clear(); + Iterator e = ((IStructuredSelection) selection).iterator(); + if (e.hasNext()) + { + Object selected = e.next(); + + if (selected != null && selected instanceof IRemoteFile) + { + RemoteFile file = (RemoteFile) selected; + if (file.isFile()) + { + ISystemRemoteElementAdapter adapter = (ISystemRemoteElementAdapter)file.getAdapter(ISystemRemoteElementAdapter.class); + if (adapter != null) + { + ISystemEditableRemoteObject editable = adapter.getEditableRemoteObject(file); + if (editable != null) + { + if (editable.getLocalResource().exists()) + { + _selected.add(file); + enable = true; + } + } + } + + + /** FIXME - no longer have a getCachedCopy() method + try + { + if (file.getCachedCopy() != null) + { + _selected.add(file); + enable = true; + } + } + catch (SystemMessageException ex) + { + } + */ + } + } + } + + return enable; + } + + public void run() + { + // get cached file + IFile[] files = getFiles(_selected, fReplaceMode); + for (int i = 0; i < files.length; i++) + doFromHistory(files[i]); + } + + private void doFromHistory(final IFile file) + { + //DKM - hack - needed to use compare class loader to load bundle for current locale + ResourceBundle bundle = ResourceBundle.getBundle(fBundleName, Locale.getDefault(), CompareUIPlugin.class.getClassLoader()); + + String title = Utilities.getString(bundle, "title"); //$NON-NLS-1$ + + Shell parentShell = CompareUIPlugin.getShell(); + + IFileState states[] = null; + try + { + states = file.getHistory(null); + } + catch (CoreException ex) + { + MessageDialog.openError(parentShell, title, ex.getMessage()); + return; + } + + if (states == null || states.length <= 0) + { + String msg = Utilities.getString(bundle, "noLocalHistoryError"); //$NON-NLS-1$ + MessageDialog.openInformation(parentShell, title, msg); + return; + } + + ITypedElement base = new ResourceNode(file); + + IDocument document = getDocument(file); + ITypedElement target = base; + if (document != null) + target = new DocumentBufferNode(document, file); + + ITypedElement[] editions = new ITypedElement[states.length + 1]; + editions[0] = base; + for (int i = 0; i < states.length; i++) + editions[i + 1] = new HistoryItem(base, states[i]); + + EditionSelectionDialog d = new EditionSelectionDialog(parentShell, bundle); + d.setEditionTitleArgument(file.getName()); + d.setEditionTitleImage(CompareUIPlugin.getImage(file)); + //d.setHideIdenticalEntries(false); + if (fHelpContextId != null) + d.setHelpContextId(fHelpContextId); + + if (fReplaceMode) + { + + ITypedElement ti = null; + if (fPrevious) + ti = d.selectPreviousEdition(target, editions, null); + else + ti = d.selectEdition(target, editions, null); + + if (ti instanceof IStreamContentAccessor) + { + IStreamContentAccessor sa = (IStreamContentAccessor) ti; + try + { + + if (document != null) + updateDocument(document, sa); + else + updateWorkspace(bundle, parentShell, sa, file); + + } + catch (InterruptedException x) + { + // Do nothing. Operation has been canceled by user. + + } + catch (InvocationTargetException x) + { + String reason = x.getTargetException().getMessage(); + MessageDialog.openError(parentShell, title, Utilities.getFormattedString(bundle, "replaceError", reason)); //$NON-NLS-1$ + } + } + } + else + { + d.setCompareMode(true); + + d.selectEdition(target, editions, null); + } + } + + private void updateWorkspace(final ResourceBundle bundle, Shell shell, final IStreamContentAccessor sa, final IFile file) throws InvocationTargetException, InterruptedException + { + + WorkspaceModifyOperation operation = new WorkspaceModifyOperation() + { + public void execute(IProgressMonitor pm) throws InvocationTargetException + { + try + { + String taskName = Utilities.getString(bundle, "taskName"); //$NON-NLS-1$ + pm.beginTask(taskName, IProgressMonitor.UNKNOWN); + file.setContents(sa.getContents(), false, true, pm); + } + catch (CoreException e) + { + throw new InvocationTargetException(e); + } + finally + { + pm.done(); + } + } + }; + + ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(shell); + pmdialog.run(false, true, operation); + } + + private void updateDocument(IDocument document, IStreamContentAccessor sa) throws InvocationTargetException + { + try + { + InputStream is = sa.getContents(); + String text = Utilities.readString(is, SystemEncodingUtil.ENCODING_UTF_8); + document.replace(0, document.getLength(), text); + } + catch (CoreException e) + { + throw new InvocationTargetException(e); + } + catch (BadLocationException e) + { + throw new InvocationTargetException(e); + } + } + + private IDocument getDocument(IFile file) + { + IWorkbench wb = PlatformUI.getWorkbench(); + if (wb == null) + return null; + IWorkbenchWindow[] ws = wb.getWorkbenchWindows(); + if (ws == null) + return null; + + FileEditorInput test = new FileEditorInput(file); + + for (int i = 0; i < ws.length; i++) + { + IWorkbenchWindow w = ws[i]; + IWorkbenchPage[] wps = w.getPages(); + if (wps != null) + { + for (int j = 0; j < wps.length; j++) + { + IWorkbenchPage wp = wps[j]; + IEditorPart ep = wp.findEditor(test); + if (ep instanceof ITextEditor) + { + ITextEditor te = (ITextEditor) ep; + IDocumentProvider dp = te.getDocumentProvider(); + if (dp != null) + { + IDocument doc = dp.getDocument(ep); + if (doc != null) + return doc; + } + } + } + } + } + return null; + } + + private IFile[] getFiles(List remoteFiles, boolean modifiable) + { + IFile[] result = new IFile[remoteFiles.size()]; + for (int i = 0; i < remoteFiles.size(); i++) + { + IRemoteFile remotefile = (IRemoteFile)remoteFiles.get(i); + SystemEditableRemoteFile eFile = new SystemEditableRemoteFile(remotefile); + try + { + eFile.download(getShell()); + eFile.addAsListener(); + eFile.setLocalResourceProperties(); + IFile localFile = eFile.getLocalResource(); + result[i] = localFile; + } + catch (Exception e) + { + } + } + + return result; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractAction.java new file mode 100644 index 00000000000..37dc15561dd --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractAction.java @@ -0,0 +1,258 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.ISystemDragDropAdapter; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class SystemExtractAction extends SystemBaseAction +{ + protected List _selected; + protected Shell _parent; + protected String _label; + + public SystemExtractAction(Shell parent) + { + super(FileResources.ACTION_EXTRACT_LABEL, parent); + _label = FileResources.ACTION_EXTRACT_LABEL; + setToolTipText(FileResources.ACTION_EXTRACT_TOOLTIP); + _selected = new ArrayList(); + _parent = parent; + allowOnMultipleSelection(true); + setHelp(SystemPlugin.HELPPREFIX + "actn0118"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_EXTRACT_ID)); + } + + public SystemExtractAction(Shell parent, String label, String tooltip) + { + super(label, tooltip, parent); + _label = label; + setToolTipText(tooltip); + _selected = new ArrayList(); + _parent = parent; + allowOnMultipleSelection(true); + setHelp(SystemPlugin.HELPPREFIX + "actn0118"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_EXTRACT_ID)); + + } + + public void run() + { + for (int i = 0; i < _selected.size(); i++) + { + IRemoteFile selection = (IRemoteFile) _selected.get(i); + IRemoteFile destinationParent = selection.getParentRemoteFile(); + IRemoteFileSubSystem ss = selection.getParentRemoteFileSubSystem(); + String newName = getExtractedName(selection); + IRemoteFile destination = null; + try + { + destination = ss.getRemoteFileObject(destinationParent.getAbsolutePath() + destinationParent.getSeparator() + newName); + ss.createFolder(destination); + } + catch (SystemMessageException e) + { + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), e.getSystemMessage()); + dlg.open(); + continue; + } + IRunnableContext runnableContext = getRunnableContext(_parent); + + ExtractRunnable runnable = new ExtractRunnable(selection, destination); + try + { + // currently we don't run this in a thread because + // in some cases dialogs are launched in the operation + // (widgets can only be legally used on the main thread) + runnableContext.run(false, true, runnable); // inthread, cancellable, IRunnableWithProgress + } + catch (java.lang.reflect.InvocationTargetException exc) + { + } + catch (java.lang.InterruptedException e) + { + } + // always refresh + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + registry.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, destination, destinationParent, ss, null, null); + registry.fireEvent(new SystemResourceChangeEvent(destination, ISystemResourceChangeEvents.EVENT_REFRESH, destinationParent)); + } + } + + protected class ExtractRunnable implements IRunnableWithProgress + { + private IRemoteFileSubSystem destSS; + private IRemoteFileSubSystem sourceSS; + private IRemoteFile selection; + private IRemoteFile destination; + + public ExtractRunnable(IRemoteFile source, IRemoteFile dest) + { + destSS = dest.getParentRemoteFileSubSystem(); + sourceSS = source.getParentRemoteFileSubSystem(); + selection = source; + destination = dest; + } + + public void run(IProgressMonitor monitor) + { + IRemoteFile[] sources = sourceSS.listFoldersAndFiles(selection); + for (int j = 0; j < sources.length && !monitor.isCanceled(); j++) + { + try + { + ISystemDragDropAdapter srcAdapter = (ISystemDragDropAdapter) ((IAdaptable) selection).getAdapter(ISystemDragDropAdapter.class); + boolean sameSysType = sourceSS.getClass().equals(destSS.getClass()); + boolean sameSys = (sourceSS == destSS); + if (!sameSys) + { + Object source = srcAdapter.doDrag(sources[j], sameSysType, monitor); + srcAdapter.doDrop(source, destination, sameSysType, sameSys, 0, monitor); + } + else + { + srcAdapter.doDrop(sources[j], destination, sameSysType, sameSys, 0, monitor); + } + } + catch (Exception e) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_OPERATION_FAILED); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + System.out.println(e.getMessage()); + System.out.println("Could not extract " + sources[j].getAbsolutePath()); + } + } + } + + } + + /** + * Called when the selection changes in the systems view. This determines + * the input object for the command and whether to enable or disable + * the action. + * + * @param selection the current seleciton + * @return whether to enable or disable the action + */ + public boolean updateSelection(IStructuredSelection selection) + { + _selected.clear(); + boolean enable = false; + + Iterator e = ((IStructuredSelection) selection).iterator(); + while (e.hasNext()) + { + Object selected = e.next(); + + if (selected != null && selected instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) selected; + if (file.isArchive() && file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) + { + _selected.add(file); + enable = true; + } + } + else + { + return false; + } + } + if (_selected.size() == 1) + { + this.setText(getActionLabelForSingleSelection()); + } + else + { + this.setText(_label); + } + return enable; + } + + /** + * Extending classes must override this method, otherwise + * when there is one selection, the action label will be + * "Extract to xxxx", where xxxx is a dynamically created directory + * name. Note: you can also eliminate this behaviour by overriding + * the updateSelection method. + * @return Set this to return the normal action label if you don't want + * the name dynamically created. + */ + protected String getActionLabelForSingleSelection() + { + String msg = FileResources.ACTION_EXTRACT_SUB_LABEL; + return SystemMessage.sub(msg, "%1", getExtractedName((IRemoteFile)_selected.get(0))); + } + + protected String getExtractedName(IRemoteFile selection) + { + String newName = selection.getName(); + int k = newName.lastIndexOf("."); + if (k == -1) + { + newName = newName + "_contents"; + } + else + { + newName = newName.substring(0, k); + } + return newName; + } + + protected IRunnableContext getRunnableContext(Shell shell) + { + IRunnableContext irc = SystemPlugin.getTheSystemRegistry().getRunnableContext(); + if (irc != null) + { + return irc; + } + + return new ProgressMonitorDialog(shell); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractToAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractToAction.java new file mode 100644 index 00000000000..fd5758330e6 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemExtractToAction.java @@ -0,0 +1,199 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.rse.core.ISystemTypes; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.ExtractToDialog; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class SystemExtractToAction extends SystemExtractAction implements IValidatorRemoteSelection, ISystemMessages +{ + protected static final String[] systemTypes = { ISystemTypes.SYSTEMTYPE_LOCAL, + ISystemTypes.SYSTEMTYPE_WINDOWS, + ISystemTypes.SYSTEMTYPE_LINUX, + ISystemTypes.SYSTEMTYPE_POWER_LINUX, + ISystemTypes.SYSTEMTYPE_UNIX, + ISystemTypes.SYSTEMTYPE_AIX, + ISystemTypes.SYSTEMTYPE_ISERIES + }; + protected SystemMessage targetDescendsFromSrcMsg = null; + protected int currentlyProcessingSelection = 0; + + public SystemExtractToAction(Shell parent) + { + super(parent,FileResources.ACTION_EXTRACT_TO_LABEL, FileResources.ACTION_EXTRACT_TO_TOOLTIP); + setHelp(SystemPlugin.HELPPREFIX + "actn0119"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_EXTRACTTO_ID)); + + } + + public SystemExtractToAction(Shell parent, String label, String tooltip) + { + super(parent, label, tooltip); + setHelp(SystemPlugin.HELPPREFIX + "actn0119"); + setImageDescriptor(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_EXTRACTTO_ID)); + } + + public void run() + { + for (int i = 0; i < _selected.size(); i++) + { + currentlyProcessingSelection = i; + IRemoteFile selection = (IRemoteFile) _selected.get(i); + IRemoteFileSubSystem sourceSS = selection.getParentRemoteFileSubSystem(); + String title = FileResources.RESID_EXTRACTTO_TITLE; + ExtractToDialog dialog = new ExtractToDialog(getShell(), title); + if (dialog == null) + return; + dialog.setNeedsProgressMonitor(true); + + String message = SystemMessage.sub(FileResources.RESID_EXTRACTTO_PROMPT, "&1", selection.getAbsolutePath()); + dialog.setMessage(message); + dialog.setShowNewConnectionPrompt(true); + dialog.setShowPropertySheet(true, false); + dialog.setSystemTypes(systemTypes); + + dialog.setPreSelection(selection); + + dialog.setBlockOnOpen(true); + dialog.setSelectionValidator(this); + + /*if (dlgHelpId!=null) + { + dialog.setHelp(dlgHelpId); + }*/ + + int rc = dialog.open(); + + // if (rc != 0) NOT RELIABLE! + boolean cancelled = false; + if (dialog.wasCancelled()) cancelled = true; + + IRemoteFile destination = null; + IRemoteFileSubSystem destSS = null; + if (!cancelled) + { + destination = (IRemoteFile) dialog.getOutputObject(); + destSS = destination.getParentRemoteFileSubSystem(); + } + else + { + return; + } + if (destination == null) + { + System.out.println("blah"); + } + if (selection.isAncestorOf(destination)) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DEST_NOT_IN_SOURCE); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + i--; + continue; + } + if (!destination.canWrite()) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DEST_TARGET_READONLY); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + i--; + continue; + } + IRunnableContext runnableContext = getRunnableContext(_parent); + + ExtractRunnable runnable = new ExtractRunnable(selection, destination); + try + { + // currently we don't run this in a thread because + // in some cases dialogs are launched in the operation + // (widgets can only be legally used on the main thread) + runnableContext.run(false, true, runnable); // inthread, cancellable, IRunnableWithProgress + } + catch (java.lang.reflect.InvocationTargetException exc) + { + } + catch (java.lang.InterruptedException e) + { + } + // always refresh + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + registry.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, destination, destination.getParentPath(), destSS, null, null); + registry.fireEvent(new SystemResourceChangeEvent(destination, ISystemResourceChangeEvents.EVENT_REFRESH, destination.getParentPath())); + } + } + + protected boolean destinationInSource(IRemoteFile destination) + { + boolean insource = false; + for (int i = 0; i < _selected.size(); i++) + { + if (destination.isDescendantOf((IRemoteFile) _selected.get(i))) + { + insource = true; + break; + } + } + return insource; + } + + protected String getActionLabelForSingleSelection() + { + return _label; + } + + public SystemMessage isValid(IHost selectedConnection, Object[] selectedObjects, ISystemRemoteElementAdapter[] remoteAdaptersForSelectedObjects) + { + //if (selectedConnection != sourceConnection) {} // someday, but can't happen today. + Object selectedObject = selectedObjects[0]; + IRemoteFile currentSelection = (IRemoteFile) _selected.get(currentlyProcessingSelection); + if (!(selectedObject instanceof IRemoteFile)) + return null; + IRemoteFile selectedFolder = (IRemoteFile)selectedObject; + if (selectedFolder.isDescendantOf(currentSelection)) + { + if (targetDescendsFromSrcMsg == null) + targetDescendsFromSrcMsg = SystemPlugin.getPluginMessage(FILEMSG_MOVE_TARGET_DESCENDS_FROM_SOUCE); + return targetDescendsFromSrcMsg; + } + else + return null; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemFileUpdateFilterAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemFileUpdateFilterAction.java new file mode 100644 index 00000000000..41e62682c57 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemFileUpdateFilterAction.java @@ -0,0 +1,56 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.rse.files.ui.SystemFileFilterStringEditPane; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.filters.actions.SystemChangeFilterAction; +import org.eclipse.rse.ui.filters.dialogs.SystemChangeFilterDialog; +import org.eclipse.swt.widgets.Shell; + + +/** + * The action that displays the Change File Filter dialog. + * Note that the input filter is deduced from the current selection, which must be a filter reference. + */ +public class SystemFileUpdateFilterAction + extends SystemChangeFilterAction +{ + + /** + * Constructor + */ + public SystemFileUpdateFilterAction(Shell parent) + { + super(parent, SystemResources.ACTION_UPDATEFILTER_LABEL, SystemResources.ACTION_UPDATEFILTER_TOOLTIP); + setDialogTitle(SystemFileResources.RESID_CHGFILEFILTER_TITLE); + } + /** + * Overridable extension point to configure the filter dialog. Typically you don't need + * to subclass our default dialog. + */ + protected void configureFilterDialog(SystemChangeFilterDialog dlg) + { + // it is cheaper to do this here, as it defers instantiation of the edit pane until the + // user actually runs the action! + Shell shell = dlg.getShell(); + if (shell == null) + shell = dlg.getParentShell(); + + dlg.setFilterStringEditPane(new SystemFileFilterStringEditPane(shell)); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemMoveRemoteFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemMoveRemoteFileAction.java new file mode 100644 index 00000000000..c7952b419c4 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemMoveRemoteFileAction.java @@ -0,0 +1,192 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import java.util.Vector; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.actions.SystemBaseCopyAction; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.widgets.Shell; + + +/** + * Move selected files and folders action. + */ +public class SystemMoveRemoteFileAction extends SystemCopyRemoteFileAction + implements ISystemMessages, IValidatorRemoteSelection +{ + private SystemMessage targetEqualsSrcMsg = null; + private SystemMessage targetDescendsFromSrcMsg = null; + protected Vector movedFiles = new Vector(); + + /** + * Constructor + */ + public SystemMoveRemoteFileAction(Shell shell) + { + super(shell, MODE_MOVE); + setHelp(SystemPlugin.HELPPREFIX+"actn0111"); + setDialogHelp(SystemPlugin.HELPPREFIX+"dmrf0000"); + } + + // -------------------------- + // PARENT METHOD OVERRIDES... + // -------------------------- + /** + * Reset. This is a re-run of this action + */ + protected void reset() + { + movedFiles.clear(); + super.reset(); + + //targetEqualsSrcMsg = null; + } + + /** + * @see SystemBaseCopyAction#doCopy(IProgressMonitor, Object, Object, String) + * @param monitor Usually not needed + * @param targetContainer will be the IRemoteFile folder selected to move into + * @param oldObject will be the IRemoteFile object currently being moved + * @param newName will be the new name to give the oldObject on move + */ + protected boolean doCopy(IProgressMonitor monitor, Object targetContainer, Object oldObject, String newName) + throws Exception + { + IRemoteFile targetFolder = (IRemoteFile)targetContainer; + IRemoteFile srcFileOrFolder = (IRemoteFile)oldObject; + + IRemoteFileSubSystem ss = targetFolder.getParentRemoteFileSubSystem(); + + boolean ok = false; + + ok = ss.move(srcFileOrFolder, targetFolder, newName, monitor); + if (!ok) + { + SystemMessage msg = SystemPlugin.getPluginMessage(FILEMSG_MOVE_FILE_FAILED); + msg.makeSubstitution(srcFileOrFolder.getName()); + throw new SystemMessageException(msg); + } + else + { + String sep = targetFolder.getSeparator(); + String targetFolderName = targetFolder.getAbsolutePath(); + if (!targetFolderName.endsWith(sep)) + copiedFiles.addElement(targetFolderName+sep+newName); + else + copiedFiles.addElement(targetFolderName+newName); + + movedFiles.addElement(srcFileOrFolder); + } + + return ok; + } + + /** + * The user has selected a remote object. Return null if OK is to be enabled, or a SystemMessage + * if it is not to be enabled. The message will be displayed on the message line. + */ + public SystemMessage isValid(IHost selectedConnection, Object[] selectedObjects, ISystemRemoteElementAdapter[] remoteAdaptersForSelectedObjects) + { + //if (selectedConnection != sourceConnection) {} // someday, but can't happen today. + Object selectedObject = selectedObjects[0]; + if (!(selectedObject instanceof IRemoteFile)) + return null; + IRemoteFile selectedFolder = (IRemoteFile)selectedObject; + if (selectedFolder.getAbsolutePath().equals(firstSelectionParent.getAbsolutePath())) + { + if (targetEqualsSrcMsg == null) + targetEqualsSrcMsg = SystemPlugin.getPluginMessage(FILEMSG_MOVE_TARGET_EQUALS_SOURCE); + return targetEqualsSrcMsg; + } + else if (selectedFolder.getAbsolutePath().equals(firstSelection.getAbsolutePath())) + { + if (targetEqualsSrcMsg == null) + targetEqualsSrcMsg = SystemPlugin.getPluginMessage(FILEMSG_MOVE_TARGET_EQUALS_SOURCE); // todo: different msg + return targetEqualsSrcMsg; + } + else if (selectedFolder.isDescendantOf(firstSelection)) + { + if (targetDescendsFromSrcMsg == null) + targetDescendsFromSrcMsg = SystemPlugin.getPluginMessage(FILEMSG_MOVE_TARGET_DESCENDS_FROM_SOUCE); + return targetDescendsFromSrcMsg; + } + else + return null; + } + + /** + * Called after all the copy/move operations end, be it successfully or not. + * Your opportunity to display completion or do post-copy selections/refreshes + */ + public void copyComplete() + { + // we want to do the super.copyComplete() to refresh the target, but first we must do refresh the + // source to reflect the deletion... + + // refresh all instances of the source parent, and all affected filters... + ISubSystem fileSS = targetFolder.getParentRemoteFileSubSystem(); + //SystemPlugin.getTheSystemRegistry().fireRemoteResourceChangeEvent( + // ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_DELETED, copiedFiles, firstSelectionParent.getAbsolutePath(), fileSS, null, null); + SystemPlugin.getTheSystemRegistry().fireRemoteResourceChangeEvent( + ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_DELETED, movedFiles, firstSelectionParent.getAbsolutePath(), fileSS, null, null); + + /* old release 1.0 way of doing it... + Viewer v = getViewer(); + if (v instanceof ISystemTree) + { + SystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + ISystemTree tree = (ISystemTree)v; + Object parent = tree.getSelectedParent(); + if (parent != null) + { + if (parent instanceof IRemoteFile) + { + //System.out.println("Firing REFRESH_REMOTE"); + sr.fireEvent( + new com.ibm.etools.systems.model.impl.SystemResourceChangeEvent( + parent,ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, null) ); + } + else + { + //System.out.println("MOVE OPERATION: Firing REFRESH"); + // FIRST REFRESH EXPANDED FILTER + sr.fireEvent( + new com.ibm.etools.systems.model.impl.SystemResourceChangeEvent( + parent,ISystemResourceChangeEvent.EVENT_REFRESH, null) ); + // NEXT REFRESH ALL OTHER PLACES THAT MIGHT BE SHOWING THE SOURCE FOLDER + sr.fireEvent( + new com.ibm.etools.systems.model.impl.SystemResourceChangeEvent( + firstSelectionParent,ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, null) ); + } + } + else + SystemPlugin.logWarning("Hmm, selected parent is null on a move operation!"); + }*/ + super.copyComplete(); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileAction.java new file mode 100644 index 00000000000..61dba9137d0 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileAction.java @@ -0,0 +1,68 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.wizards.SystemNewFileWizard; +import org.eclipse.rse.ui.ISystemContextMenuConstants; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemBaseWizardAction; +import org.eclipse.swt.widgets.Shell; + + + +/** + * An action for prompting the user with a wizard, for creating a new file + */ +public class SystemNewFileAction extends SystemBaseWizardAction +{ + + /** + * Constructor when you want to use the default label, tooltip and image + */ + public SystemNewFileAction(Shell parent) + { + this(SystemResources.ACTION_NEWFILE_LABEL, + SystemResources.ACTION_NEWFILE_TOOLTIP, + //PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FILE), + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFILE_ID), + parent); + } + + /** + * Constructor when you want to supply your own label, tooltip and image + */ + public SystemNewFileAction(String text,String tooltip,ImageDescriptor image,Shell parent) + { + super(text, tooltip, image, parent); + setContextMenuGroup(ISystemContextMenuConstants.GROUP_NEW); + allowOnMultipleSelection(false); + } + + /** + * Override of parent to create the wizard + */ + protected IWizard createWizard() + { + SystemNewFileWizard newFileWizard = new SystemNewFileWizard(); + // newFileWizard.setInputObject(getValue()); + return newFileWizard; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterAction.java new file mode 100644 index 00000000000..069ea06a106 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterAction.java @@ -0,0 +1,81 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.SystemFileFilterStringEditPane; +import org.eclipse.rse.filters.ISystemFilterPool; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.filters.actions.SystemNewFilterAction; +import org.eclipse.rse.ui.filters.dialogs.SystemNewFilterWizard; +import org.eclipse.swt.widgets.Shell; + + + +/** + * The action that displays the New File Filter wizard. + * File Filters are typed filters that allow users to get a list of files meeting the filtering criteria. + */ +public class SystemNewFileFilterAction + extends SystemNewFilterAction +{ + //private RemoteFileSubSystemFactory inputSubsystemFactory; + + /** + * Constructor + */ + public SystemNewFileFilterAction(IRemoteFileSubSystemConfiguration subsystemFactory, ISystemFilterPool parentPool, Shell shell) + + { + super(shell, parentPool, SystemFileResources.ACTION_NEWFILTER_LABEL, SystemFileResources.ACTION_NEWFILTER_TOOLTIP, + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFILTER_ID)); + + //setHelp(SystemPlugin.HELPPREFIX+"anff0000"); + //setDialogHelp(SystemPlugin.HELPPREFIX+"wnff0000"); + setHelp(SystemPlugin.HELPPREFIX+"actn0042"); + setDialogHelp(SystemPlugin.HELPPREFIX+"wnfr0000"); + } + + /** + * Set the parent filter pool that the new-filter actions need. + */ + public void setParentFilterPool(ISystemFilterPool parentPool) + { + this.parentPool = parentPool; + } + /** + * Parent intercept. + *

+ * Overridable extension. For those cases when you don't want to create your + * own wizard subclass, but prefer to simply configure the default wizard. + *

+ * Note, at the point this is called, all the base configuration, based on the + * setters for this action, have been called. + *

+ * We do it here versus via setters as it defers some work until the user actually + * selects this action. + */ + protected void configureNewFilterWizard(SystemNewFilterWizard wizard) + { + // configuration that used to only be possible via subclasses... + wizard.setWizardPageTitle(SystemFileResources.RESID_NEWFILEFILTER_PAGE1_TITLE); + wizard.setWizardImage(SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFILTERWIZARD_ID)); + wizard.setPage1Description(SystemFileResources.RESID_NEWFILEFILTER_PAGE1_DESCRIPTION); + wizard.setFilterStringEditPane(new SystemFileFilterStringEditPane(wizard.getShell())); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterFromFolderAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterFromFolderAction.java new file mode 100644 index 00000000000..8813be3e93e --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFileFilterFromFolderAction.java @@ -0,0 +1,124 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import java.util.Iterator; + +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystemConfiguration; +import org.eclipse.rse.filters.ISystemFilterPool; +import org.eclipse.rse.filters.ISystemFilterPoolReferenceManagerProvider; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFile; +import org.eclipse.rse.ui.filters.dialogs.SystemNewFilterWizard; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.widgets.Shell; + + +/** + * Class for defining a new filter from a preselected folder + */ +public class SystemNewFileFilterFromFolderAction extends SystemNewFileFilterAction +{ + private RemoteFile _selected; + + /** + * Constructor for SystemNewFileFilterFromFolderAction + * @param parent + */ + public SystemNewFileFilterFromFolderAction(Shell parent) + { + // initially use null, but update based on selection + super(null, null, parent); + setHelp(SystemPlugin.HELPPREFIX+"actn0112"); + } + + + public void run() + { + IRemoteFileSubSystem fileSubsystem = _selected.getParentRemoteFileSubSystem(); + ISubSystemConfiguration factory = fileSubsystem.getSubSystemConfiguration(); + ISystemFilterPool filterPool = fileSubsystem.getFilterPoolReferenceManager().getDefaultSystemFilterPoolManager().getFirstDefaultSystemFilterPool(); + setParentFilterPool(filterPool); + setAllowFilterPoolSelection(fileSubsystem.getFilterPoolReferenceManager().getReferencedSystemFilterPools()); + super.run(); + } + + /** + * Called when the selection changes in the systems view. This determines + * the input object for the command and whether to enable or disable + * the action. + * + * @param selection the current seleciton + * @return whether to enable or disable the action + */ + public boolean updateSelection(IStructuredSelection selection) + { + boolean enable = false; + + Iterator e = ((IStructuredSelection) selection).iterator(); + Object selected = e.next(); + + if (selected != null && selected instanceof IRemoteFile) + { + _selected = (RemoteFile) selected; + //if (!_selected.isFile()) + { + enable = true; + } + } + + + + return enable; + } + + + /** + * Output method. Do not override.
+ * Get the contextual system filter pool reference manager provider. Will return non-null if the + * current selection is a reference to a filter pool or filter, or a reference manager + * provider. + */ + public ISystemFilterPoolReferenceManagerProvider getSystemFilterPoolReferenceManagerProvider() + { + return _selected.getParentRemoteFileSubSystem().getFilterPoolReferenceManager().getProvider(); + } + + /** + * Parent intercept. + *

+ * Overridable extension. For those cases when you don't want to create your + * own wizard subclass, but prefer to simply configure the default wizard. + *

+ * Note, at the point this is called, all the base configuration, based on the + * setters for this action, have been called. + *

+ * We do it here versus via setters as it defers some work until the user actually + * selects this action. + */ + protected void configureNewFilterWizard(SystemNewFilterWizard wizard) + { + super.configureNewFilterWizard(wizard); + String[] filters = new String[1]; + ISystemRemoteElementAdapter adapter = (ISystemRemoteElementAdapter)_selected.getAdapter(ISystemRemoteElementAdapter.class); + filters[0] = adapter.getFilterStringFor(_selected); + wizard.setDefaultFilterStrings(filters); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFolderAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFolderAction.java new file mode 100644 index 00000000000..2d758bef356 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemNewFolderAction.java @@ -0,0 +1,67 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.wizards.SystemNewFolderWizard; +import org.eclipse.rse.ui.ISystemContextMenuConstants; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.actions.SystemBaseWizardAction; +import org.eclipse.swt.widgets.Shell; + + + +/** + * An action for prompting the user with a wizard, for creating a new folder + */ +public class SystemNewFolderAction extends SystemBaseWizardAction +{ + + /** + * Constructor when you want to use the default label, tooltip and image + */ + public SystemNewFolderAction(Shell parent) + { + this(FileResources.ACTION_NEWFOLDER_LABEL, + FileResources.ACTION_NEWFOLDER_TOOLTIP, + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFOLDER_ID), + parent); + } + + /** + * Constructor when you want to supply your own label, tooltip and image + */ + public SystemNewFolderAction(String text, String tooltip, ImageDescriptor image, Shell parent) + { + super(text, tooltip, image, parent); + setContextMenuGroup(ISystemContextMenuConstants.GROUP_NEW); + allowOnMultipleSelection(false); + } + + /** + * Override of parent to create the wizard + */ + protected IWizard createWizard() + { + SystemNewFolderWizard newFolderWizard = new SystemNewFolderWizard(); + return newFolderWizard; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteArchiveSelectAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteArchiveSelectAction.java new file mode 100644 index 00000000000..a5eaffda150 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteArchiveSelectAction.java @@ -0,0 +1,47 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.rse.files.ui.dialogs.SystemRemoteArchiveDialog; +import org.eclipse.rse.ui.dialogs.SystemRemoteResourceDialog; +import org.eclipse.swt.widgets.Shell; + + + +public class SystemRemoteArchiveSelectAction extends + SystemRemoteFileSelectAction +{ + public SystemRemoteArchiveSelectAction(Shell shell) + { + super(shell); + } + + public SystemRemoteArchiveSelectAction(Shell shell, String label, String tooltip) + { + super(shell, label, tooltip); + } + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell, String title) + { + return new SystemRemoteArchiveDialog(shell, title); + } + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell) + { + return new SystemRemoteArchiveDialog(shell); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileLineOpenWithMenu.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileLineOpenWithMenu.java new file mode 100644 index 00000000000..d6d461c4086 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileLineOpenWithMenu.java @@ -0,0 +1,377 @@ +/******************************************************************************** + * Copyright (c) 2005, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector; +import org.eclipse.debug.core.sourcelookup.containers.ProjectSourceContainer; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.IRemoteLineReference; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.ISystemTextEditor; +import org.eclipse.rse.files.ui.resources.RemoteSourceLookupDirector; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteCommandShell; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteError; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteOutput; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.part.FileEditorInput; + + +/** + * Open With menu class for openning remote files to a certain line number + */ +public class SystemRemoteFileLineOpenWithMenu extends SystemRemoteFileOpenWithMenu +{ + protected IRemoteLineReference _remoteLine; + protected IProject _associatedProject; + + public void updateSelection(IStructuredSelection selection) + { + if (selection.size() == 1) + { + Object element = selection.getFirstElement(); + if (element instanceof IRemoteLineReference) + { + + _remoteLine = (IRemoteLineReference)element; + _remoteFile = outputToFile(_remoteLine); + if (_remoteFile == null) + { + return; + } + if (_remoteLine instanceof IRemoteOutput) + { + IRemoteOutput output = (IRemoteOutput)_remoteLine; + _associatedProject = ((IRemoteCommandShell)output.getParent()).getAssociatedProject(); + } + + } + } + } + + public void fill(Menu menu, int index) + { + if (_associatedProject != null) + { + IEditorDescriptor defaultEditor = getDefaultTextEditor(); + // project file edit action if there's an associated project + IEditorDescriptor projectEditDescriptor = getPreferredEditor(_remoteFile); + createProjectFileMenuItem(menu, defaultEditor, projectEditDescriptor); + } + + super.fill(menu, index); + } + + + protected IEditorRegistry getEditorRegistry() + { + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); + } + + protected IEditorDescriptor getDefaultTextEditor() + { + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); + } + + /** + * Creates the menu item for the editor descriptor. + * + * @param menu the menu to add the item to + * @param descriptor the editor descriptor, or null for the system editor + * @param preferredEditor the descriptor of the preferred editor, or null + */ + protected void createProjectFileMenuItem(Menu menu, final IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) + { + // XXX: Would be better to use bold here, but SWT does not support it. + final MenuItem menuItem = new MenuItem(menu, SWT.RADIO); + menuItem.setSelection(true); + String pLabel = SystemMessage.sub(FileResources.RESID_OPEN_FROM_ASSOCIATED_PROJECT, "&1", _associatedProject.getName()); + menuItem.setText(pLabel); + Image image = getImage(descriptor); + if (image != null) + { + menuItem.setImage(image); + } + Listener listener = new Listener() + { + public void handleEvent(Event event) + { + switch (event.type) + { + case SWT.Selection: + if(menuItem.getSelection()) + { + openWorkspaceFile(_remoteFile, (IRemoteOutput)_remoteLine, descriptor); + } + break; + } + } + }; + menuItem.addListener(SWT.Selection, listener); + } + + + public static IRemoteFile outputToFile(IRemoteLineReference output) + { + IRemoteFile file = null; + Object parent = output.getParent(); + IRemoteFileSubSystem fs = null; + if (parent instanceof IRemoteCommandShell) + { + fs = RemoteFileUtility.getFileSubSystem(((IRemoteCommandShell)parent).getCommandSubSystem().getHost()); + } + else if (parent instanceof IRemoteFile) + { + return (IRemoteFile) parent; + } + + if (fs != null) + { + String path = output.getAbsolutePath(); + if (path != null && path.length() > 0) + { + Object obj = null; + try + { + obj = fs.getObjectWithAbsoluteName(path); + } + catch (Exception e) + { + return null; + } + if (obj != null && obj instanceof IRemoteFile) + { + file = (IRemoteFile) obj; + + return file; + } + } + } + + return file; + } + + + + protected void openEditor(IRemoteFile file, IEditorDescriptor descriptor) + { + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(file, descriptor.getId()); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell()); + handleGotoLine(); + } + + + protected void handleGotoLine() + { + handleGotoLine(_remoteFile, _remoteLine.getLine(), _remoteLine.getCharStart(), _remoteLine.getCharEnd()); + } + + + public static void handleGotoLine(IRemoteFile remoteFile, int line, int charStart, int charEnd) + { + if (line > 0) + { + IWorkbench desktop = PlatformUI.getWorkbench(); + IWorkbenchPage persp = desktop.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = null; + String fileName = remoteFile.getAbsolutePath(); + IEditorReference[] editors = persp.getEditorReferences(); + for (int i = 0; i < editors.length; i++) + { + IEditorReference ref = editors[i]; + IEditorPart editorp = ref.getEditor(false); + if (editorp != null) + { + IEditorInput einput = editorp.getEditorInput(); + if (einput instanceof IFileEditorInput) + { + IFileEditorInput input = (IFileEditorInput) einput; + IFile efile = input.getFile(); + + SystemIFileProperties properties = new SystemIFileProperties(efile); + String comparePath = properties.getRemoteFilePath(); + + if (comparePath != null && (comparePath.replace('\\','/').equals(fileName.replace('\\','/')))) + { + editor = editorp; + persp.bringToTop(editor); + if (editor instanceof ISystemTextEditor) + { + ISystemTextEditor lpex = (ISystemTextEditor)editor; + lpex.gotoLine(line); + lpex.selectText(charStart, charEnd); + + } + else + { + try + { + IMarker marker = efile.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + + IDE.gotoMarker(editor, marker); + + + } + catch (CoreException e) + { + e.printStackTrace(); + } + } + } + } + } + } + } + } + + /** + * Open workspace file associated with IRemoteCommandShell. If there is no associated project + * return. + * @param remoteFile + * @param output + * @return + */ + protected boolean openWorkspaceFile(IRemoteFile remoteFile, IRemoteOutput output, IEditorDescriptor desc) + { + IRemoteCommandShell cmd = (IRemoteCommandShell)(output.getParent()); + IProject associatedProject = cmd.getAssociatedProject(); + if (associatedProject != null) + { + ProjectSourceContainer container = new ProjectSourceContainer(associatedProject, false); + ISourceLookupDirector director = new RemoteSourceLookupDirector(); + container.init(director); + try + { + Object[] matches = container.findSourceElements(remoteFile.getName()); + for (int i = 0; i < matches.length; i++) + { + //System.out.println("match="+matches[i]); + } + + if (matches.length == 1) + { + IFile localMatch = (IFile)matches[0]; + + + + IWorkbenchPage activePage = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + + FileEditorInput finput = new FileEditorInput(localMatch); + + if (desc == null) + { + desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(remoteFile.getName()); + } + if (desc == null) + { + desc = getDefaultTextEditor(); + } + String editorid = desc.getId(); + + IEditorPart editor = activePage.openEditor(finput, editorid); + + int line = output.getLine(); + int charStart = output.getCharStart(); + int charEnd = output.getCharEnd(); + + try + { + IMarker marker = null; + + // DKM - should we? this will populate the Problems view..but resources are actually remote + if (output instanceof IRemoteError) + { + IRemoteError error = (IRemoteError)output; + String type = error.getType(); + + marker = localMatch.createMarker(IMarker.TEXT); + + if (type.equals("error")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); + } + else if (type.equals("warning")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); + } + else if (type.equals("informational")) + { + marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO); + } + + marker.setAttribute(IMarker.MESSAGE, output.getText()); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + + } + else + { + marker = localMatch.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + } + IDE.gotoMarker(editor, marker); + + + } + catch (CoreException e) + { + e.printStackTrace(); + } + return true; + } + } + catch(Exception e) + { + e.printStackTrace(); + } + } + + return false; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileOpenWithMenu.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileOpenWithMenu.java new file mode 100644 index 00000000000..e2d27632ef5 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileOpenWithMenu.java @@ -0,0 +1,358 @@ +/******************************************************************************** + * Copyright (c) 2005, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import java.text.Collator; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Hashtable; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.action.ContributionItem; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.files.ui.resources.UniversalFileTransferUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + +/** + * Open with menu class for remote files + */ +public class SystemRemoteFileOpenWithMenu extends ContributionItem +{ + protected IWorkbenchPage page; + protected IRemoteFile _remoteFile; + protected IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); + + private static Hashtable imageCache = new Hashtable(11); + + /** + * The id of this action. + */ + public static final String ID = PlatformUI.PLUGIN_ID + ".OpenWithMenu";//$NON-NLS-1$ + + /* + * Compares the labels from two IEditorDescriptor objects + */ + private static final Comparator comparer = new Comparator() + { + private Collator collator = Collator.getInstance(); + + public int compare(Object arg0, Object arg1) { + String s1 = ((IEditorDescriptor)arg0).getLabel(); + String s2 = ((IEditorDescriptor)arg1).getLabel(); + return collator.compare(s1, s2); + } + }; + + +/** + * Constructs a new instance of SystemOpenWithMenu. + */ +public SystemRemoteFileOpenWithMenu() +{ + super(ID); + this.page = null; + _remoteFile = null; +} + +/* + * Initializes the IRemoteFile + */ +public void updateSelection(IStructuredSelection selection) +{ + if (selection.size() == 1) + { + _remoteFile = (IRemoteFile)selection.getFirstElement(); + } +} + +/** + * Returns an image to show for the corresponding editor descriptor. + * + * @param editorDesc the editor descriptor, or null for the system editor + * @return the image or null + */ +protected Image getImage(IEditorDescriptor editorDesc) { + ImageDescriptor imageDesc = getImageDescriptor(editorDesc); + if (imageDesc == null) { + return null; + } + Image image = (Image) imageCache.get(imageDesc); + if (image == null) { + image = imageDesc.createImage(); + imageCache.put(imageDesc, image); + } + return image; +} + +private String getFileName() +{ + return _remoteFile.getName(); +} + +/** + * Returns the image descriptor for the given editor descriptor, + * or null if it has no image. + */ +private ImageDescriptor getImageDescriptor(IEditorDescriptor editorDesc) { + ImageDescriptor imageDesc = null; + if (editorDesc == null) { + imageDesc = registry.getImageDescriptor(getFileName()); + } + else { + imageDesc = editorDesc.getImageDescriptor(); + } + if (imageDesc == null) { + if (editorDesc.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) + imageDesc = registry.getSystemExternalEditorImageDescriptor(getFileName()); + } + return imageDesc; +} +/** + * Creates the menu item for the editor descriptor. + * + * @param menu the menu to add the item to + * @param descriptor the editor descriptor, or null for the system editor + * @param preferredEditor the descriptor of the preferred editor, or null + */ +protected void createMenuItem(Menu menu, final IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) +{ + // XXX: Would be better to use bold here, but SWT does not support it. + final MenuItem menuItem = new MenuItem(menu, SWT.RADIO); + boolean isPreferred = preferredEditor != null && descriptor.getId().equals(preferredEditor.getId()); + menuItem.setSelection(isPreferred); + menuItem.setText(descriptor.getLabel()); + Image image = getImage(descriptor); + if (image != null) { + menuItem.setImage(image); + } + Listener listener = new Listener() { + public void handleEvent(Event event) { + switch (event.type) { + case SWT.Selection: + if(menuItem.getSelection()) + { + openEditor(_remoteFile, descriptor); + } + break; + } + } + }; + menuItem.addListener(SWT.Selection, listener); +} + + +protected void openEditor(IRemoteFile file, IEditorDescriptor descriptor) +{ + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(file, descriptor.getId()); + if (descriptor.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) + { + editableFile.openInSystemEditor(SystemBasePlugin.getActiveWorkbenchShell()); + } + else + { + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell()); + } +} + + +/** + * Get the local cache of the remote file, or null if none. + * @param remoteFile the remote file. + * @return the local cached resource, or null if none. + */ +private IFile getLocalResource(IRemoteFile remoteFile) +{ + return (IFile)UniversalFileTransferUtility.getTempFileFor(remoteFile); +} + +/** + * Returns the preferred editor for the remote file. If the remote file has a cached local resource, + * then returns the default editor associated with that resource, by calling IDE.getDefaultEditor(IFile). + * Otherwise, get the default editor associated with that remote file name from the editor registry. + * @param remoteFile the remote file. + * @return the preferred editor for the remote file, or null if none. + */ +protected IEditorDescriptor getPreferredEditor(IRemoteFile remoteFile) { + + IFile localFile = getLocalResource(remoteFile); + + if (localFile == null) { + return registry.getDefaultEditor(remoteFile.getName()); + } + else { + return IDE.getDefaultEditor(localFile); + } +} + + +protected IEditorDescriptor getDefaultEditor(IRemoteFile remoteFile) +{ + IFile localFile = getLocalResource(remoteFile); + + if (localFile == null) { + return registry.getDefaultEditor(remoteFile.getName()); + } + else { + return IDE.getDefaultEditor(localFile); + } +} + +protected void setDefaultEditor(IRemoteFile remoteFile, String editorId) +{ + IFile localFile = getLocalResource(remoteFile); + + if (localFile == null) { + registry.setDefaultEditor(remoteFile.getName(), editorId); + } + else { + IDE.setDefaultEditor(localFile, editorId); + } +} + + +protected IEditorRegistry getEditorRegistry() +{ + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); +} + +protected IEditorDescriptor getDefaultTextEditor() +{ + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); +} + +/* (non-Javadoc) + * Fills the menu with perspective items. + */ +public void fill(Menu menu, int index) +{ + if (_remoteFile == null) { + return; + } + + IEditorDescriptor defaultEditor = registry.findEditor("org.eclipse.ui.DefaultTextEditor"); // may be null + IEditorDescriptor preferredEditor = getPreferredEditor(_remoteFile); // may be null + + Object[] editors = registry.getEditors(getFileName()); + Collections.sort(Arrays.asList(editors), comparer); + + boolean defaultFound = false; + + //Check that we don't add it twice. This is possible + //if the same editor goes to two mappings. + ArrayList alreadyMapped= new ArrayList(); + + for (int i = 0; i < editors.length; i++) { + IEditorDescriptor editor = (IEditorDescriptor) editors[i]; + if(!alreadyMapped.contains(editor)){ + createMenuItem(menu, editor, preferredEditor); + if (defaultEditor != null && editor.getId().equals(defaultEditor.getId())) + defaultFound = true; + alreadyMapped.add(editor); + } + } + + // Only add a separator if there is something to separate + if (editors.length > 0) + new MenuItem(menu, SWT.SEPARATOR); + + // Add default editor. Check it if it is saved as the preference. + if (!defaultFound && defaultEditor != null) { + createMenuItem(menu, defaultEditor, preferredEditor); + } + + // Add system editor (should never be null) + IEditorDescriptor descriptor = registry.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + createMenuItem(menu, descriptor, preferredEditor); + + //DKM- disable inplace editor for now + /* + // Add system in-place editor (can be null) + descriptor = registry.findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); + if (descriptor != null) { + createMenuItem(menu, descriptor, preferredEditor); + } + */ + createDefaultMenuItem(menu, _remoteFile); +} + + +/* (non-Javadoc) + * Returns whether this menu is dynamic. + */ +public boolean isDynamic() +{ + return true; +} + + +/** + * Creates the menu item for clearing the current selection. + * + * @param menu the menu to add the item to + * @param file the file bing edited + * @param registry the editor registry + */ +protected void createDefaultMenuItem(Menu menu, final IRemoteFile file) +{ + final MenuItem menuItem = new MenuItem(menu, SWT.RADIO); + IEditorDescriptor defaultEditor = getDefaultEditor(file); + menuItem.setSelection(defaultEditor == null); + menuItem.setText(FileResources.DefaultEditorDescription_name); + + Listener listener = new Listener() + { + public void handleEvent(Event event) + { + switch (event.type) + { + case SWT.Selection: + if(menuItem.getSelection()) + { + setDefaultEditor(file, null); + + IEditorDescriptor defaultEditor = getDefaultEditor(file); + openEditor(file, defaultEditor); + + } + break; + } + } + }; + + menuItem.addListener(SWT.Selection, listener); +} + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSearchOpenWithMenu.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSearchOpenWithMenu.java new file mode 100644 index 00000000000..51d4649a6c5 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSearchOpenWithMenu.java @@ -0,0 +1,148 @@ +/******************************************************************************** + * Copyright (c) 2005, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.services.search.IHostSearchResult; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteSearchResult; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + +/** + * Open with menu for remote search result openning + * + */ +public class SystemRemoteFileSearchOpenWithMenu extends + SystemRemoteFileLineOpenWithMenu +{ + protected IRemoteSearchResult _searchResult; + public void updateSelection(IStructuredSelection selection) + { + if (selection.size() == 1) + { + Object element = selection.getFirstElement(); + if (element instanceof IRemoteSearchResult) + { + _searchResult = (IRemoteSearchResult)element; + _remoteFile = outputToFile(_searchResult); + } + } + } + + protected void handleGotoLine() + { + handleGotoLine(_remoteFile, _searchResult); + } + + public static void handleGotoLine(IRemoteFile remoteFile, IHostSearchResult searchResult) { + + int line = searchResult.getLine(); + + if (line > 0) { + + IWorkbench desktop = PlatformUI.getWorkbench(); + IWorkbenchPage persp = desktop.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = null; + String fileName = remoteFile.getAbsolutePath(); + IEditorReference[] editors = persp.getEditorReferences(); + + for (int i = 0; i < editors.length; i++) { + IEditorReference ref = editors[i]; + IEditorPart editorp = ref.getEditor(false); + + if (editorp != null) { + + IEditorInput einput = editorp.getEditorInput(); + + if (einput instanceof IFileEditorInput) { + IFileEditorInput input = (IFileEditorInput)einput; + IFile efile = input.getFile(); + + SystemIFileProperties properties = new SystemIFileProperties(efile); + String comparePath = properties.getRemoteFilePath(); + + if (comparePath != null && (comparePath.replace('\\','/').equals(fileName.replace('\\','/')))) { + editor = editorp; + persp.bringToTop(editor); + + int firstStartOffset = -1; + int firstEndOffset = -1; + + int matchSize = searchResult.numOfMatches(); + + if (matchSize > 0) { + firstStartOffset = searchResult.getCharStart(0); + firstEndOffset = searchResult.getCharEnd(0); + } + /* DKM- always use markers now + if (editor instanceof ISystemTextEditor) { + ISystemTextEditor lpex = (ISystemTextEditor)editor; + lpex.gotoLine(line); + lpex.selectText(firstStartOffset, firstEndOffset); + } + else + */ + { + + try { + + // create a marker for the first match + IMarker firstMarker = createMarker(efile, line, firstStartOffset, firstEndOffset); + + int charStart = -1; + int charEnd = -1; + + for (int idx = 1; idx < matchSize; idx++) { + charStart = searchResult.getCharStart(idx); + charEnd = searchResult.getCharEnd(idx); + createMarker(efile, line, charStart, charEnd); + } + + // highlight the first marker (first match) + IDE.gotoMarker(editor, firstMarker); + } + catch (CoreException e) { + SystemBasePlugin.logError("Error occured trying to create a marker", e); + } + } + } + } + } + } + } + } + + protected static IMarker createMarker(IFile file, int line, int charStart, int charEnd) throws CoreException { + IMarker marker = file.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + return marker; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSelectAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSelectAction.java new file mode 100644 index 00000000000..8be372ed04a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFileSelectAction.java @@ -0,0 +1,504 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.ISystemAddFileListener; +import org.eclipse.rse.files.ui.dialogs.SystemRemoteFileDialog; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.actions.SystemBaseDialogAction; +import org.eclipse.rse.ui.dialogs.SystemRemoteResourceDialog; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.SystemActionViewerFilter; +import org.eclipse.swt.widgets.Shell; + + + +/** + * The action for allowing the user to select a remote folder. + *

+ * To configure the functionality, call these methods: + *

+ *

+ * To configure the text on the dialog, call these methods: + *

+ *

+ * After running, call these methods to get the output: + *

+ */ +public class SystemRemoteFileSelectAction extends SystemBaseDialogAction +{ + private String[] systemTypes; + private IHost systemConnection, outputConnection; + private IRemoteFile preSelection; + private String rootFolderAbsPath; + private String message, treeTip, dlgTitle; + private boolean showPropertySheet = false; + private boolean showPropertySheetDetailsButtonInitialState; + private boolean showPropertySheetDetailsButton = false; + private boolean multipleSelectionMode = false; + private boolean onlyConnection = false; + private IValidatorRemoteSelection selectionValidator; + private SystemActionViewerFilter customViewerFilter = null; + + /** + * Constructor that uses default action label and tooltip + * + * @param shell The shell to hang the dialog off of + */ + public SystemRemoteFileSelectAction(Shell shell) + { + this(shell, FileResources.ACTION_SELECT_DIRECTORY_LABEL, FileResources.ACTION_SELECT_DIRECTORY_TOOLTIP); + } + /** + * Constructor when you have your own action label and tooltip + * + * @param shell The shell to hang the dialog off of + * @param label + * @param tooltip + */ + public SystemRemoteFileSelectAction(Shell shell, String label, String tooltip) + { + super(label, tooltip, null, shell); + super.setNeedsProgressMonitor(true); // the default is to include a monitor. Caller can override + } + + + // ------------------------ + // CONFIGURATION METHODS... + // ------------------------ + /** + * Set the title for the dialog. The default is "Browse for Folder" + */ + public void setDialogTitle(String title) + { + this.dlgTitle = title; + } + + /** + * Set the message shown at the top of the form + */ + public void setMessage(String message) + { + this.message = message; + } + /** + * Set the tooltip text for the remote systems tree from which an item is selected. + */ + public void setSelectionTreeToolTipText(String tip) + { + this.treeTip = tip; + } + + /** + * Set the system connection to restrict the user to seeing in the tree. + * + * @see #setRootFolder(IHost, String) + */ + public void setHost(IHost conn) + { + systemConnection = conn; + onlyConnection = true; + } + /** + * Set the connection to default the selection to + */ + public void setDefaultConnection(IHost conn) + { + systemConnection = conn; + onlyConnection = false; + } + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + this.systemTypes = systemTypes; + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + } + + /** + * Set to true if a "New Connection..." special connection is to be shown for creating new connections + */ + public void setShowNewConnectionPrompt(boolean show) + { + } + + + /** + * Set the root folder from which to start listing files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + *

+ * This call effectively transforms the select dialog by: + *

+ * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + systemConnection = connection; + rootFolderAbsPath = folderAbsolutePath; + IRemoteFileSubSystem ss = RemoteFileUtility.getFileSubSystem(connection); + + if (ss != null) + { + try + { + IRemoteFile rootFolder = ss.getRemoteFileObject(rootFolderAbsPath); + if (rootFolder != null) + { + setPreSelection(rootFolder); + } + } + catch (Exception e) + { + + } + } + onlyConnection = true; + } + /** + * Set the root folder from which to start listing folders. + * This version identifies the folder via an IRemoteFile object. + * There is another overload that identifies the folder via a connection and folder path. + *

+ * This call effectively transforms the select dialog by: + *

+ * + * @param rootFolder The IRemoteFile object representing the remote folder to start the list from + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IRemoteFile rootFolder) + { + setRootFolder(rootFolder.getSystemConnection(),rootFolder.getAbsolutePath()); + } + /** + * Set a file or folder to preselect. This will: + * + * If there is no parent, then we were given a root. In which case we will + * + */ + public void setPreSelection(IRemoteFile selection) + { + preSelection = selection; + } + + + + /** + * Enable Add mode. This means the OK button is replaced with an Add button, and + * the Cancel with a Close button. When Add is pressed, the caller is called back. + * The dialog is not exited until Close is pressed. + *

+ * When a library is selected, the caller is called back to decide to enable the Add + * button or not. + */ + public void enableAddMode(ISystemAddFileListener caller) + { + } + /** + * Overloaded method that allows setting the label and tooltip text of the Add button. + * If you pass null for the label, the default is used ("Add"). + */ + public void enableAddMode(ISystemAddFileListener caller, String addLabel, String addToolTipText) + { + enableAddMode(caller); + } + + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

+ * Default is false + */ + public void setShowPropertySheet(boolean show) + { + this.showPropertySheet = show; + } + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

+ * This overload shows a Details>>> button so the user can decide if they want to see the + * property sheet. + *

+ * @param show True if to show the property sheet within the dialog + * @param initialState True if the property is to be initially displayed, false if it is not + * to be displayed until the user presses the Details button. + */ + public void setShowPropertySheet(boolean show, boolean initialState) + { + setShowPropertySheet(show); + if (show) + { + this.showPropertySheetDetailsButton = true; + this.showPropertySheetDetailsButtonInitialState = initialState; + } + } + + /** + * Set multiple selection mode. Default is single selection mode + *

+ * If you turn on multiple selection mode, you must use the getSelectedObjects() + * method to retrieve the list of selected objects. + * + * @see #getSelectedObjects() + */ + public void setMultipleSelectionMode(boolean multiple) + { + this.multipleSelectionMode = multiple; + } + + /* + * Indicates whether to allow selection of objects from differnet parents + */ + public void setAllowForMultipleParents(boolean multiple) + { + } + + /** + * Specify a validator to use when the user selects a remote file or folder. + * This allows you to decide if OK should be enabled or not for that remote file or folder. + */ + public void setSelectionValidator(IValidatorRemoteSelection selectionValidator) + { + this.selectionValidator = selectionValidator; + } + + // ----------------- + // OUTPUT METHODS... + // ----------------- + /** + * Retrieve selected file object. If multiple files selected, returns the first. + */ + public IRemoteFile getSelectedFile() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return ((IRemoteFile[])o)[0]; + else if (o instanceof IRemoteFile) + return (IRemoteFile)o; + else + return null; + } + /** + * Retrieve selected file objects. If no files selected, returns an array of zero. + * If one file selected returns an array of one. + */ + public IRemoteFile[] getSelectedFiles() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return (IRemoteFile[])o; + else if (o instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)o}; + else if (o instanceof Object[]) + { + Object[] objs= (Object[])o; + IRemoteFile[] files = new IRemoteFile[objs.length]; + for (int i = 0; i < objs.length; i++) + { + files[i]= (IRemoteFile)objs[i]; + } + return files; + } + else + return new IRemoteFile[0]; + } + + + + /** + * Return all selected objects. This method will return an array of one + * unless you have called setMultipleSelectionMode(true)! + *

+ * It will always return null if the user cancelled the dialog. + * + * @see #setMultipleSelectionMode(boolean) + */ + public Object[] getSelectedObjects() + { + Object remoteObject = getValue(); + if (remoteObject == null) + return null; + else if (remoteObject instanceof Object[]) + return (Object[])remoteObject; + else if (remoteObject instanceof IRemoteFile[]) + return (Object[])remoteObject; + else if (remoteObject instanceof Object) + return new Object[] {remoteObject}; + else + return null; + } + + /** + * Return selected connection + */ + public IHost getSelectedConnection() + { + return outputConnection; + } + + // ------------------- + // INTERNAL METHODS... + // ------------------- + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell, String title) + { + return new SystemRemoteFileDialog(shell, title); + } + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell) + { + return new SystemRemoteFileDialog(shell); + } + + /** + * Called by eclipse when user selects this action + */ + protected Dialog createDialog(Shell shell) + { + SystemRemoteResourceDialog dlg = null; + if (dlgTitle == null) + { + dlg = createRemoteResourceDialog(shell); + } + else + { + dlg = createRemoteResourceDialog(shell, dlgTitle); + } + + if (customViewerFilter != null) + { + dlg.setCustomViewerFilter(customViewerFilter); + } + dlg.setMultipleSelectionMode(multipleSelectionMode); + + if (message != null) + dlg.setMessage(message); + if (treeTip != null) + dlg.setSelectionTreeToolTipText(treeTip); + + if (systemConnection != null) + { + dlg.setDefaultSystemConnection(systemConnection, onlyConnection); + } + + if (systemTypes != null) + { + dlg.setSystemTypes(systemTypes); + } + + if (preSelection != null) + { + dlg.setPreSelection(preSelection); + } + + if (showPropertySheet) + { + if (showPropertySheetDetailsButton) + dlg.setShowPropertySheet(true, showPropertySheetDetailsButtonInitialState); + else + dlg.setShowPropertySheet(true); + } + if (selectionValidator != null) + dlg.setSelectionValidator(selectionValidator); + + return dlg; + } + + /** + * Required by parent. We return the selected object + */ + protected Object getDialogValue(Dialog dlg) + { + SystemRemoteResourceDialog ourDlg = (SystemRemoteResourceDialog)dlg; + Object outputObject = null; + outputConnection = null; + if (!ourDlg.wasCancelled()) + { + if (multipleSelectionMode) + outputObject = ourDlg.getSelectedObjects(); + else + outputObject = ourDlg.getSelectedObject(); + outputConnection = ourDlg.getSelectedConnection(); + } + return outputObject; // parent class calls setValue on what we return + } + + public void setCustomViewerFilter(SystemActionViewerFilter filter) + { + customViewerFilter = filter; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFolderSelectAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFolderSelectAction.java new file mode 100644 index 00000000000..81b263e39eb --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemRemoteFolderSelectAction.java @@ -0,0 +1,95 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.rse.files.ui.dialogs.SystemRemoteFolderDialog; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.dialogs.SystemRemoteResourceDialog; +import org.eclipse.swt.widgets.Shell; + + +public class SystemRemoteFolderSelectAction extends + SystemRemoteFileSelectAction +{ + public SystemRemoteFolderSelectAction(Shell shell) + { + super(shell); + } + + public SystemRemoteFolderSelectAction(Shell shell, String label, String tooltip) + { + super(shell, label, tooltip); + } + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell, String title) + { + return new SystemRemoteFolderDialog(shell, title); + } + + protected SystemRemoteResourceDialog createRemoteResourceDialog(Shell shell) + { + return new SystemRemoteFolderDialog(shell); + } + + /** + * Retrieve selected folder object. If multiple folders selected, returns the first. + */ + public IRemoteFile getSelectedFolder() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return ((IRemoteFile[])o)[0]; + else if (o instanceof IRemoteFile) + return (IRemoteFile)o; + else + return null; + } + /** + * Retrieve selected folder objects. If no folders selected, returns an array of zero. + * If one folder selected returns an array of one. + */ + public IRemoteFile[] getSelectedFolders() + { + Object o = getValue(); + if (o instanceof Object[]) { + + Object[] temp = (Object[])o; + + IRemoteFile[] files = new IRemoteFile[temp.length]; + + // ensure all objects are IRemoteFiles + for (int i = 0; i < temp.length; i++) { + + if (temp[i] instanceof IRemoteFile) { + files[i] = (IRemoteFile)temp[i]; + } + // should never happen + else { + return new IRemoteFile[0]; + } + } + + return files; + } + if (o instanceof IRemoteFile[]) + return (IRemoteFile[])o; + else if (o instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)o}; + else + return new IRemoteFile[0]; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemReplaceWithEditionAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemReplaceWithEditionAction.java new file mode 100644 index 00000000000..9243876b041 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemReplaceWithEditionAction.java @@ -0,0 +1,38 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.compare.internal.ICompareContextIds; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.swt.widgets.Shell; + + + +public class SystemReplaceWithEditionAction extends SystemEditionAction +{ + + public SystemReplaceWithEditionAction(Shell parent) + { + super(parent, + FileResources.ACTION_REPLACEWITH_HISTORY_LABEL, + FileResources.ACTION_REPLACEWITH_HISTORY_TOOLTIP, + "org.eclipse.compare.internal.ReplaceWithEditionAction", //$NON-NLS-1$ + true); + + this.fHelpContextId= ICompareContextIds.REPLACE_WITH_EDITION_DIALOG; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchAction.java new file mode 100644 index 00000000000..b366dc4aabc --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchAction.java @@ -0,0 +1,44 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.search.SystemSearchPage; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.search.ui.NewSearchUI; +import org.eclipse.swt.widgets.Shell; + + +public class SystemSearchAction extends SystemBaseAction { + + + public SystemSearchAction(Shell parent) { + super(SystemResources.ACTION_SEARCH_LABEL, + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_SEARCH_ID), parent); + setToolTipText(SystemResources.ACTION_SEARCH_TOOLTIP); + setHelp(SystemPlugin.HELPPREFIX + "rsdi0000"); + + allowOnMultipleSelection(false); + } + + public void run() { + NewSearchUI.openSearchDialog(SystemBasePlugin.getActiveWorkbenchWindow(), SystemSearchPage.SYSTEM_SEARCH_PAGE_ID); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchBrowseFileLineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchBrowseFileLineAction.java new file mode 100644 index 00000000000..9b4338ec4b5 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchBrowseFileLineAction.java @@ -0,0 +1,51 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteSearchResult; +import org.eclipse.swt.widgets.Shell; + + +public class SystemSearchBrowseFileLineAction extends SystemSearchEditFileLineAction { + + /** + * Constructor to create an edit action that jumps to a file line. + * @param text the label for the action. + * @param tooltip the tooltip for the action. + * @param image the image for the action. + * @param parent the parent shell. + * @param editorId the editor id. + * @param remoteFile the remote file that is to be opened. + * @param line the line number. + */ + public SystemSearchBrowseFileLineAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId, IRemoteFile remoteFile, IRemoteSearchResult searchResult) { + super(text, tooltip, image, parent, editorId, remoteFile, searchResult); + } + + /** + * @see org.eclipse.rse.files.ui.actions.SystemSearchEditFileAction#process(IRemoteFile) + */ + protected void process(IRemoteFile remoteFile) { + SystemEditableRemoteFile editableFile = new SystemEditableRemoteFile(remoteFile, _editorId); + editableFile.open(SystemBasePlugin.getActiveWorkbenchShell(), true); + handleGotoLine(_remoteFile, _searchResult); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchEditFileLineAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchEditFileLineAction.java new file mode 100644 index 00000000000..0e28b64a969 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSearchEditFileLineAction.java @@ -0,0 +1,162 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteSearchResult; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + + +/** + * Edit action used by search to create markers for all matches in a line and highlight the first match. + */ +public class SystemSearchEditFileLineAction extends SystemEditFileAction { + + protected IRemoteFile _remoteFile; + protected IRemoteSearchResult _searchResult; + + /** + * Constructor to create an edit action that jumps to a file line. + * @param text the label for the action. + * @param tooltip the tooltip for the action. + * @param image the image for the action. + * @param parent the parent shell. + * @param editorId the editor id. + * @param remoteFile the remote file that is to be opened. + * @param line the line number. + */ + public SystemSearchEditFileLineAction(String text, String tooltip, ImageDescriptor image, Shell parent, String editorId, IRemoteFile remoteFile, IRemoteSearchResult searchResult) { + super(text, tooltip, image, parent, editorId); + this._remoteFile = remoteFile; + this._searchResult = searchResult; + } + + /** + * Calls process(). + */ + public void run() { + process(_remoteFile, _searchResult); + } + + /** + * Process the remote file selection. + */ + public void process(IRemoteFile remoteFile, IRemoteSearchResult searchResult) { + super.process(remoteFile); + handleGotoLine(remoteFile, searchResult); + } + + public static void handleGotoLine(IRemoteFile remoteFile, IRemoteSearchResult searchResult) { + + int line = searchResult.getLine(); + + if (line > 0) { + + IWorkbench desktop = PlatformUI.getWorkbench(); + IWorkbenchPage persp = desktop.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = null; + String fileName = remoteFile.getAbsolutePath(); + IEditorReference[] editors = persp.getEditorReferences(); + + for (int i = 0; i < editors.length; i++) { + IEditorReference ref = editors[i]; + IEditorPart editorp = ref.getEditor(false); + + if (editorp != null) { + + IEditorInput einput = editorp.getEditorInput(); + + if (einput instanceof IFileEditorInput) { + IFileEditorInput input = (IFileEditorInput)einput; + IFile efile = input.getFile(); + + SystemIFileProperties properties = new SystemIFileProperties(efile); + String comparePath = properties.getRemoteFilePath(); + + if (comparePath != null && (comparePath.replace('\\','/').equals(fileName.replace('\\','/')))) { + editor = editorp; + persp.bringToTop(editor); + + int firstStartOffset = -1; + int firstEndOffset = -1; + + int matchSize = searchResult.numOfMatches(); + + if (matchSize > 0) { + firstStartOffset = searchResult.getCharStart(0); + firstEndOffset = searchResult.getCharEnd(0); + } + /* DKM- always use markers now + if (editor instanceof ISystemTextEditor) { + ISystemTextEditor lpex = (ISystemTextEditor)editor; + lpex.gotoLine(line); + lpex.selectText(firstStartOffset, firstEndOffset); + } + else + */ + { + + try { + + // create a marker for the first match + IMarker firstMarker = createMarker(efile, line, firstStartOffset, firstEndOffset); + + int charStart = -1; + int charEnd = -1; + + for (int idx = 1; idx < matchSize; idx++) { + charStart = searchResult.getCharStart(idx); + charEnd = searchResult.getCharEnd(idx); + createMarker(efile, line, charStart, charEnd); + } + + // highlight the first marker (first match) + IDE.gotoMarker(editor, firstMarker); + } + catch (CoreException e) { + SystemBasePlugin.logError("Error occured trying to create a marker", e); + } + } + } + } + } + } + } + } + + protected static IMarker createMarker(IFile file, int line, int charStart, int charEnd) throws CoreException { + IMarker marker = file.createMarker(IMarker.TEXT); + marker.setAttribute(IMarker.LINE_NUMBER, line); + marker.setAttribute(IMarker.CHAR_START, charStart); + marker.setAttribute(IMarker.CHAR_END, charEnd); + return marker; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectFileTypesAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectFileTypesAction.java new file mode 100644 index 00000000000..cc44062e176 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectFileTypesAction.java @@ -0,0 +1,157 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.ui.actions.SystemBaseDialogAction; +import org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog; +import org.eclipse.swt.widgets.Shell; + + +/** + * The action for allowing the user to select one or more file types, using the Eclipse + * dialog for this. The types are from the file editor registry, as specified in the + * Workbench preferences. + *

+ * To set preselected types, use {@link #setTypes(List)} or {@link #setTypes(String[])}. + * Or, if you have single string of comma-separated types, call {@link #setTypes(String)}. + *

+ * After running, and checking wasCancelled(), you can query the selected types + * using one of: + *

    + *
  1. {@link #getTypes()} to retrieve the selected types as a List + *
  2. {@link #getTypesArray()} to retrieve the selected types as a String array + *
  3. {@link #getTypesString()} to retrieve the selected types as a single String of comma-delimited selections + *

    + * Note the types are remembered after running, so a subsequent run will result in the previous types + * being preselected, assuming you re-use the same instance of this class. + * + * @see org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog + */ +public class SystemSelectFileTypesAction extends SystemBaseDialogAction +{ + protected List types = new ArrayList(); + + /** + * Constructor + * To set preselected types, use {@link #setTypes(List)} or {@link #setTypes(String[])}. + * Note the types are remember after running, so a subsequent run will result in the previous types + * being preselected. + */ + public SystemSelectFileTypesAction(Shell shell) + { + super(SystemFileResources.ACTION_SELECTFILETYPES_LABEL, SystemFileResources.ACTION_SELECTFILETYPES_TOOLTIP, null, shell); + } + + /** + * Set the current input types as a String array. + * Each type is a file name extension, without the dot, as in "java" or "class" + */ + public void setTypes(String[] types) + { + this.types = Arrays.asList(types); + } + /** + * Set the current input types as a java.util List, such as ArrayList + * Each type is a file name extension, without the dot, as in "java" or "class" + */ + public void setTypes(List types) + { + this.types = types; + } + /** + * Set the current input types given a comma-separated list as a single String. + */ + public void setTypes(String typeString) + { + setTypes(RemoteFileFilterString.parseTypes(typeString)); + } + + /** + * Get the selected file types after running the action. Returns an ArrayList + */ + public List getTypes() + { + return types; + } + /** + * Get the selected file types after running the action. Returns a String array + */ + public String[] getTypesArray() + { + String[] typesArray = new String[types.size()]; + Iterator i = types.iterator(); + int idx=0; + while (i.hasNext()) + typesArray[idx++] = (String)i.next(); + return typesArray; + } + /** + * Get the selected file types as a concatenated list of strings, comma-separated + */ + public String getTypesString() + { + return RemoteFileFilterString.getTypesString(getTypesArray()); + } + + /** + * Return true if the dialog was cancelled by the user. + * Only valid after calling run(). + */ + public boolean wasCancelled() + { + return (getValue() == null); + } + + + /** + * Create and return the dialog + */ + public Dialog createDialog(Shell parent) + { + SystemSelectFileTypesDialog dialog = + new SystemSelectFileTypesDialog(getShell(), types); + return dialog; + } + + /** + * Parent abstract method. + * Called after dialog runs, to retrieve the value from the dialog. + * Will return null if dialog cancelled. + */ + public Object getDialogValue(Dialog dlg) + { + Object[] result = ((SystemSelectFileTypesDialog)dlg).getResult(); + if (result != null) + { + types = new ArrayList(result.length); + for (int idx = 0; idx < result.length; idx++) + types.add(result[idx]); + return types; + } + else + return null; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFileAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFileAction.java new file mode 100644 index 00000000000..b04151ce285 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFileAction.java @@ -0,0 +1,524 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.ISystemAddFileListener; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseDialogAction; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.swt.widgets.Shell; + + +/** + * The action for allowing the user to select a remote file. + *

    + * To configure, call these methods: + *

    + *

    + * Call these methods to configure the text on the dialog + *

    + *

    + * After running, call these methods to get the output: + *

    + */ +public class SystemSelectRemoteFileAction extends SystemBaseDialogAction +{ + private String[] systemTypes; + private IHost systemConnection, outputConnection; + private IHost rootFolderConnection; + private IRemoteFile preSelection; + private String rootFolderAbsPath, fileTypes; + private String message, treeTip, dlgTitle; + private String addLabel, addToolTipText; + private int expandDepth = 0; + private boolean showNewConnectionPrompt = true; + private boolean restrictFolders = false; + private boolean showPropertySheet = false; + private boolean showPropertySheetDetailsButtonInitialState; + private boolean showPropertySheetDetailsButton = false; + private boolean multipleSelectionMode = false; + private boolean onlyConnection = false; + private boolean allowFolderSelection = true; + private ISystemAddFileListener addButtonCallback = null; + private IValidatorRemoteSelection selectionValidator; + private List viewerFilters = new ArrayList(); + + /** + * Constructor that uses default action label and tooltip + * + * @param shell The shell to hang the dialog off of + */ + public SystemSelectRemoteFileAction(Shell shell) + { + this(shell, FileResources.ACTION_SELECT_FILE_LABEL, FileResources.ACTION_SELECT_FILE_TOOLTIP); + } + /** + * Constructor when you have your own action label and tooltip + * + * @param shell The shell to hang the dialog off of + * @param label + * @param tooltip + */ + public SystemSelectRemoteFileAction(Shell shell, String label, String tooltip) + { + super(label, tooltip, null, shell); + super.setNeedsProgressMonitor(true); // the default is to include a monitor. Caller can override + } + + + // ------------------------ + // CONFIGURATION METHODS... + // ------------------------ + /** + * Set the system connection to restrict the user to seeing in the tree. + * + * @see #setRootFolder(IHost, String) + */ + public void setHost(IHost conn) + { + systemConnection = conn; + onlyConnection = true; + } + /** + * Set the connection to default the selection to + */ + public void setDefaultConnection(IHost conn) + { + systemConnection = conn; + onlyConnection = false; + } + + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + this.systemTypes = systemTypes; + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + } + + /** + * Set to true if a "New Connection..." special connection is to be shown for creating new connections + */ + public void setShowNewConnectionPrompt(boolean show) + { + this.showNewConnectionPrompt = show; + } + + /** + * Specify the zero-based auto-expand level for the tree. The default is zero, meaning + * only show the connections. + */ + public void setAutoExpandDepth(int depth) + { + this.expandDepth = depth; + } + + /** + * Set the root folder from which to start listing files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + rootFolderConnection = connection; + rootFolderAbsPath = folderAbsolutePath; + } + /** + * Set the root folder from which to start listing files. + * This version identifies the folder via an IRemoteFile object. + * There is another overload that identifies the folder via a connection and folder path. + * + * @param rootFolder The IRemoteFile object representing the remote folder to start the list from + */ + public void setRootFolder(IRemoteFile rootFolder) + { + setRootFolder(rootFolder.getSystemConnection(),rootFolder.getAbsolutePath()); + } + /** + * Set a file or folder to preselect. This will: + * + * If there is no parent, then we were given a root. In which case we will + * + */ + public void setPreSelection(IRemoteFile selection) + { + preSelection = selection; + } + + /** + * For files mode, restrict the files list by an array of file types + */ + public void setFileTypes(String[] fileTypes) + { + if (fileTypes != null) + this.fileTypes = RemoteFileFilterString.getTypesString(fileTypes); + else + this.fileTypes = null; + } + /** + * For files mode, restrict the files list by a comman-delimited array of file types. + * The last type must also end in a comma. Eg "java, class," or "class,". + */ + public void setFileTypes(String fileTypes) + { + this.fileTypes = fileTypes; + } + + /** + * Specify whether setRootFolder should prevent the user from being able to see or select + * any other folder. This causes two effects: + *
      + *
    1. The special filter for root/drives is not shown + *
    2. No subfolders are listed in the root folder + *
    + */ + public void setRestrictFolders(boolean restrict) + { + this.restrictFolders = restrict; + } + + /** + * Enable Add mode. This means the OK button is replaced with an Add button, and + * the Cancel with a Close button. When Add is pressed, the caller is called back. + * The dialog is not exited until Close is pressed. + *

    + * When a library is selected, the caller is called back to decide to enable the Add + * button or not. + */ + public void enableAddMode(ISystemAddFileListener caller) + { + this.addButtonCallback = caller; + } + /** + * Overloaded method that allows setting the label and tooltip text of the Add button. + * If you pass null for the label, the default is used ("Add"). + */ + public void enableAddMode(ISystemAddFileListener caller, String addLabel, String addToolTipText) + { + enableAddMode(caller); + this.addLabel = addLabel; + this.addToolTipText = addToolTipText; + } + + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * Default is false + */ + public void setShowPropertySheet(boolean show) + { + this.showPropertySheet = show; + } + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * This overload shows a Details>>> button so the user can decide if they want to see the + * property sheet. + *

    + * @param show True if to show the property sheet within the dialog + * @param initialState True if the property is to be initially displayed, false if it is not + * to be displayed until the user presses the Details button. + */ + public void setShowPropertySheet(boolean show, boolean initialState) + { + setShowPropertySheet(show); + if (show) + { + this.showPropertySheetDetailsButton = true; + this.showPropertySheetDetailsButtonInitialState = initialState; + } + } + + /** + * Set multiple selection mode. Default is single selection mode + *

    + * If you turn on multiple selection mode, you must use the getSelectedObjects() + * method to retrieve the list of selected objects. + *

    + * Further, if you turn this on, it has the side effect of allowing the user + * to select any remote object. The assumption being if you are prompting for + * files, you also want to allow the user to select a folder, with the meaning + * being that all files within the folder are implicitly selected. + * + * @see #getSelectedObjects() + */ + public void setMultipleSelectionMode(boolean multiple) + { + this.multipleSelectionMode = multiple; + } + /** + * Specify a validator to use when the user selects a remote file or folder. + * This allows you to decide if OK should be enabled or not for that remote file or folder. + */ + public void setSelectionValidator(IValidatorRemoteSelection selectionValidator) + { + this.selectionValidator = selectionValidator; + } + + + // ----------------------------------------------- + // MRI METHODS. THESE ONLY NEED BE + // CALLED IF YOU WISH TO CHANGE THE DEFAULT MRI... + // ----------------------------------------------- + /** + * Set the title for the dialog. The default is "Browse for Folder" + */ + public void setDialogTitle(String title) + { + this.dlgTitle = title; + } + /** + * Set the message shown at the top of the form + */ + public void setMessage(String message) + { + this.message = message; + } + /** + * Set the tooltip text for the remote systems tree from which an item is selected. + */ + public void setSelectionTreeToolTipText(String tip) + { + this.treeTip = tip; + } + + + // ----------------- + // OUTPUT METHODS... + // ----------------- + + /** + * Retrieve selected file object. If multiple files selected, returns the first. + */ + public IRemoteFile getSelectedFile() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return ((IRemoteFile[])o)[0]; + else if (o instanceof IRemoteFile) + return (IRemoteFile)o; + else + return null; + } + /** + * Retrieve selected file objects. If no files selected, returns an array of zero. + * If one file selected returns an array of one. + */ + public IRemoteFile[] getSelectedFiles() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return (IRemoteFile[])o; + else if (o instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)o}; + else + return new IRemoteFile[0]; + } + + /** + * Return all selected objects. This method will return an array of one + * unless you have called setMultipleSelectionMode(true)! + * @see #setMultipleSelectionMode(boolean) + */ + public Object[] getSelectedObjects() + { + Object remoteObject = getValue(); + if (remoteObject == null) + return null; + else if (remoteObject instanceof Object[]) + return (Object[])remoteObject; + else if (remoteObject instanceof IRemoteFile[]) + return (Object[])remoteObject; + else if (remoteObject instanceof Object) + return new Object[] {remoteObject}; + else + return null; + } + + /** + * Return selected connection + */ + public IHost getSelectedConnection() + { + return outputConnection; + } + + // ------------------- + // INTERNAL METHODS... + // ------------------- + + /** + * Called by eclipse when user selects this action + */ + protected Dialog createDialog(Shell shell) + { + SystemSelectRemoteFileOrFolderDialog dlg = null; + if (dlgTitle == null) + dlg = new SystemSelectRemoteFileOrFolderDialog(shell, true); // true => file vs folder mode + else + dlg = new SystemSelectRemoteFileOrFolderDialog(shell, dlgTitle, true); // true => file vs folder mode + dlg.setShowNewConnectionPrompt(showNewConnectionPrompt); + dlg.setMultipleSelectionMode(multipleSelectionMode); + if (restrictFolders) + dlg.setRestrictFolders(true); + if (message != null) + dlg.setMessage(message); + if (treeTip != null) + dlg.setSelectionTreeToolTipText(treeTip); + if (systemConnection != null) + { + if (onlyConnection) + dlg.setSystemConnection(systemConnection); + else + dlg.setDefaultConnection(systemConnection); + } + if (systemTypes != null) + dlg.setSystemTypes(systemTypes); + if (expandDepth != 0) + dlg.setAutoExpandDepth(expandDepth); + if (fileTypes != null) + dlg.setFileTypes((String)fileTypes); // must be called before setRootFolder! + if (preSelection != null) + dlg.setPreSelection(preSelection); + else if (rootFolderConnection != null) + dlg.setRootFolder(rootFolderConnection, rootFolderAbsPath); + if (showPropertySheet) + if (showPropertySheetDetailsButton) + dlg.setShowPropertySheet(true, showPropertySheetDetailsButtonInitialState); + else + dlg.setShowPropertySheet(true); + if (addButtonCallback != null) + if ((addLabel!=null) || (addToolTipText!=null)) + dlg.enableAddMode(addButtonCallback, addLabel, addToolTipText); + else + dlg.enableAddMode(addButtonCallback); + if (selectionValidator != null) + dlg.setSelectionValidator(selectionValidator); + + if (!allowFolderSelection) { + dlg.setAllowFolderSelection(allowFolderSelection); + } + + // add viewer filters if any + if (viewerFilters != null) { + Iterator iter = viewerFilters.iterator(); + + while (iter.hasNext()) { + ViewerFilter filter = (ViewerFilter)(iter.next()); + dlg.addViewerFilter(filter); + } + } + + return dlg; + } + + /** + * Required by parent. We return the selected object + */ + protected Object getDialogValue(Dialog dlg) + { + SystemSelectRemoteFileOrFolderDialog ourDlg = (SystemSelectRemoteFileOrFolderDialog)dlg; + Object outputObject = null; + outputConnection = null; + if (!ourDlg.wasCancelled()) + { + outputConnection = ourDlg.getSelectedConnection(); + if (multipleSelectionMode) + outputObject = ourDlg.getSelectedObjects(); + else + outputObject = ourDlg.getSelectedObject(); + } + return outputObject; // parent class calls setValue on what we return + } + + /** + * Add viewer filter. + * @param filter a viewer filter. + */ + public void addViewerFilter(ViewerFilter filter) { + viewerFilters.add(filter); + } + + /** + * Sets whether to allow folder selection. The default selection validator will use this to + * determine whether the OK button will be enabled when a folder is selected. The default + * is true. + * @param allow true to allow folder selection, false otherwise. + */ + public void setAllowFolderSelection(boolean allow) { + allowFolderSelection = allow; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFolderAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFolderAction.java new file mode 100644 index 00000000000..8b9f908f11f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemSelectRemoteFolderAction.java @@ -0,0 +1,502 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.ISystemAddFileListener; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.actions.SystemBaseDialogAction; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.swt.widgets.Shell; + + + +/** + * The action for allowing the user to select a remote folder. + *

    + * To configure the functionality, call these methods: + *

    + *

    + * To configure the text on the dialog, call these methods: + *

    + *

    + * After running, call these methods to get the output: + *

    + */ +public class SystemSelectRemoteFolderAction extends SystemBaseDialogAction +{ + private String[] systemTypes; + private IHost systemConnection, outputConnection; + private IHost rootFolderConnection; + private IRemoteFile preSelection; + private String rootFolderAbsPath; + private String message, treeTip, dlgTitle; + private String addLabel, addToolTipText; + private int expandDepth = 0; + private boolean showNewConnectionPrompt = true; + private boolean restrictFolders = false; + private boolean showPropertySheet = false; + private boolean showPropertySheetDetailsButtonInitialState; + private boolean showPropertySheetDetailsButton = false; + private boolean multipleSelectionMode = false; + private boolean allowForMultipleParents = false; + private boolean onlyConnection = false; + private ISystemAddFileListener addButtonCallback = null; + private IValidatorRemoteSelection selectionValidator; + + /** + * Constructor that uses default action label and tooltip + * + * @param shell The shell to hang the dialog off of + */ + public SystemSelectRemoteFolderAction(Shell shell) + { + this(shell, FileResources.ACTION_SELECT_DIRECTORY_LABEL, FileResources.ACTION_SELECT_DIRECTORY_TOOLTIP); + } + /** + * Constructor when you have your own action label and tooltip + * + * @param shell The shell to hang the dialog off of + * @param label + * @param tooltip + */ + public SystemSelectRemoteFolderAction(Shell shell, String label, String tooltip) + { + super(label, tooltip, null, shell); + super.setNeedsProgressMonitor(true); // the default is to include a monitor. Caller can override + } + + + // ------------------------ + // CONFIGURATION METHODS... + // ------------------------ + /** + * Set the title for the dialog. The default is "Browse for Folder" + */ + public void setDialogTitle(String title) + { + this.dlgTitle = title; + } + + /** + * Set the message shown at the top of the form + */ + public void setMessage(String message) + { + this.message = message; + } + /** + * Set the tooltip text for the remote systems tree from which an item is selected. + */ + public void setSelectionTreeToolTipText(String tip) + { + this.treeTip = tip; + } + + /** + * Set the system connection to restrict the user to seeing in the tree. + * + * @see #setRootFolder(IHost, String) + */ + public void setHost(IHost conn) + { + systemConnection = conn; + onlyConnection = true; + } + /** + * Set the connection to default the selection to + */ + public void setDefaultConnection(IHost conn) + { + systemConnection = conn; + onlyConnection = false; + } + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + this.systemTypes = systemTypes; + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + } + + /** + * Set to true if a "New Connection..." special connection is to be shown for creating new connections + */ + public void setShowNewConnectionPrompt(boolean show) + { + this.showNewConnectionPrompt = show; + } + /** + * Specify the zero-based auto-expand level for the tree. The default is zero, meaning + * only show the connections. + */ + public void setAutoExpandDepth(int depth) + { + this.expandDepth = depth; + } + + /** + * Set the root folder from which to start listing files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + *

    + * This call effectively transforms the select dialog by: + *

    + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + rootFolderConnection = connection; + rootFolderAbsPath = folderAbsolutePath; + } + /** + * Set the root folder from which to start listing folders. + * This version identifies the folder via an IRemoteFile object. + * There is another overload that identifies the folder via a connection and folder path. + *

    + * This call effectively transforms the select dialog by: + *

    + * + * @param rootFolder The IRemoteFile object representing the remote folder to start the list from + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IRemoteFile rootFolder) + { + setRootFolder(rootFolder.getSystemConnection(),rootFolder.getAbsolutePath()); + } + /** + * Set a file or folder to preselect. This will: + * + * If there is no parent, then we were given a root. In which case we will + * + */ + public void setPreSelection(IRemoteFile selection) + { + preSelection = selection; + } + + /** + * Specify whether setRootFolder should prevent the user from being able to see or select + * any other folder. This causes this effect: + *
      + *
    1. The special filter for root/drives is not shown + *
    + */ + public void setRestrictFolders(boolean restrict) + { + restrictFolders = true; + } + + /** + * Enable Add mode. This means the OK button is replaced with an Add button, and + * the Cancel with a Close button. When Add is pressed, the caller is called back. + * The dialog is not exited until Close is pressed. + *

    + * When a library is selected, the caller is called back to decide to enable the Add + * button or not. + */ + public void enableAddMode(ISystemAddFileListener caller) + { + this.addButtonCallback = caller; + } + /** + * Overloaded method that allows setting the label and tooltip text of the Add button. + * If you pass null for the label, the default is used ("Add"). + */ + public void enableAddMode(ISystemAddFileListener caller, String addLabel, String addToolTipText) + { + enableAddMode(caller); + this.addLabel = addLabel; + this.addToolTipText = addToolTipText; + } + + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * Default is false + */ + public void setShowPropertySheet(boolean show) + { + this.showPropertySheet = show; + } + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * This overload shows a Details>>> button so the user can decide if they want to see the + * property sheet. + *

    + * @param show True if to show the property sheet within the dialog + * @param initialState True if the property is to be initially displayed, false if it is not + * to be displayed until the user presses the Details button. + */ + public void setShowPropertySheet(boolean show, boolean initialState) + { + setShowPropertySheet(show); + if (show) + { + this.showPropertySheetDetailsButton = true; + this.showPropertySheetDetailsButtonInitialState = initialState; + } + } + + /** + * Set multiple selection mode. Default is single selection mode + *

    + * If you turn on multiple selection mode, you must use the getSelectedObjects() + * method to retrieve the list of selected objects. + * + * @see #getSelectedObjects() + */ + public void setMultipleSelectionMode(boolean multiple) + { + this.multipleSelectionMode = multiple; + } + + /* + * Indicates whether to allow selection of objects from differnet parents + */ + public void setAllowForMultipleParents(boolean multiple) + { + this.allowForMultipleParents = multiple; + } + + /** + * Specify a validator to use when the user selects a remote file or folder. + * This allows you to decide if OK should be enabled or not for that remote file or folder. + */ + public void setSelectionValidator(IValidatorRemoteSelection selectionValidator) + { + this.selectionValidator = selectionValidator; + } + + // ----------------- + // OUTPUT METHODS... + // ----------------- + + + /** + * Retrieve selected folder object. If multiple folders selected, returns the first. + */ + public IRemoteFile getSelectedFolder() + { + Object o = getValue(); + if (o instanceof IRemoteFile[]) + return ((IRemoteFile[])o)[0]; + else if (o instanceof IRemoteFile) + return (IRemoteFile)o; + else + return null; + } + /** + * Retrieve selected folder objects. If no folders selected, returns an array of zero. + * If one folder selected returns an array of one. + */ + public IRemoteFile[] getSelectedFolders() + { + Object o = getValue(); + if (o instanceof Object[]) { + + Object[] temp = (Object[])o; + + IRemoteFile[] files = new IRemoteFile[temp.length]; + + // ensure all objects are IRemoteFiles + for (int i = 0; i < temp.length; i++) { + + if (temp[i] instanceof IRemoteFile) { + files[i] = (IRemoteFile)temp[i]; + } + // should never happen + else { + return new IRemoteFile[0]; + } + } + + return files; + } + if (o instanceof IRemoteFile[]) + return (IRemoteFile[])o; + else if (o instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)o}; + else + return new IRemoteFile[0]; + } + + /** + * Return all selected objects. This method will return an array of one + * unless you have called setMultipleSelectionMode(true)! + *

    + * It will always return null if the user cancelled the dialog. + * + * @see #setMultipleSelectionMode(boolean) + */ + public Object[] getSelectedObjects() + { + Object remoteObject = getValue(); + if (remoteObject == null) + return null; + else if (remoteObject instanceof Object[]) + return (Object[])remoteObject; + else if (remoteObject instanceof IRemoteFile[]) + return (Object[])remoteObject; + else if (remoteObject instanceof Object) + return new Object[] {remoteObject}; + else + return null; + } + + /** + * Return selected connection + */ + public IHost getSelectedConnection() + { + return outputConnection; + } + + // ------------------- + // INTERNAL METHODS... + // ------------------- + + /** + * Called by eclipse when user selects this action + */ + protected Dialog createDialog(Shell shell) + { + SystemSelectRemoteFileOrFolderDialog dlg = null; + if (dlgTitle == null) + dlg = new SystemSelectRemoteFileOrFolderDialog(shell, false); // false => folder vs file mode + else + dlg = new SystemSelectRemoteFileOrFolderDialog(shell, dlgTitle, false); // false => folder vs file mode + dlg.setShowNewConnectionPrompt(showNewConnectionPrompt); + dlg.setMultipleSelectionMode(multipleSelectionMode); + dlg.setAllowForMultipleParents(allowForMultipleParents); + if (restrictFolders) + dlg.setRestrictFolders(true); + if (message != null) + dlg.setMessage(message); + if (treeTip != null) + dlg.setSelectionTreeToolTipText(treeTip); + if (systemConnection != null) + { + if (onlyConnection) + dlg.setSystemConnection(systemConnection); + else + dlg.setDefaultConnection(systemConnection); + } + if (systemTypes != null) + dlg.setSystemTypes(systemTypes); + if (expandDepth != 0) + dlg.setAutoExpandDepth(expandDepth); + if (preSelection != null) + dlg.setPreSelection(preSelection); + else if (rootFolderConnection != null) + dlg.setRootFolder(rootFolderConnection, rootFolderAbsPath); + if (showPropertySheet) + if (showPropertySheetDetailsButton) + dlg.setShowPropertySheet(true, showPropertySheetDetailsButtonInitialState); + else + dlg.setShowPropertySheet(true); + if (addButtonCallback != null) + if ((addLabel!=null) || (addToolTipText!=null)) + dlg.enableAddMode(addButtonCallback, addLabel, addToolTipText); + else + dlg.enableAddMode(addButtonCallback); + if (selectionValidator != null) + dlg.setSelectionValidator(selectionValidator); + + return dlg; + } + + /** + * Required by parent. We return the selected object + */ + protected Object getDialogValue(Dialog dlg) + { + SystemSelectRemoteFileOrFolderDialog ourDlg = (SystemSelectRemoteFileOrFolderDialog)dlg; + Object outputObject = null; + outputConnection = null; + if (!ourDlg.wasCancelled()) + { + if (multipleSelectionMode) + outputObject = ourDlg.getSelectedObjects(); + else + outputObject = ourDlg.getSelectedObject(); + outputConnection = ourDlg.getSelectedConnection(); + } + return outputObject; // parent class calls setValue on what we return + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemUploadConflictAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemUploadConflictAction.java new file mode 100644 index 00000000000..dc05ee91aef --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/actions/SystemUploadConflictAction.java @@ -0,0 +1,538 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.actions; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.window.Window; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.ISaveAsDialog; +import org.eclipse.rse.files.ui.resources.SaveAsDialog; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemBaseAction; +import org.eclipse.rse.ui.dialogs.SystemPromptDialog; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.part.FileEditorInput; + + +/** + * This is the default action used to handle upload conflicts + */ +public class SystemUploadConflictAction extends SystemBaseAction implements Runnable +{ + + /** + * This is the default dialog used to handle upload conflicts + */ + private class UploadConflictDialog extends SystemPromptDialog implements ISystemMessages, SelectionListener + { + private Button _overwriteLocalButton; + private Button _overwriteRemoteButton; + private Button _saveasButton; + private Button _browseButton; + private Text _saveasFileEntry; + + private boolean _overwriteLocal; + private boolean _overwriteRemote; + private boolean _saveas; + + private SystemMessage _errorMessage; + + private IRemoteFile _saveasLocation; + + /** + * Constructor. + * @param shell the parent shell of the dialog + */ + public UploadConflictDialog(Shell shell) + { + super(shell, FileResources.RESID_CONFLICT_SAVE_TITLE); + //pack(); + } + + /** + * Called when a button is pressed in the dialog + */ + protected void buttonPressed(int buttonId) + { + setReturnCode(buttonId); + _overwriteLocal = _overwriteLocalButton.getSelection(); + _overwriteRemote = _overwriteRemoteButton.getSelection(); + _saveas = _saveasButton.getSelection(); + close(); + } + + /** + * Returns whether the user decided to overwrite the local file + * @return whether the user decided to overwrite the local file + */ + public boolean getOverwriteLocal() + { + return _overwriteLocal; + } + + /** + * Returns whether the user decided to overwrite the remote file + * @return whether the user decided to overwrite the remote file + */ + public boolean getOverwriteRemote() + { + return _overwriteRemote; + } + + /** + * Returns whether the user decided to save to a different location + * @return whether the user decided to save to a different location + */ + public boolean getSaveas() + { + return _saveas; + } + + /** + * Returns the location where the cached file should be saved to + * @return the location where the cached file should be saved to + */ + public IRemoteFile getSaveasLocation() + { + return _saveasLocation; + } + + /** + * Creates the dialog contents. + */ + public Control createInner(Composite parent) + { + Image image = getShell().getDisplay().getSystemImage(SWT.ICON_QUESTION); + + Composite c = new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + c.setLayout(layout); + c.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Composite m = new Composite(c, SWT.NONE); + + GridLayout mlayout = new GridLayout(); + mlayout.numColumns = 2; + m.setLayout(mlayout); + m.setLayoutData(new GridData(GridData.FILL_BOTH)); + + Label label = new Label(m, 0); + image.setBackground(label.getBackground()); + label.setImage(image); + label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_BEGINNING)); + + Text text = new Text(m, SWT.WRAP | SWT.MULTI); + text.setEditable(false); + text.setText(FileResources.RESID_CONFLICT_SAVE_MESSAGE); + + GridData textData = new GridData(GridData.FILL_BOTH); + textData.widthHint = 100; + textData.horizontalSpan = 2; + textData.verticalSpan = 5; + + Composite options = new Composite(c, SWT.NONE); + GridLayout olayout = new GridLayout(); + olayout.numColumns = 1; + options.setLayout(olayout); + options.setLayoutData(new GridData(GridData.FILL_BOTH)); + + _overwriteLocalButton = new Button(options, SWT.RADIO); + _overwriteLocalButton.setText(FileResources.RESID_CONFLICT_SAVE_REPLACELOCAL); + _overwriteLocalButton.addSelectionListener(this); + _overwriteLocalButton.setSelection(true); + + _overwriteRemoteButton = new Button(options, SWT.RADIO); + _overwriteRemoteButton.setText(FileResources.RESID_CONFLICT_SAVE_OVERWRITEREMOTE); + _overwriteRemoteButton.addSelectionListener(this); + + _saveasButton = new Button(options, SWT.RADIO); + _saveasButton.setText(FileResources.RESID_CONFLICT_SAVE_SAVETODIFFERENT); + _saveasButton.addSelectionListener(this); + + Composite s = new Composite(options, SWT.NONE); + GridLayout slayout = new GridLayout(); + slayout.numColumns = 2; + s.setLayout(slayout); + s.setLayoutData(new GridData(GridData.FILL_BOTH)); + + _saveasFileEntry = new Text(s, SWT.BORDER); + _saveasFileEntry.setEnabled(false); + + GridData fileEntryData = new GridData(GridData.FILL_BOTH); + fileEntryData.widthHint = 100; + _saveasFileEntry.setLayoutData(fileEntryData); + _saveasFileEntry.setEditable(false); + + _browseButton = new Button(s, SWT.PUSH); + _browseButton.setText(SystemResources.BUTTON_BROWSE); + _browseButton.addSelectionListener(this); + _browseButton.setEnabled(false); + + setHelp(); + + return c; + } + + /** + * Called when a widget is selected + */ + public void widgetSelected(SelectionEvent e) + { + if (_saveasButton.getSelection()) + { + _browseButton.setEnabled(true); + _saveasFileEntry.setEnabled(true); + if (_saveasLocation != null) + { + _errorMessage = null; + setErrorMessage(_errorMessage); + enableOkButton(true); + } + else + { + enableOkButton(false); + _errorMessage = SystemPlugin.getPluginMessage(MSG_VALIDATE_PATH_EMPTY); + setErrorMessage(_errorMessage); + } + } + else + { + _browseButton.setEnabled(false); + _saveasFileEntry.setEnabled(false); + enableOkButton(true); + _errorMessage = null; + setErrorMessage(_errorMessage); + } + + if (e.getSource() == _browseButton) + { + + ISaveAsDialog dlg = SaveAsDialog.getSaveAsDialog(getShell()); + dlg.setMultipleSelectionMode(false); + + if (_remoteFile != null) + { + dlg.setPreSelection(_remoteFile); + + if (dlg.open() == OK) + { + Object output = dlg.getOutputObject(); + if (output instanceof IRemoteFile) + { + IRemoteFile toCreate = (IRemoteFile) output; + // validate + try + { + _errorMessage = null; + _saveasLocation = toCreate; + _saveasFileEntry.setText(toCreate.getAbsolutePath()); + + enableOkButton(_errorMessage == null); + + setErrorMessage(_errorMessage); + } + catch (Exception ex) + { + } + } + } + } + } + + } + + public void widgetDefaultSelected(SelectionEvent e) + { + } + + /** + * Returns the initial focus control + * @return the initial focus control + */ + protected Control getInitialFocusControl() + { + enableOkButton(true); + return _overwriteLocalButton; + } + + private void setHelp() + { + setHelp(SystemPlugin.HELPPREFIX + "scdl0000"); + } + } + + /** + * Action used to close a specified editor + */ + public class CloseEditorAction implements Runnable + { + public IEditorPart _editor; + + public CloseEditorAction(IEditorPart editor) + { + _editor = editor; + } + + public void run() + { + // close old editor + SystemBasePlugin.getActiveWorkbenchWindow().getActivePage().closeEditor(_editor, false); + } + } + + /** + * Action used to reopen the editor for a cached file with a remote file from a different location + */ + public class ReopenAction implements Runnable + { + private IFile _tempFile; + private IRemoteFile _saveasFile; + + public ReopenAction(IFile tempFile, IRemoteFile saveasFile) + { + _tempFile = tempFile; + _saveasFile = saveasFile; + } + + private IEditorPart getEditorFor(IFile tempFile) + { + + IWorkbenchWindow window = SystemBasePlugin.getActiveWorkbenchWindow(); + if (window != null) + { + IWorkbenchPage page = window.getActivePage(); + if (page != null) + { + IEditorPart editor = page.getActiveEditor(); + IEditorInput input = editor.getEditorInput(); + if (input instanceof FileEditorInput) + { + FileEditorInput finput = (FileEditorInput) input; + if (finput.getFile().getFullPath().equals(tempFile.getFullPath())) + { + return editor; + } + } + } + } + + return null; + } + + public void run() + { + try + { + _saveasFile = _saveasFile.getParentRemoteFileSubSystem().getRemoteFileObject(_saveasFile.getAbsolutePath()); + SystemPlugin.getTheSystemRegistry().fireEvent(new SystemResourceChangeEvent(_saveasFile.getParentRemoteFile(), ISystemResourceChangeEvents.EVENT_REFRESH, null)); + + } + catch (SystemMessageException e) + { + e.printStackTrace(); + } + + // close editor + IEditorPart editor = getEditorFor(_tempFile); + if (editor != null) + { + String id = editor.getEditorSite().getId(); + + // open editor on new file + SystemEditableRemoteFile edit = new SystemEditableRemoteFile(_saveasFile, id); + try + { + edit.download(getShell()); + edit.addAsListener(); + edit.setLocalResourceProperties(); + + // open new editor + edit.openEditor(); + + // close old editor + CloseEditorAction closeAction = new CloseEditorAction(editor); + Display.getDefault().asyncExec(closeAction); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } + + private IFile _tempFile; + private IRemoteFile _remoteFile; + + /** + * Constructor. + * @param shell the parent shell of the action + * @param tempFile the cached local file that is in conflict with the remote file + * @param remoteFile the remote file + * @param remoteNewer indicates whether the remote file has changed since it was last downloaded + */ + public SystemUploadConflictAction(Shell shell, IFile tempFile, IRemoteFile remoteFile, boolean remoteNewer) + { + super(FileResources.RESID_CONFLICT_SAVE_TITLE, shell); + _tempFile = tempFile; + _remoteFile = remoteFile; + } + + /** + * Called when this action is invoked + */ + public void run() + { + SystemIFileProperties properties = new SystemIFileProperties(_tempFile); + + UploadConflictDialog cnfDialog = new UploadConflictDialog(SystemBasePlugin.getActiveWorkbenchShell()); + if (cnfDialog.open() == Window.OK) + { + IRemoteFileSubSystem fs = _remoteFile.getParentRemoteFileSubSystem(); + + // does user want to open local or replace local with remote? + if (cnfDialog.getOverwriteRemote()) + { + // user wants to keep the local version + // and user wants to overwrite the remote file with pending changes + try + { + fs.uploadUTF8(_tempFile, _remoteFile, null); + _remoteFile.markStale(true); + _remoteFile = fs.getRemoteFileObject(_remoteFile.getAbsolutePath()); + properties.setRemoteFileTimeStamp(_remoteFile.getLastModified()); + properties.setDirty(false); + } + catch (RemoteFileSecurityException e) + { + } + catch (RemoteFileIOException e) + { + } + catch (Exception e) + { + } + } + else if (cnfDialog.getOverwriteLocal()) + { + // user wants to replace local copy with the remote version + try + { + // download remote version + fs.downloadUTF8(_remoteFile, _tempFile, null); + + properties.setRemoteFileTimeStamp(_remoteFile.getLastModified()); + //properties.setRemoteFileTimeStamp(-1); + + properties.setDirty(false); + properties.setUsedBinaryTransfer(_remoteFile.isBinary()); + } + catch (RemoteFileSecurityException e) + { + e.printStackTrace(); + } + catch (RemoteFileIOException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + else if (cnfDialog.getSaveas()) + { + IRemoteFile remoteFile = cnfDialog.getSaveasLocation(); + if (remoteFile != null) + { + try + { + fs = remoteFile.getParentRemoteFileSubSystem(); + if (!remoteFile.exists()) + { + fs.createFile(remoteFile); + } + } + catch (SystemMessageException e) + { + SystemBasePlugin.logError("Error in performSaveAs", e); + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_UNEXPECTED); + SystemMessageDialog dialog = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), message); + dialog.open(); + return; + } + + try + { + // copy temp file to remote system + fs.uploadUTF8(_tempFile, remoteFile, null); + + // set original time stamp to 0 so that file will be overwritten next download + properties.setRemoteFileTimeStamp(0); + properties.setDirty(false); + } + catch (SystemMessageException e) + { + //e.printStackTrace(); + } + + ReopenAction reopen = new ReopenAction(_tempFile, remoteFile); + + Display.getDefault().asyncExec(reopen); + } + } + } + else + { + // cancelled dialog, so no remote synchronization + // set dirty flag! + properties.setDirty(true); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/compare/SystemCompareInput.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/compare/SystemCompareInput.java new file mode 100644 index 00000000000..1d47aaade12 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/compare/SystemCompareInput.java @@ -0,0 +1,250 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.compare; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.compare.CompareConfiguration; +import org.eclipse.compare.CompareEditorInput; +import org.eclipse.compare.ITypedElement; +import org.eclipse.compare.ZipFileStructureCreator; +import org.eclipse.compare.internal.BufferedResourceNode; +import org.eclipse.compare.internal.Utilities; +import org.eclipse.compare.structuremergeviewer.DiffNode; +import org.eclipse.compare.structuremergeviewer.DiffTreeViewer; +import org.eclipse.compare.structuremergeviewer.Differencer; +import org.eclipse.compare.structuremergeviewer.IDiffContainer; +import org.eclipse.compare.structuremergeviewer.IDiffElement; +import org.eclipse.compare.structuremergeviewer.IStructureComparator; +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.swt.widgets.Composite; + + + +public class SystemCompareInput extends CompareEditorInput +{ + + private static final boolean NORMALIZE_CASE = true; + private Object fRoot; + + class MyDiffNode extends DiffNode + { + private boolean fDirty = false; + private ITypedElement fLastId; + private String fLastName; + + public MyDiffNode(IDiffContainer parent, int description, ITypedElement ancestor, ITypedElement left, ITypedElement right) + { + super(parent, description, ancestor, left, right); + } + + public void fireChange() + { + super.fireChange(); + setDirty(true); + fDirty = true; + if (_diffViewer != null) + _diffViewer.refresh(this); + } + + void clearDirty() + { + fDirty = false; + } + + public String getName() + { + if (fLastName == null) + fLastName = super.getName(); + if (fDirty) + return '<' + fLastName + '>'; + return fLastName; + } + + public ITypedElement getId() + { + ITypedElement id = super.getId(); + if (id == null) + return fLastId; + fLastId = id; + return id; + } + } + + private List _remoteEditables; + private DiffTreeViewer _diffViewer; + private IResource _leftResource; + private IResource _rightResource; + + public SystemCompareInput(CompareConfiguration configuration) + { + super(configuration); + _remoteEditables = new ArrayList(); + } + + /** + * Creates a IStructureComparator for the given input. + * Returns null if no IStructureComparator + * can be found for the IResource. + */ + private IStructureComparator getStructure(IResource input) + { + if (input instanceof IContainer) + return new BufferedResourceNode(input); + + if (input instanceof IFile) + { + IStructureComparator rn = new BufferedResourceNode(input); + IFile file = (IFile) input; + String type = normalizeCase(file.getFileExtension()); + if ("JAR".equals(type) || "ZIP".equals(type)) //$NON-NLS-2$ //$NON-NLS-1$ + return new ZipFileStructureCreator().getStructure(rn); + return rn; + } + return null; + } + + private String normalizeCase(String s) + { + if (NORMALIZE_CASE && s != null) + return s.toUpperCase(); + return s; + } + + public IResource getLeftResource() + { + return _leftResource; + } + + public IResource getRightResource() + { + return _rightResource; + } + + public Object prepareInput(IProgressMonitor monitor) + { + ISystemEditableRemoteObject ef1 = (ISystemEditableRemoteObject)_remoteEditables.get(0); + ISystemEditableRemoteObject ef2 = (ISystemEditableRemoteObject)_remoteEditables.get(1); + + try + { + ef1.download(monitor); + ef2.download(monitor); + ef1.addAsListener(); + ef2.addAsListener(); + ef1.setLocalResourceProperties(); + ef2.setLocalResourceProperties(); + + _leftResource = ef1.getLocalResource(); + _rightResource = ef2.getLocalResource(); + + String title; + String format = Utilities.getString("ResourceCompare.twoWay.title"); //$NON-NLS-1$ + title = MessageFormat.format(format, new String[] {_leftResource.getName(), _rightResource.getName()}); + setTitle(title); + } + catch (Exception e) + { + } + + IStructureComparator c1 = getStructure(_leftResource); + IStructureComparator c2 = getStructure(_rightResource); + + Differencer d = new Differencer() + { + protected Object visit(Object parent, int description, Object ancestor, Object left, Object right) + { + return new MyDiffNode((IDiffContainer) parent, description, (ITypedElement) ancestor, (ITypedElement) left, (ITypedElement) right); + } + }; + + fRoot = d.findDifferences(false, monitor, null, null, c1, c2); + return fRoot; + } + + public Viewer createDiffViewer(Composite parent) + { + _diffViewer = new DiffTreeViewer(parent, getCompareConfiguration()) + { + protected void fillContextMenu(IMenuManager manager) + { + super.fillContextMenu(manager); + } + }; + return _diffViewer; + } + + public void addRemoteEditable(ISystemEditableRemoteObject file) + { + _remoteEditables.add(file); + } + + public void saveChanges(IProgressMonitor pm) throws CoreException + { + super.saveChanges(pm); + if (fRoot instanceof DiffNode) + { + try + { + commit(pm, (DiffNode) fRoot); + } + finally + { + if (_diffViewer != null) + _diffViewer.refresh(); + setDirty(false); + } + } + + } + + /* + * Recursively walks the diff tree and commits all changes. + */ + private void commit(IProgressMonitor pm, DiffNode node) throws CoreException + { + if (node instanceof MyDiffNode) + ((MyDiffNode) node).clearDirty(); + + ITypedElement left = node.getLeft(); + if (left instanceof BufferedResourceNode) + ((BufferedResourceNode) left).commit(pm); + + ITypedElement right = node.getRight(); + if (right instanceof BufferedResourceNode) + ((BufferedResourceNode) right).commit(pm); + + IDiffElement[] children = node.getChildren(); + if (children != null) + { + for (int i = 0; i < children.length; i++) + { + IDiffElement element = children[i]; + if (element instanceof DiffNode) + commit(pm, (DiffNode) element); + } + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemEnterOrSelectRemoteFileDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemEnterOrSelectRemoteFileDialog.java new file mode 100644 index 00000000000..8ce6063996f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemEnterOrSelectRemoteFileDialog.java @@ -0,0 +1,112 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; + +import org.eclipse.rse.files.ui.widgets.SystemEnterOrSelectRemoteFileForm; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +/** + * A dialog for either selecting or entering a file name. + * Use {@link #getRemotePath()} to get the absolute remote path of what the user selected or entered. + * Note that if the user enters a file name, then the output object will be its parent folder, since + * the file with that name may not exist. + */ +public class SystemEnterOrSelectRemoteFileDialog extends SystemSelectRemoteFileOrFolderDialog { + + private SystemEnterOrSelectRemoteFileForm form; + + /** + * Creates the dialog with the parent shell. + * @param shell the parent shell. + */ + public SystemEnterOrSelectRemoteFileDialog(Shell shell) { + super(shell, true); + setMultipleSelectionMode(false); + } + + /** + * Creates a dialog under the parent shell with the given title. + * @param shell the parent shell. + * @param title the title for the dialog. + */ + public SystemEnterOrSelectRemoteFileDialog(Shell shell, String title) { + super(shell, title, true); + setMultipleSelectionMode(false); + } + + /** + * Always returns false. + * @see org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog#getMultipleSelectionMode() + */ + public boolean getMultipleSelectionMode() { + return false; + } + + /** + * Has no effect. Multiple selection mode is not allowed. + * @see org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog#setMultipleSelectionMode(boolean) + */ + public void setMultipleSelectionMode(boolean multiple) { + super.setMultipleSelectionMode(false); + } + + /** + * Creates the select or enter file form. Sets the verbage of the form. + * @see org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog#getForm(boolean) + */ + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) { + form = new SystemEnterOrSelectRemoteFileForm(getMessageLine(), this, fileMode); + form.setMessage(SystemFileResources.RESID_ENTER_OR_SELECT_FILE_VERBAGE_LABEL); + setOutputObject(null); + return form; + } + + /** + * Returns the remote path. + * @return the remote path. + */ + public String getRemotePath() { + IRemoteFile file = (IRemoteFile)getOutputObject(); + + String absPath = file.getAbsolutePath(); + + // if the output is a file, then return the absolute path. + if (file.isFile()) { + return absPath; + } + // if the output is a folder, then file name is available in the text field + // of the form, so append the file name to the folder path + else { + String fileName = form.getFileName(); + String sep = file.getSeparator(); + + // add separator if necessary + if (!absPath.endsWith(sep)) { + absPath += sep; + } + + // add file name if necessary + absPath += fileName; + + return absPath; + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemPromptForHomeFolderDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemPromptForHomeFolderDialog.java new file mode 100644 index 00000000000..ffa9c227964 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemPromptForHomeFolderDialog.java @@ -0,0 +1,131 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.widgets.SystemRemoteFolderCombo; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.dialogs.SystemPromptDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +/** + * Dialog for prompting the user for his home folder. This is called once when + * the user first expands his default "/home/username" filter string. + *

    NOT USED YET

    + */ +public class SystemPromptForHomeFolderDialog + extends SystemPromptDialog + implements SelectionListener +{ + private IHost connection; + private ISubSystem subsystem; + private SystemRemoteFolderCombo folderCombo = null; + + /** + * Constructor + */ + public SystemPromptForHomeFolderDialog(Shell shell, ISystemFilter filter) + { + super(shell, SystemFileResources.RESID_HOMEPROMPT_TITLE); + setBlockOnOpen(true); // always modal + subsystem = (ISubSystem)filter.getProvider(); + connection = subsystem.getHost(); + //pack(); + } + + /** + * Return initial control to be given focus + */ + protected Control getInitialFocusControl() + { + return folderCombo.getFolderCombo(); + } + + /** + * Create and populate dialog area + * @see SystemPromptDialog#createInner(Composite) + */ + protected Control createInner(Composite parent) + { + // Inner composite + int gridColumns = 1; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, gridColumns); + + // verbage + boolean wantBorder = false; + int span = 1; + int widthHint = 200; + SystemWidgetHelpers.createVerbage(composite_prompts, SystemFileResources.RESID_HOMEPROMPT_TITLE, span, wantBorder, widthHint); + + // connection\folder prompt + boolean readOnly = false; + folderCombo = new SystemRemoteFolderCombo(composite_prompts, SWT.BORDER, null, readOnly); + folderCombo.setSystemConnection(connection); + folderCombo.setText("/home/"+SystemPlugin.getLocalMachineName()); + + // listen for selections + //folderCombo.addSelectionListener(this); + + return composite_prompts; + } + + /** + * From SelectionListener interface + */ + public void widgetDefaultSelected(SelectionEvent event) + { + } + + /** + * From SelectionListener interface. + * Called when user selects new item in dropdown + */ + public void widgetSelected(SelectionEvent event) + { + Object src = event.getSource(); + Combo comboWidget = folderCombo.getCombo(); + if (src == comboWidget) + { + //clearErrorMessage(); + //clearMessage(); + //String selectedFolder = folderCombo.getText(); + } + } + + + /** + * Called when user presses OK button. + * Return true to close dialog. + * Return false to not close dialog. + */ + protected boolean processOK() + { + boolean ok = true; + return ok; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteArchiveDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteArchiveDialog.java new file mode 100644 index 00000000000..4fce6f3727b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteArchiveDialog.java @@ -0,0 +1,69 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; + +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.view.SystemActionViewerFilter; +import org.eclipse.swt.widgets.Shell; + + +public class SystemRemoteArchiveDialog extends SystemRemoteFileDialog +{ + private SystemActionViewerFilter _filter; + + public SystemRemoteArchiveDialog(Shell shell, String title, IHost defaultConnection) + { + super(shell, title, defaultConnection); + } + + public SystemRemoteArchiveDialog(Shell shell, String title) + { + super(shell, title); + + } + + public SystemRemoteArchiveDialog(Shell shell) + { + super(shell, SystemFileResources.RESID_SELECTFILE_TITLE); + + } + + public SystemActionViewerFilter getViewerFilter() + { + if (_filter== null) + { + _filter = new SystemActionViewerFilter(); + Class[] types = {IRemoteFile.class}; + _filter.addFilterCriterion(types, "isDirectory", "true"); + _filter.addFilterCriterion(types, "isArchive", "true"); + } + return _filter; + } + + + public String getVerbage() + { + return SystemFileResources.RESID_SELECTFILE_VERBAGE; + } + + public String getTreeTip() + { + return SystemFileResources.RESID_SELECTFILE_SELECT_TOOLTIP; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileDialog.java new file mode 100644 index 00000000000..65a4a9b3560 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileDialog.java @@ -0,0 +1,58 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; + +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.ui.dialogs.SystemRemoteResourceDialog; +import org.eclipse.rse.ui.view.SystemActionViewerFilter; +import org.eclipse.swt.widgets.Shell; + + +public class SystemRemoteFileDialog extends SystemRemoteResourceDialog +{ + public SystemRemoteFileDialog(Shell shell, String title, IHost defaultConnection) + { + super(shell, title, new SystemRemoteFileSelectionInputProvider(defaultConnection)); + } + + public SystemRemoteFileDialog(Shell shell, String title) + { + super(shell, title, new SystemRemoteFileSelectionInputProvider()); + } + + public SystemRemoteFileDialog(Shell shell) + { + super(shell, SystemFileResources.RESID_SELECTFILE_TITLE, new SystemRemoteFileSelectionInputProvider()); + } + + + public String getVerbage() + { + return SystemFileResources.RESID_SELECTFILE_VERBAGE; + } + + public String getTreeTip() + { + return SystemFileResources.RESID_SELECTFILE_SELECT_TOOLTIP; + } + + public SystemActionViewerFilter getViewerFilter() + { + return null; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileSelectionInputProvider.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileSelectionInputProvider.java new file mode 100644 index 00000000000..9b5bd069a02 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFileSelectionInputProvider.java @@ -0,0 +1,44 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; + +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.ui.view.SystemResourceSelectionInputProvider; + + +public class SystemRemoteFileSelectionInputProvider extends + SystemResourceSelectionInputProvider +{ + + public SystemRemoteFileSelectionInputProvider(IHost connection) + { + super(connection); + } + + public SystemRemoteFileSelectionInputProvider() + { + super(); + } + + protected ISubSystem getSubSystem(IHost selectedConnection) + { + return RemoteFileUtility.getFileSubSystem(selectedConnection); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFolderDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFolderDialog.java new file mode 100644 index 00000000000..ac6e9973ed6 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemRemoteFolderDialog.java @@ -0,0 +1,68 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; + +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.view.SystemActionViewerFilter; +import org.eclipse.swt.widgets.Shell; + + +public class SystemRemoteFolderDialog extends SystemRemoteFileDialog +{ + private SystemActionViewerFilter _filter; + + public SystemRemoteFolderDialog(Shell shell, String title, IHost defaultConnection) + { + super(shell, title, defaultConnection); + } + + public SystemRemoteFolderDialog(Shell shell, String title) + { + super(shell, title); + + } + + public SystemRemoteFolderDialog(Shell shell) + { + super(shell, SystemFileResources.RESID_SELECTDIRECTORY_TITLE); + + } + + public SystemActionViewerFilter getViewerFilter() + { + if (_filter== null) + { + _filter = new SystemActionViewerFilter(); + Class[] types = {IRemoteFile.class}; + _filter.addFilterCriterion(types, "isDirectory", "true"); + } + return _filter; + } + + + public String getVerbage() + { + return SystemFileResources.RESID_SELECTDIRECTORY_VERBAGE; + } + + public String getTreeTip() + { + return SystemFileResources.RESID_SELECTDIRECTORY_SELECT_TOOLTIP; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemSelectRemoteFileOrFolderDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemSelectRemoteFileOrFolderDialog.java new file mode 100644 index 00000000000..a515464df5e --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/dialogs/SystemSelectRemoteFileOrFolderDialog.java @@ -0,0 +1,561 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.dialogs; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.rse.files.ui.ISystemAddFileListener; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.dialogs.SystemPromptDialog; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.SystemViewForm; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + +/** + * Dialog for allowing users to select a remote file or folder. This is a thin dialog wrapper on top of + * the SystemSelectRemoteFileOrFolderForm widget, which you could optionally imbed directly into your own + * dialog or wizard page. + *

    + * Call these methods to configure the functionality of the dialog + *

    + *

    + * Call these methods to configure the text on the dialog + *

    + *

    + * After running, call these methods to get the output: + *

    + * + * @see org.eclipse.rse.files.ui.actions.SystemSelectRemoteFileAction + * @see org.eclipse.rse.files.ui.actions.SystemSelectRemoteFolderAction + */ +public class SystemSelectRemoteFileOrFolderDialog + extends SystemPromptDialog + //implements ISystemFileConstants +{ + public static final boolean FILE_MODE = true; + public static final boolean FOLDER_MODE = false; + protected SystemSelectRemoteFileOrFolderForm form; + private boolean multipleSelectionMode; + protected IHost outputConnection; + private ISystemAddFileListener addButtonCallback = null; + + /** + * Constructor + * + * @param shell The shell to hang the dialog off of + * @param fileMode True if selecting files, false if selecting folders + * + */ + public SystemSelectRemoteFileOrFolderDialog(Shell shell, boolean fileMode) + { + this(shell, + fileMode ? SystemFileResources.RESID_SELECTFILE_TITLE : SystemFileResources.RESID_SELECTDIRECTORY_TITLE, + fileMode); + } + + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param fileMode True if selecting files, false if selecting folders + */ + public SystemSelectRemoteFileOrFolderDialog(Shell shell, String title, boolean fileMode) + { + super(shell, title); + super.setBlockOnOpen(true); // always modal + form = getForm(fileMode); + //pack(); + } + + // ------------------ + // PUBLIC METHODS... + // ------------------ + /** + * indicate whether selections from different parents are allowed + */ + public void setAllowForMultipleParents(boolean flag) + { + form.setAllowForMultipleParents(flag); + } + + /** + * Set the system connection to restrict the user to selecting files or folders from + */ + public void setSystemConnection(IHost conn) + { + form.setSystemConnection(conn); + } + /** + * Set the connection to default the selection to + */ + public void setDefaultConnection(IHost conn) + { + form.setDefaultConnection(conn); + } + + /** + * Restrict to certain system types + * @param systemTypes the system types to restrict what connections are shown and what types of connections + * the user can create + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + form.setSystemTypes(systemTypes); + } + /** + * Set to true if a "New Connection..." special connection is to be shown for creating new connections + */ + public void setShowNewConnectionPrompt(boolean show) + { + form.setShowNewConnectionPrompt(show); + } + /** + * Set the message shown at the top of the form + */ + public void setMessage(String message) + { + form.setMessage(message); + } + /** + * Set the tooltip text for the remote systems tree from which an item is selected. + */ + public void setSelectionTreeToolTipText(String tip) + { + form.setSelectionTreeToolTipText(tip); + } + /** + * Specify the zero-based auto-expand level for the tree. The default is zero, meaning + * only show the connections. + */ + public void setAutoExpandDepth(int depth) + { + form.setAutoExpandDepth(depth); + } + + /** + * Set the root folder from which to start listing folders or files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + form.setRootFolder(connection, folderAbsolutePath); + } + /** + * Set the root folder from which to start listing folders. + * This version identifies the folder via an IRemoteFile object. + * There is another overload that identifies the folder via a connection and folder path. + *

    + * This call effectively transforms the select dialog by: + *

    + * + * @param rootFolder The IRemoteFile object representing the remote folder to start the list from + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IRemoteFile rootFolder) + { + form.setRootFolder(rootFolder); + } + /** + * Set a file or folder to preselect. This will: + * + * If there is no parent, then we were given a root. In which case we will + * + */ + public void setPreSelection(IRemoteFile selection) + { + form.setPreSelection(selection); + } + + /** + * For files mode, restrict the files list by an array of file types + *

    + * This must be called BEFORE setRootFolder! + */ + public void setFileTypes(String[] fileTypes) + { + form.setFileTypes(fileTypes); + } + /** + * For files mode, restrict the files list by a comman-delimited array of file types. + * The last type must also end in a comma. Eg "java, class," or "class,". + *

    + * This must be called BEFORE setRootFolder! + */ + public void setFileTypes(String fileTypes) + { + form.setFileTypes(fileTypes); + } + /** + * Specify whether setRootFolder should prevent the user from being able to see or select + * any other folder. This causes two effects: + *

      + *
    1. The special filter for root/drives is not shown + *
    2. No subfolders are listed in the target folder, if we are listing files. Of course, they are shown + * if we are listing folders, else it would be an empty list! + *
    + */ + public void setRestrictFolders(boolean restrict) + { + form.setRestrictFolders(restrict); + } + /** + * Enable Add mode. This means the OK button is replaced with an Add button, and + * the Cancel with a Close button. When Add is pressed, the caller is called back. + * The dialog is not exited until Close is pressed. + *

    + * When a library is selected, the caller is called back to decide to enable the Add + * button or not. + */ + public void enableAddMode(ISystemAddFileListener caller) + { + this.addButtonCallback = caller; + form.enableAddMode(caller); + setShowAddButton(true); + enableAddButton(false); + setShowOkButton(false); + setCancelButtonLabel(SystemResources.BUTTON_CLOSE); + } + /** + * Overloaded method that allows setting the label and tooltip text of the Add button. + * If you pass null for the label, the default is used ("Add"). + */ + public void enableAddMode(ISystemAddFileListener caller, String addLabel, String addToolTipText) + { + enableAddMode(caller); + if (addLabel != null) + setAddButtonLabel(addLabel); + if (addToolTipText != null) + setAddButtonToolTipText(addToolTipText); + } + + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * This overload always shows the property sheet + *

    + * Default is false + */ + public void setShowPropertySheet(boolean show) + { + form.setShowPropertySheet(show); + } + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * This overload shows a Details>>> button so the user can decide if they want to see the + * property sheet. + *

    + * @param show True if show the property sheet within the dialog + * @param initialState True if the property is to be initially displayed, false if it is not + * to be displayed until the user presses the Details button. + */ + public void setShowPropertySheet(boolean show, boolean initialState) + { + if (show) + { + form.setShowPropertySheet(initialState); + setShowDetailsButton(true, !initialState); + } + } + + /** + * Set multiple selection mode. Default is single selection mode + *

    + * If you turn on multiple selection mode, you must use the getSelectedObjects() + * method to retrieve the list of selected objects. + *

    + * Further, if you turn this on, it has the side effect of allowing the user + * to select any remote object. The assumption being if you are prompting for + * files, you also want to allow the user to select a folder, with the meaning + * being that all files within the folder are implicitly selected. + * + * @see #getSelectedObjects() + */ + public void setMultipleSelectionMode(boolean multiple) + { + this.multipleSelectionMode = multiple; + form.setMultipleSelectionMode(multiple); + } + /** + * Specify a validator to use when the user selects a remote file or folder. + * This allows you to decide if OK should be enabled or not for that remote file or folder. + */ + public void setSelectionValidator(IValidatorRemoteSelection selectionValidator) + { + form.setSelectionValidator(selectionValidator); + } + + // ------------------ + // OUTPUT METHODS... + // ------------------ + + /** + * Return selected file or folder + */ + public Object getSelectedObject() + { + if (getOutputObject() instanceof Object[]) + return ((Object[])getOutputObject())[0]; + else + return getOutputObject(); + } + /** + * Return all selected objects. This method will return an array of one + * unless you have called setMultipleSelectionMode(true)! + * @see #setMultipleSelectionMode(boolean) + */ + public Object[] getSelectedObjects() + { + if (getOutputObject() instanceof Object[]) + return (Object[])getOutputObject(); + else if (getOutputObject() instanceof Object) + return new Object[] {getOutputObject()}; + else + return null; + } + + /** + * Return selected connection + */ + public IHost getSelectedConnection() + { + return outputConnection; + } + + /** + * Return the multiple selection mode as set by setMultipleSelectionMode(boolean) + */ + public boolean getMultipleSelectionMode() + { + return multipleSelectionMode; + } + /** + * Return the embedded System Tree object. + * Will be null until createContents is called. + */ + public SystemViewForm getSystemViewForm() + { + return form.getSystemViewForm(); + } + + // ------------------ + // PRIVATE METHODS... + // ------------------ + /** + * Private method. + * @see SystemPromptDialog#getInitialFocusControl() + */ + protected Control getInitialFocusControl() + { + return form.getInitialFocusControl(); + } + + /** + * Private method. + * @see SystemPromptDialog#createInner(Composite) + */ + protected Control createInner(Composite parent) + { + return form.createContents(getShell(), parent); + } + + /** + * Private method. + * Get the contents. + */ + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + //System.out.println("INSIDE GETFORM"); + //if (form == null) + //{ + form = new SystemSelectRemoteFileOrFolderForm(getMessageLine(), this, fileMode); + // reset output variables just to be safe + setOutputObject(null); + outputConnection = null; + //} + return form; + } + + /** + * Create message line. Intercept so we can set msg line of form. + */ + protected ISystemMessageLine createMessageLine(Composite c) + { + ISystemMessageLine msgLine = super.createMessageLine(c); + if (form != null) + form.setMessageLine(msgLine); + return msgLine; + } + + + /** + * Private method. + *

    + * Called when user presses OK button. + * Return true to close dialog. + * Return false to not close dialog. + */ + protected boolean processOK() + { + boolean closeDialog = form.verify(); + if (closeDialog) + { + outputConnection = form.getSelectedConnection(); + if (multipleSelectionMode) + setOutputObject(form.getSelectedObjects()); + else + setOutputObject(form.getSelectedObject()); + } + else + setOutputObject(null); + return closeDialog; + } + + /** + * Private method. + *

    + * Called when user presses Add button. + */ + protected boolean processAdd() + { + Object errMsg = addButtonCallback.addButtonPressed(form.getSelectedConnection(), (IRemoteFile[])form.getSelectedObjects()); + if (errMsg != null) + { + if (errMsg instanceof String) + setErrorMessage((String)errMsg); + else + setErrorMessage((SystemMessage)errMsg); + } + else + clearErrorMessage(); + enableAddButton(false); // presumably you won't add the same thing twice! + return false; + } + /** + * Private method. + *

    + * Called when user presses DETAILS button. + *

    + * Note the text is automatically toggled for us! We need only + * do whatever the functionality is that we desire + * + * @param hideMode the current state of the details toggle, prior to this request. If we return true from + * this method, this state and the button text will be toggled. + * + * @return true if the details state toggle was successful, false if it failed. + */ + protected boolean processDetails(boolean hideMode) + { + form.toggleShowPropertySheet(getShell(), getContents()); + return true; + } + + + public void setPageComplete(boolean complete) + { + if (addButtonCallback != null) + enableAddButton(complete); + else + super.setPageComplete(complete); + } + + /** + * We have to override close to ensure that we reset the form to null + */ + public boolean close() + { + if (super.close()) + { + if (form != null) + { + form.dispose(); + } + form = null; + return true; + } + return false; + } + + /** + * Add viewer filter. + * @param filter a viewer filter. + */ + public void addViewerFilter(ViewerFilter filter) { + + if (form != null) { + form.addViewerFilter(filter); + } + } + + /** + * Sets whether to allow folder selection. The default selection validator will use this to + * determine whether the OK button will be enabled when a folder is selected. The default + * is true. This call only makes sense if the dialog is in file selection mode. + * @param allow true to allow folder selection, false otherwise. + */ + public void setAllowFolderSelection(boolean allow) { + + if (form != null) { + form.setAllowFolderSelection(allow); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/FileServicesPropertyPage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/FileServicesPropertyPage.java new file mode 100644 index 00000000000..a4515e7de6e --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/FileServicesPropertyPage.java @@ -0,0 +1,98 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.propertypages; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.servicesubsystem.IServiceSubSystemConfiguration; +import org.eclipse.rse.core.subsystems.ISubSystemConfiguration; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.subsystems.files.core.servicesubsystem.FileServiceSubSystem; +import org.eclipse.rse.subsystems.files.core.servicesubsystem.IFileServiceSubSystemConfiguration; +import org.eclipse.rse.ui.propertypages.ServicesPropertyPage; +import org.eclipse.rse.ui.widgets.services.FactoryServiceElement; +import org.eclipse.rse.ui.widgets.services.ServiceElement; + + +public class FileServicesPropertyPage extends ServicesPropertyPage +{ + + private IFileServiceSubSystemConfiguration _currentFactory; + + protected FileServiceSubSystem getFileServiceSubSystem() + { + return (FileServiceSubSystem)getElement(); + } + + protected ServiceElement[] getServiceElements() + { + FileServiceSubSystem subSystem = getFileServiceSubSystem(); + + IHost host = subSystem.getHost(); + _currentFactory = (IFileServiceSubSystemConfiguration)subSystem.getParentRemoteFileSubSystemFactory(); + IFileServiceSubSystemConfiguration[] factories = getFileServiceSubSystemFactories(host.getSystemType()); + + + // create elements for each + ServiceElement[] elements = new ServiceElement[factories.length]; + for (int i = 0; i < factories.length; i++) + { + IFileServiceSubSystemConfiguration factory = factories[i]; + elements[i] = new FactoryServiceElement(host, factory); + if (factory == _currentFactory) + { + elements[i].setSelected(true); + } + } + + return elements; + } + + protected IFileServiceSubSystemConfiguration[] getFileServiceSubSystemFactories(String systemType) + { + List results = new ArrayList(); + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + ISubSystemConfiguration[] factories = sr.getSubSystemConfigurationsBySystemType(systemType); + + for (int i = 0; i < factories.length; i++) + { + ISubSystemConfiguration factory = factories[i]; + if (factory instanceof IFileServiceSubSystemConfiguration) + { + results.add(factory); + } + } + + return (IFileServiceSubSystemConfiguration[])results.toArray(new IFileServiceSubSystemConfiguration[results.size()]); + } + + + protected IServiceSubSystemConfiguration getCurrentServiceSubSystemFactory() + { + return _currentFactory; + } + + public void setSubSystemFactory(ISubSystemConfiguration factory) + { + _currentFactory = (IFileServiceSubSystemConfiguration)factory; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemAbstractRemoteFilePropertyPageExtensionAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemAbstractRemoteFilePropertyPageExtensionAction.java new file mode 100644 index 00000000000..fda09965aee --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemAbstractRemoteFilePropertyPageExtensionAction.java @@ -0,0 +1,119 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.propertypages; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.propertypages.SystemAbstractPropertyPageExtensionAction; +import org.eclipse.rse.ui.propertypages.SystemBasePropertyPage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbenchPropertyPage; + + + +/** + * This is a base class to simplify the creation of property pages supplied via the + * com.ibm.etools.systems.core.propertyPages extension point, targeting remote files + * and/or remote folders. + *

    + * The only method you must implement is {@link #createContentArea(Composite)}. + *

    + * The benefits of this class are:

    + * + */ +public abstract class SystemAbstractRemoteFilePropertyPageExtensionAction + extends SystemAbstractPropertyPageExtensionAction implements IWorkbenchPropertyPage +{ + + /** + * Constructor + */ + public SystemAbstractRemoteFilePropertyPageExtensionAction() + { + super(); + } + + // ---------------------------------- + // OVERRIDABLE METHODS FROM PARENT... + // ---------------------------------- + /** + * Abstract. You must override.
    + * This is where child classes create their content area versus createContent, + * in order to have the message line configured for them and mnemonics assigned. + */ + protected abstract Control createContentArea(Composite parent); + + /** + * You may override if your page has input fields. By default returns true.
    + * Validate all the widgets on the page. Based on this, the Eclipse framework will know whether + * to veto any user attempt to select another property page from the list on the left in the + * Properties dialog. + *

    + * Subclasses should override to do full error checking on all the widgets on the page. Recommendation:
    + *

    + * + * @return true if there are no errors, false if any errors were found. + */ + protected boolean verifyPageContents() + { + return true; + } + + // ------------------------------------------------------------------ + // CONVENIENCE METHODS WE ADD SPECIFICALLY FOR REMOTE FILE ACTIONS... + // ------------------------------------------------------------------ + /** + * Retrieve the input selected object, as an IRemoteFile, for convenience. + */ + public IRemoteFile getRemoteFile() + { + return (IRemoteFile)super.getRemoteObject(); + } + + /** + * Get the remote file subsystem from which the selected objects were resolved. + * This has many useful methods in it, including support to transfer files to and + * from the local and remote systems. + */ + public IRemoteFileSubSystem getRemoteFileSubSystem() + { + return (IRemoteFileSubSystem)getSubSystem(); + } + + /** + * Returns the remote file subsystem factory which owns the subsystem from which the + * selected remote objects were resolved. This has some useful methods in it, + * including isUnixStyle() indicating if this remote file system is unix or windows. + */ + public IRemoteFileSubSystemConfiguration getRemoteFileSubSystemFactory() + { + return (IRemoteFileSubSystemConfiguration)getSubSystemFactory(); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemCachePreferencePage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemCachePreferencePage.java new file mode 100644 index 00000000000..3d3933a51c9 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemCachePreferencePage.java @@ -0,0 +1,649 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.propertypages; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.preference.FieldEditorPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.files.ui.resources.SystemRemoteEditManager; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.ui.GenericMessages; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.Mnemonics; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.SystemTableViewProvider; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.dialogs.ListSelectionDialog; +import org.eclipse.ui.model.AdaptableList; +import org.eclipse.ui.model.WorkbenchContentProvider; + + +/** + * Preference page for generic Remote System cache preferences + */ +public class SystemCachePreferencePage extends PreferencePage implements IWorkbenchPreferencePage, Listener +{ + + private Button _clearButton; + private Button _maxCacheCheckbox; + private Text _maxCacheSize; + + /** + * Constructor + */ + public SystemCachePreferencePage() + { + super(); + setPreferenceStore(SystemPlugin.getDefault().getPreferenceStore()); + setDescription(FileResources.RESID_PREF_CACHE_DESCRIPTION); + } + + /** + * Configure the composite. We intercept to set the help. + */ + public void createControl(Composite parent) + { + super.createControl(parent); + } + + /** + * + */ + protected Control createContents(Composite gparent) + { + Composite parent = SystemWidgetHelpers.createComposite(gparent, 1); + + Composite maxComp = SystemWidgetHelpers.createComposite(parent, 2); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + maxComp.setLayout(layout); + maxComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); + + _maxCacheCheckbox = + SystemWidgetHelpers.createCheckBox( + maxComp, + FileResources.RESID_PREF_CACHE_MAX_CACHE_SIZE_LABEL, + this); + _maxCacheCheckbox.setToolTipText( + FileResources.RESID_PREF_CACHE_MAX_CACHE_SIZE_TOOLTIP); + + _maxCacheSize = SystemWidgetHelpers.createTextField(maxComp, this); + GridData gd = new GridData(); + gd.widthHint = 75; + _maxCacheSize.setLayoutData(gd); + + _maxCacheSize.setTextLimit(5); + _maxCacheSize.addVerifyListener(new VerifyListener() + { + public void verifyText(VerifyEvent e) + { + e.doit = true; + for (int loop = 0; loop < e.text.length(); loop++) + { + if (!Character.isDigit(e.text.charAt(loop))) + e.doit = false; + } + } + }); + + Composite clearComp = SystemWidgetHelpers.createComposite(parent, 2); + layout = new GridLayout(); + layout.numColumns = 2; + clearComp.setLayout(layout); + clearComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); + + SystemWidgetHelpers.createLabel( + clearComp, + FileResources.RESID_PREF_CACHE_CLEAR_LABEL); + _clearButton = + SystemWidgetHelpers.createPushButton( + clearComp, + FileResources.RESID_PREF_CACHE_CLEAR, + this); + _clearButton.setToolTipText(FileResources.RESID_PREF_CACHE_CLEAR_TOOLTIP); + gd = new GridData(); + gd.widthHint = 75; + _clearButton.setLayoutData(gd); + + Composite warningComp = SystemWidgetHelpers.createComposite(clearComp, 2); + gd = new GridData(); + gd.horizontalSpan = 2; + warningComp.setLayoutData(gd); + + Display display = getControl().getDisplay(); + Label warningLabel = + SystemWidgetHelpers.createLabel( + warningComp, + FileResources.RESID_PREF_CACHE_CLEAR_WARNING_LABEL); + FontData oldData = warningLabel.getFont().getFontData()[0]; + FontData data = new FontData(oldData.getName(), oldData.getHeight(), SWT.BOLD); + Font fFont = new Font(display, data); + + warningLabel.setFont(fFont); + SystemWidgetHelpers.createLabel( + warningComp, + FileResources.RESID_PREF_CACHE_CLEAR_WARNING_DESCRIPTION); + + (new Mnemonics()).setOnPreferencePage(true).setMnemonics(parent); + SystemWidgetHelpers.setCompositeHelp(parent, SystemPlugin.HELPPREFIX + "fchp0000"); + + initControls(); + return parent; + } + + private void initControls() + { + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + boolean enableMaxSize = store.getBoolean(ISystemPreferencesConstants.LIMIT_CACHE); + _maxCacheSize.setEnabled(enableMaxSize); + + String maxCacheSizeStr = store.getString(ISystemPreferencesConstants.MAX_CACHE_SIZE); + + if (maxCacheSizeStr == null || maxCacheSizeStr.equals("")) { + maxCacheSizeStr = ISystemPreferencesConstants.DEFAULT_MAX_CACHE_SIZE; + } + + _maxCacheSize.setText(maxCacheSizeStr); + _maxCacheCheckbox.setSelection(enableMaxSize); + } + + /** + * Inherited method. + */ + public void init(IWorkbench workbench) + { + + } + + /** + * @see FieldEditorPreferencePage#performDefaults() + */ + protected void performDefaults() + { + super.performDefaults(); + + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + + boolean enableMaxSize = store.getDefaultBoolean(ISystemPreferencesConstants.LIMIT_CACHE); + _maxCacheCheckbox.setSelection(enableMaxSize); + + _maxCacheSize.setEnabled(enableMaxSize); + _maxCacheSize.setText(store.getDefaultString(ISystemPreferencesConstants.MAX_CACHE_SIZE)); + } + + /** + * Set default preferences for the communications preference page. + * + * @param store PreferenceStore used for this preference page. + */ + public static void initDefaults(IPreferenceStore store) + { + store.setDefault(ISystemPreferencesConstants.LIMIT_CACHE, ISystemPreferencesConstants.DEFAULT_LIMIT_CACHE); + store.setDefault(ISystemPreferencesConstants.MAX_CACHE_SIZE, ISystemPreferencesConstants.DEFAULT_MAX_CACHE_SIZE); + } + + /** + * @see FieldEditorPreferencePage#performOk() + */ + public boolean performOk() + { + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + String size = _maxCacheSize.getText(); + + if (size == null || size.trim().equals("")) { + size = ISystemPreferencesConstants.DEFAULT_MAX_CACHE_SIZE; + } + + store.setValue(ISystemPreferencesConstants.MAX_CACHE_SIZE, size); + store.setValue(ISystemPreferencesConstants.LIMIT_CACHE, _maxCacheCheckbox.getSelection()); + + return super.performOk(); + } + + public class ClearTempFilesRunnable implements IRunnableWithProgress + { + public void run(IProgressMonitor monitor) + { + SystemRemoteEditManager mgr = SystemRemoteEditManager.getDefault(); + // if no temp file project, nothing to do + if (!mgr.doesRemoteEditProjectExist()) + { + return; + } + + IProject tempFiles = mgr.getRemoteEditProject(); + if (tempFiles != null) + { + try + { + IWorkspace workspace = SystemBasePlugin.getWorkspace(); + IResource[] members = tempFiles.members(); + if (members != null) + { + for (int i = 0; i < members.length; i++) + { + IResource member = members[i]; + if ((member instanceof IFile) && + member.getName().equals(".project")) + { + } + else + { + // DKM - passing true now so that out-of-synch temp files are deleted too (i.e. generated .evt files) + // this solves the worse part of 58951 + member.delete(true, monitor); + } + } + } + + } + catch (Exception e) + { + } + finally + { + mgr.getRemoteEditProject(); + /* + try + { + + + // recreate .project + IProjectDescription description = tempFiles.getDescription(); + String[] natures = description.getNatureIds(); + String[] newNatures = new String[natures.length + 1]; + + // copy all previous natures + for (int i = 0; i < natures.length; i++) + { + newNatures[i] = natures[i]; + } + + newNatures[newNatures.length - 1] = SystemRemoteEditManager.REMOTE_EDIT_PROJECT_NATURE_ID; + description.setNatureIds(newNatures); + tempFiles.setDescription(description, null); + + mgr.addCSupport(tempFiles); + mgr.addJavaSupport(tempFiles); + + + } + catch (CoreException e) + { + } + */ + } + + } + } + } + + protected IRunnableContext getRunnableContext(Shell shell) + { + IRunnableContext irc = SystemPlugin.getTheSystemRegistry().getRunnableContext(); + if (irc != null) + { + return irc; + } + else + { + // for other cases, use statusbar + IWorkbenchWindow win = SystemBasePlugin.getActiveWorkbenchWindow(); + if (win != null) + { + Shell winShell = SystemBasePlugin.getActiveWorkbenchShell(); + if (winShell != null && winShell.isVisible() && !winShell.isDisposed()) + { + shell = winShell; + return win; + } + else + { + win = null; + } + } + + return new ProgressMonitorDialog(shell); + } + } + public void handleEvent(Event e) + { + if (e.widget == _clearButton) + { + + if (checkDirtyEditors()) + { + IRunnableContext runnableContext = getRunnableContext(SystemBasePlugin.getActiveWorkbenchShell()); + try + { + // currently we don't run this in a thread because + // in some cases dialogs are launched in the operation + // (widgets can only be legally used on the main thread) + runnableContext.run(false, true, new ClearTempFilesRunnable()); + // inthread, cancellable, IRunnableWithProgress + } + catch (java.lang.reflect.InvocationTargetException exc) + { + } + catch (java.lang.InterruptedException ex) + { + } + } + + } + else if (e.widget == _maxCacheCheckbox) + { + _maxCacheSize.setEnabled(_maxCacheCheckbox.getSelection()); + } + } + + protected boolean getDirtyReplicas(IContainer parent, List dirtyReplicas) + { + try + { + IResource[] children = parent.members(); + for (int i = 0; i < children.length; i++) + { + IResource child = children[i]; + if (child instanceof IFile) + { + SystemIFileProperties properties = new SystemIFileProperties(child); + if (properties.getDirty()) + { + if (properties.getRemoteFileObject() != null) + { + ISystemEditableRemoteObject editable = + (ISystemEditableRemoteObject) properties.getRemoteFileObject(); + dirtyReplicas.add(editable); + } + else if (properties.getDownloadFileTimeStamp() != child.getLocalTimeStamp()) + { + String ssString = properties.getRemoteFileSubSystem(); + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + ISubSystem subsystem = registry.getSubSystem(ssString); + if (subsystem != null) + { + String path = properties.getRemoteFilePath(); + try + { + IAdaptable remoteFile = (IAdaptable) subsystem.getObjectWithAbsoluteName(path); + if (remoteFile != null) + { + ISystemRemoteElementAdapter adapter = + (ISystemRemoteElementAdapter) remoteFile.getAdapter( + ISystemRemoteElementAdapter.class); + ISystemEditableRemoteObject editable = + adapter.getEditableRemoteObject(remoteFile); + editable.openEditor(); + // need this to get a reference back to the object + properties.setRemoteFileObject(editable); + dirtyReplicas.add(editable); + } + else + { + return false; + } + } + catch (Exception e) + { + return false; + } + } + } + } + } + else if (child instanceof IContainer) + { + if (!getDirtyReplicas((IContainer) child, dirtyReplicas)) + { + return false; + } + } + } + } + catch (Exception e) + { + return false; + } + return true; + } + + protected boolean getDirtyReplicas(List results) + { + SystemRemoteEditManager mgr = SystemRemoteEditManager.getDefault(); + IProject tempFilesProject = mgr.getRemoteEditProject(); + if (!getDirtyReplicas(tempFilesProject, results)) + { + return false; + } + if (!getDirtyEditors(results)) + { + return false; + } + return true; + } + + protected boolean getDirtyEditors(List results) + { + SystemRemoteEditManager editMgr = SystemRemoteEditManager.getDefault(); + + // if there's no temp file project, there's no dirty editors + if (!editMgr.doesRemoteEditProjectExist()) + return false; + + IProject tempFilesProject = editMgr.getRemoteEditProject(); + IWorkbenchWindow activeWindow = SystemBasePlugin.getActiveWorkbenchWindow(); + IWorkbenchPage activePage = activeWindow.getActivePage(); + + IEditorReference[] activeReferences = activePage.getEditorReferences(); + + IEditorPart part; + + for (int k = 0; k < activeReferences.length; k++) + { + part = activeReferences[k].getEditor(false); + + if (part != null) + { + IEditorInput editorInput = part.getEditorInput(); + + if (editorInput instanceof IFileEditorInput) + { + IFile file = ((IFileEditorInput) editorInput).getFile(); + if (file.getProject() == tempFilesProject) + { + if (part.isDirty()) + { + SystemIFileProperties properties = new SystemIFileProperties(file); + if (properties.getDirty()) + { + // then this is already added via getDirtyReplicas() + } + else + { + + if (properties.getRemoteFileObject() != null) + { + ISystemEditableRemoteObject editable = + (ISystemEditableRemoteObject) properties.getRemoteFileObject(); + results.add(editable); + } + else + { + String ssString = properties.getRemoteFileSubSystem(); + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + ISubSystem subsystem = registry.getSubSystem(ssString); + if (subsystem != null) + { + String path = properties.getRemoteFilePath(); + try + { + + IAdaptable remoteFile = + (IAdaptable) subsystem.getObjectWithAbsoluteName(path); + if (remoteFile != null) + { + ISystemRemoteElementAdapter adapter = + (ISystemRemoteElementAdapter) remoteFile.getAdapter( + ISystemRemoteElementAdapter.class); + ISystemEditableRemoteObject editable = + adapter.getEditableRemoteObject(remoteFile); + editable.openEditor(); + // need this to get a reference back to the object + properties.setRemoteFileObject(editable); + results.add(editable); + } + } + catch (Exception e) + { + } + } + } + } + } + } + } + } + } + return true; + } + + protected ISystemEditableRemoteObject getEditableFor(IAdaptable selected) + { + ISystemRemoteElementAdapter adapter = + (ISystemRemoteElementAdapter) ((IAdaptable) selected).getAdapter(ISystemRemoteElementAdapter.class); + if (adapter.canEdit(selected)) + { + ISystemEditableRemoteObject editable = adapter.getEditableRemoteObject(selected); + try + { + editable.setLocalResourceProperties(); + } + catch (Exception e) + { + } + return editable; + } + return null; + } + + protected boolean checkDirtyEditors() + { + SystemRemoteEditManager mgr = SystemRemoteEditManager.getDefault(); + if (!mgr.doesRemoteEditProjectExist()) + { + return true; + } + + List dirtyEditors = new ArrayList(); + if (!getDirtyReplicas(dirtyEditors)) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_CACHE_UNABLE_TO_SYNCH); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + dlg.open(); + + return false; + } + if (dirtyEditors.size() > 0) + { + AdaptableList input = new AdaptableList(); + for (int i = 0; i < dirtyEditors.size(); i++) + { + ISystemEditableRemoteObject rmtObj = (ISystemEditableRemoteObject) dirtyEditors.get(i); + input.add(rmtObj.getRemoteObject()); + } + + WorkbenchContentProvider cprovider = new WorkbenchContentProvider(); + SystemTableViewProvider lprovider = new SystemTableViewProvider(); + + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_CACHE_UPLOAD_BEFORE_DELETE); + + ListSelectionDialog dlg = + new ListSelectionDialog(getShell(), input, cprovider, lprovider, msg.getLevelOneText()); + + dlg.setInitialSelections(input.getChildren()); + // TODO: Cannot use WorkbenchMessages -- it's internal + dlg.setTitle(GenericMessages.EditorManager_saveResourcesTitle); + + int result = dlg.open(); + + //Just return false to prevent the operation continuing + if (result == IDialogConstants.CANCEL_ID) + return false; + + Object[] filesToSave = dlg.getResult(); + for (int s = 0; s < filesToSave.length; s++) + { + IAdaptable rmtObj = (IAdaptable) filesToSave[s]; + ISystemEditableRemoteObject editable = getEditableFor(rmtObj); + if (!editable.doImmediateSaveAndUpload()) + { + return false; + } + } + } + return true; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemFilePropertyPage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemFilePropertyPage.java new file mode 100644 index 00000000000..e57d0602f56 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/SystemFilePropertyPage.java @@ -0,0 +1,298 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.propertypages; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IVirtualRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.propertypages.SystemBasePropertyPage; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; + + +/** + * The remote property page for remote file properties. + * This is an output-only page. + * The plugin.xml file registers this for remote file system objects. + */ +public class SystemFilePropertyPage extends SystemBasePropertyPage + implements ISystemMessages, SelectionListener +{ + + protected Label labelNamePrompt, labelTypePrompt, labelPathPrompt, labelSizePrompt, + labelModifiedPrompt; + //protected Button cbReadablePrompt, cbWritablePrompt; + protected Button cbReadonlyPrompt, cbHiddenPrompt; + protected Label labelName, labelType, labelPath, labelSize, labelModified, labelReadable, labelWritable, labelHidden; + protected String errorMessage; + protected boolean initDone = false; + protected boolean wasReadOnly = false; + + /** + * Constructor for SystemFilterPropertyPage + */ + public SystemFilePropertyPage() + { + super(); + SystemPlugin sp = SystemPlugin.getDefault(); + } + /** + * Create the page's GUI contents. + */ + protected Control createContentArea(Composite parent) + { + IRemoteFile file = getRemoteFile(); + + // Inner composite + int nbrColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, nbrColumns); + + // Name display + labelNamePrompt = SystemWidgetHelpers.createLabel( + composite_prompts, SystemFileResources.RESID_PP_FILE_NAME_LABEL, SystemFileResources.RESID_PP_FILE_NAME_TOOLTIP); + labelName = SystemWidgetHelpers.createLabel( + composite_prompts, ""); + labelName.setToolTipText(SystemFileResources.RESID_PP_FILE_NAME_TOOLTIP); + + // Type display + labelTypePrompt = SystemWidgetHelpers.createLabel( + composite_prompts, SystemFileResources.RESID_PP_FILE_TYPE_LABEL, SystemFileResources.RESID_PP_FILE_TYPE_TOOLTIP); + labelType = SystemWidgetHelpers.createLabel( + composite_prompts, ""); + labelType.setToolTipText(SystemFileResources.RESID_PP_FILE_TYPE_TOOLTIP); + + // Path display + if (!file.isRoot()) + { + labelPathPrompt = SystemWidgetHelpers.createLabel( + composite_prompts, SystemFileResources.RESID_PP_FILE_PATH_LABEL, SystemFileResources.RESID_PP_FILE_PATH_TOOLTIP); + labelPath = SystemWidgetHelpers.createLabel( + composite_prompts, ""); + labelPath.setToolTipText(SystemFileResources.RESID_PP_FILE_PATH_TOOLTIP); + } + + // Size display + if (!file.isDirectory()) + { + labelSizePrompt = SystemWidgetHelpers.createLabel( + composite_prompts, SystemFileResources.RESID_PP_FILE_SIZE_LABEL, SystemFileResources.RESID_PP_FILE_SIZE_TOOLTIP); + labelSize = SystemWidgetHelpers.createLabel( + composite_prompts, ""); + labelSize.setToolTipText(SystemFileResources.RESID_PP_FILE_SIZE_TOOLTIP); + } + + // Modified display + if (!file.isRoot()) + { + labelModifiedPrompt = SystemWidgetHelpers.createLabel( + composite_prompts, SystemFileResources.RESID_PP_FILE_MODIFIED_LABEL, SystemFileResources.RESID_PP_FILE_MODIFIED_TOOLTIP); + labelModified = SystemWidgetHelpers.createLabel( + composite_prompts, ""); + labelModified.setToolTipText(SystemFileResources.RESID_PP_FILE_MODIFIED_TOOLTIP); + } + + // Readonly display + if (!file.isRoot()) + { + if (file.showReadOnlyProperty()) + { + cbReadonlyPrompt = SystemWidgetHelpers.createCheckBox( + composite_prompts, null, SystemFileResources.RESID_PP_FILE_READONLY_LABEL, SystemFileResources.RESID_PP_FILE_READONLY_TOOLTIP); + } + } + + /* + // Readable display + if (!file.isRoot()) + { + cbReadablePrompt = SystemWidgetHelpers.createCheckBox( + composite_prompts, null, SystemFileResources.RESID_PP_FILE_READABLE_ROOT); + } + + // Writable display + if (!file.isRoot()) + { + cbWritablePrompt = SystemWidgetHelpers.createCheckBox( + composite_prompts, null, SystemFileResources.RESID_PP_FILE_WRITABLE_ROOT); + } + */ + + // Hidden display + if (!file.isRoot()) + { + cbHiddenPrompt = SystemWidgetHelpers.createCheckBox( + composite_prompts, null, SystemFileResources.RESID_PP_FILE_HIDDEN_LABEL, SystemFileResources.RESID_PP_FILE_HIDDEN_TOOLTIP); + //((GridData)cbHiddenPrompt.getLayoutData()).horizontalSpan = nbrColumns; + } + + if (!initDone) + doInitializeFields(); + + if (!file.isRoot() && file.showReadOnlyProperty()) + cbReadonlyPrompt.addSelectionListener(this); + + return composite_prompts; + } + /** + * Get the input remote file object + */ + protected IRemoteFile getRemoteFile() + { + Object element = getElement(); + return ((IRemoteFile)element); + } + + /** + * Initialize values of input fields based on input + */ + protected void doInitializeFields() + { + initDone = true; + IRemoteFile file = getRemoteFile(); + // name + String name = file.getName(); + if (name.length() > 100) + { + String shortName = name.substring(0, 97).concat("..."); + labelName.setText(shortName); + } + else + { + labelName.setText(name); + } + + // type + if (file.isRoot()) + labelType.setText(SystemFileResources.RESID_PP_FILE_TYPE_ROOT_VALUE); + else if (file.isDirectory()) + labelType.setText(SystemFileResources.RESID_PP_FILE_TYPE_FOLDER_VALUE); + else + labelType.setText(SystemFileResources.RESID_PP_FILE_TYPE_FILE_VALUE); + // path + if (labelPath != null) + { + String path = file.getParentPath(); + if (path != null) + labelPath.setText(file.getParentPath()); + } + // size + if (labelSize != null) + labelSize.setText(Long.toString(file.getLength())); + // modified + if (labelModified != null) + { + Date date = file.getLastModifiedDate(); + if (date != null) + { + SimpleDateFormat datefmt = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); + labelModified.setText(datefmt.format(date)); + } + } + // readonly + if (file.showReadOnlyProperty()) { + if (cbReadonlyPrompt != null) + { + cbReadonlyPrompt.setSelection(!file.canWrite()); + wasReadOnly = !file.canWrite(); + if (wasReadOnly || file instanceof IVirtualRemoteFile) + cbReadonlyPrompt.setEnabled(false); + } + } + /* + // readable + if (cbReadablePrompt != null) + { + cbReadablePrompt.setSelection(file.canRead()); + cbReadablePrompt.setEnabled(false); + } + // writable + if (cbWritablePrompt != null) + { + cbWritablePrompt.setSelection(file.canWrite()); + cbWritablePrompt.setEnabled(false); + } + */ + // hidden + if (cbHiddenPrompt != null) + { + cbHiddenPrompt.setSelection(file.isHidden()); + cbHiddenPrompt.setEnabled(false); + } + } + + /** + * Called by parent when user presses OK + */ + public boolean performOk() + { + boolean ok = super.performOk(); + if (ok && (cbReadonlyPrompt!=null) && cbReadonlyPrompt.getSelection() && !wasReadOnly) + { + try + { + getRemoteFile().getParentRemoteFileSubSystem().setReadOnly(getRemoteFile()); + SystemPlugin.getTheSystemRegistry().fireEvent( + new org.eclipse.rse.model.SystemResourceChangeEvent( + getRemoteFile(),ISystemResourceChangeEvents.EVENT_PROPERTY_CHANGE,null)); + + } catch (RemoteFileIOException exc) + { + setMessage(SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_IO_ERROR)); + } catch (RemoteFileSecurityException exc) + { + setMessage(SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_SECURITY_ERROR)); + } + //catch (RemoteFileException e) + //{ + //} + } + return ok; + } + /** + * Validate all the widgets on the page + *

    + * Subclasses should override to do full error checking on all + * the widgets on the page. + */ + protected boolean verifyPageContents() + { + return true; + } + + public void widgetDefaultSelected(SelectionEvent event) + { + + } + public void widgetSelected(SelectionEvent event) + { + + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/UniversalPreferencePage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/UniversalPreferencePage.java new file mode 100644 index 00000000000..b11e5bb2b36 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/propertypages/UniversalPreferencePage.java @@ -0,0 +1,962 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.propertypages; + +import java.util.ArrayList; +import java.util.Iterator; + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.jface.preference.FieldEditorPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ColumnLayoutData; +import org.eclipse.jface.viewers.ColumnPixelData; +import org.eclipse.jface.viewers.ColumnWeightData; +import org.eclipse.jface.viewers.TableLayout; +import org.eclipse.jface.window.Window; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageFile; +import org.eclipse.rse.subsystems.files.core.model.SystemFileTransferModeMapping; +import org.eclipse.rse.subsystems.files.core.model.SystemFileTransferModeRegistry; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.Mnemonics; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.swt.widgets.TableItem; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IFileEditorMapping; +import org.eclipse.ui.IPropertyListener; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.internal.dialogs.FileExtensionDialog; +import org.eclipse.ui.internal.registry.EditorRegistry; +import org.eclipse.ui.internal.registry.FileEditorMapping; + + + +/** + * "Files" Preference page within the Remote Systems preference node. + * This allows users to specify, per file extension, whether files are + * source or binary. + */ +public class UniversalPreferencePage + extends FieldEditorPreferencePage + implements IWorkbenchPreferencePage, Listener, IPropertyListener +{ + + + + protected Label resourceTypeLabel; + protected Table resourceTypeTable; + protected Button addResourceTypeButton; + protected Button removeResourceTypeButton; + protected Button binaryButton; + protected Button textButton; + protected Button doSuperTransferButton; + + protected Button defaultBinaryButton; + protected Button defaultTextButton; + + protected SystemFileTransferModeRegistry modeRegistry; + protected IEditorRegistry editorRegistry; + + protected ArrayList modeMappings; + protected ArrayList editorMappings; + protected ArrayList imagesToDispose; + + protected Combo archiveTypeCombo; + protected Combo defaultArchiveTypeCombo; + + protected Text downloadBufferSize; + protected Text uploadBufferSize; + + /** + * Constructor + */ + public UniversalPreferencePage() { + super(GRID); + setPreferenceStore(SystemPlugin.getDefault().getPreferenceStore()); + setDescription(FileResources.RESID_PREF_UNIVERSAL_FILES_TITLE); + } + + /** + * @see org.eclipse.jface.preference.PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages + super.createControl(parent); + + } + + + protected void createFieldEditors() { + + modeRegistry = (SystemFileTransferModeRegistry)(SystemFileTransferModeRegistry.getDefault()); + editorRegistry = (IEditorRegistry)(SystemPlugin.getDefault().getWorkbench().getEditorRegistry()); + + modeMappings = new ArrayList(); + editorMappings = new ArrayList(); + imagesToDispose = new ArrayList(); + + Composite parent = getFieldEditorParent(); + + + + // define container and its layout + Composite pageComponent = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + pageComponent.setLayout(layout); + GridData data = new GridData(); + data.verticalAlignment = GridData.FILL; + data.horizontalAlignment = GridData.FILL; + pageComponent.setLayoutData(data); + + // file types label + resourceTypeLabel = new Label(pageComponent, SWT.LEFT); + resourceTypeLabel.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_LABEL); + resourceTypeLabel.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_TYPE_TOOLTIP); + data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.horizontalSpan = 2; + resourceTypeLabel.setLayoutData(data); + + // file types table + resourceTypeTable = new Table(pageComponent, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); + resourceTypeTable.addListener(SWT.Selection, this); + resourceTypeTable.addListener(SWT.DefaultSelection, this); + data = new GridData(GridData.FILL_BOTH); + data.heightHint = resourceTypeTable.getItemHeight() * 12; + data.widthHint = 200; + data.grabExcessHorizontalSpace = true; + resourceTypeTable.setLayoutData(data); + + // container for buttons + Composite groupComponent= new Composite(pageComponent, SWT.NULL); + groupComponent.setLayout(new GridLayout()); + data = new GridData(); + data.verticalAlignment = GridData.FILL; + data.horizontalAlignment = GridData.FILL; + groupComponent.setLayoutData(data); + + // add button + addResourceTypeButton = new Button(groupComponent, SWT.PUSH); + addResourceTypeButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_LABEL); + addResourceTypeButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_ADDBUTTON_TOOLTIP); + addResourceTypeButton.addListener(SWT.Selection, this); + data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.heightHint = convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); + int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + data.widthHint = Math.max(widthHint, addResourceTypeButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + addResourceTypeButton.setLayoutData(data); + + // remove button + removeResourceTypeButton = new Button(groupComponent, SWT.PUSH); + removeResourceTypeButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_LABEL); + removeResourceTypeButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_REMOVEBUTTON_TOOLTIP); + removeResourceTypeButton.addListener(SWT.Selection, this); + data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.heightHint = convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT); + widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); + data.widthHint = Math.max(widthHint, removeResourceTypeButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); + removeResourceTypeButton.setLayoutData(data); + + + // transfer mode + Group modeGroup = new Group(groupComponent, SWT.SHADOW_ETCHED_IN); + modeGroup.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_LABEL); + modeGroup.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TOOLTIP); + + layout = new GridLayout(); + layout.numColumns = 1; + //layout.verticalSpacing = 10; + layout.horizontalSpacing = 10; + modeGroup.setLayout(layout); + data = new GridData(GridData.FILL_BOTH); + data.horizontalSpan = 2; + data.widthHint = 100; + data.grabExcessHorizontalSpace = true; + modeGroup.setLayoutData(data); + + // add the binary radio button + binaryButton = new Button(modeGroup, SWT.RADIO); + binaryButton.addListener(SWT.Selection, this); + binaryButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_LABEL); + binaryButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_TOOLTIP); + + // add the text radio button + textButton = new Button(modeGroup, SWT.RADIO); + textButton.addListener(SWT.Selection, this); + textButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_LABEL); + textButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_TOOLTIP); + + +// default file transfer mode + Group defaultModeGroup = new Group(groupComponent, SWT.SHADOW_ETCHED_IN); + defaultModeGroup.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_LABEL); + defaultModeGroup.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_DEFAULT_MODE_TOOLTIP); + + layout = new GridLayout(); + layout.numColumns = 1; + //layout.verticalSpacing = 10; + layout.horizontalSpacing = 10; + defaultModeGroup.setLayout(layout); + data = new GridData(GridData.FILL_BOTH); + data.horizontalSpan = 2; + data.widthHint = 100; + data.grabExcessHorizontalSpace = true; + defaultModeGroup.setLayoutData(data); + + // add the binary radio button + defaultBinaryButton = new Button(defaultModeGroup, SWT.RADIO); + defaultBinaryButton.addListener(SWT.Selection, this); + defaultBinaryButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_LABEL); + defaultBinaryButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_BINARY_TOOLTIP); + + // add the text radio button + defaultTextButton = new Button(defaultModeGroup, SWT.RADIO); + defaultTextButton.addListener(SWT.Selection, this); + defaultTextButton.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_LABEL); + defaultTextButton.setToolTipText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_MODE_TEXT_TOOLTIP); + + + + // Add the boolean field editor for users to choose whether + // hidden files should be displayed + BooleanFieldEditor showHiddenEditor = new BooleanFieldEditor( + ISystemPreferencesConstants.SHOWHIDDEN, + FileResources.RESID_PREF_UNIVERSAL_SHOWHIDDEN_LABEL, + groupComponent); + + addField(showHiddenEditor); + + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + + // download and upload buffer size + + Group transferGroup = new Group(parent, SWT.NULL); + transferGroup.setText(FileResources.RESID_FILES_PREFERENCES_BUFFER); + + GridLayout tlayout = new GridLayout(); + tlayout.numColumns = 4; + transferGroup.setLayout(tlayout); + transferGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Label downloadBufferLabel = new Label(transferGroup, SWT.NULL); + downloadBufferLabel.setText(FileResources.RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_LABEL); + downloadBufferLabel.setToolTipText(FileResources.RESID_FILES_PREFERENCES_DOWNLOAD_BUFFER_SIZE_TOOLTIP); + + downloadBufferSize = SystemWidgetHelpers.createTextField(transferGroup, this); + GridData tgd = new GridData(); + tgd.widthHint = 75; + downloadBufferSize.setLayoutData(tgd); + downloadBufferSize.setTextLimit(10); + downloadBufferSize.setText(getDownloadBufferSize() + ""); + downloadBufferSize.addVerifyListener(new VerifyListener() + { + public void verifyText(VerifyEvent e) + { + e.doit = true; + for (int loop = 0; loop < e.text.length(); loop++) + { + if (!Character.isDigit(e.text.charAt(loop))) + e.doit = false; + } + } + }); + + Label uploadBufferLabel = new Label(transferGroup, SWT.NULL); + uploadBufferLabel.setText(FileResources.RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_LABEL); + uploadBufferLabel.setToolTipText(FileResources.RESID_FILES_PREFERENCES_UPLOAD_BUFFER_SIZE_TOOLTIP); + uploadBufferSize = SystemWidgetHelpers.createTextField(transferGroup, this); + tgd = new GridData(); + tgd.widthHint = 75; + uploadBufferSize.setLayoutData(tgd); + uploadBufferSize.setTextLimit(10); + uploadBufferSize.setText(getUploadBufferSize() +""); + uploadBufferSize.addVerifyListener(new VerifyListener() + { + public void verifyText(VerifyEvent e) + { + e.doit = true; + for (int loop = 0; loop < e.text.length(); loop++) + { + if (!Character.isDigit(e.text.charAt(loop))) + { + e.doit = false; + } + } + } + }); + + + // archive transfer + Composite archiveGroup = new Composite(parent, SWT.NULL); + GridLayout alayout = new GridLayout(); + alayout.numColumns = 2; + archiveGroup.setLayout(alayout); + archiveGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); + + + doSuperTransferButton = SystemWidgetHelpers.createCheckBox(archiveGroup, FileResources.RESID_SUPERTRANSFER_PREFS_ENABLE, this); + GridData cdata = new GridData(); + cdata.horizontalSpan = 2; + doSuperTransferButton.setLayoutData(cdata); + + archiveTypeCombo = SystemWidgetHelpers.createLabeledReadonlyCombo(archiveGroup, null, FileResources.RESID_SUPERTRANSFER_PREFS_TYPE_LABEL, FileResources.RESID_SUPERTRANSFER_PREFS_TYPE_TOOLTIP); + archiveTypeCombo.setItems(ArchiveHandlerManager.getInstance().getRegisteredExtensions()); + + boolean doSuperTransfer = getDoSuperTransfer(); + doSuperTransferButton.setSelection(doSuperTransfer); + + String initialArchiveType = store.getString(ISystemPreferencesConstants.SUPERTRANSFER_ARC_TYPE); + if (initialArchiveType == null || + !ArchiveHandlerManager.getInstance().isRegisteredArchive("test." + initialArchiveType)) + { + initialArchiveType = ISystemPreferencesConstants.DEFAULT_SUPERTRANSFER_ARCHIVE_TYPE; + } + archiveTypeCombo.setText(initialArchiveType); + archiveTypeCombo.setTextLimit(6); + archiveTypeCombo.addModifyListener(new ModifyListener() { + + public void modifyText(ModifyEvent e) + { + setSuperTransferTypePreference(archiveTypeCombo.getText()); + } + }); + + archiveTypeCombo.setEnabled(doSuperTransfer); + + + + + fillResourceTypeTable(); + + if (resourceTypeTable.getItemCount() > 0) { + resourceTypeTable.setSelection(0); + resourceTypeTable.setFocus(); + } + + fillMode(); + updateEnabledState(); + + (new Mnemonics()).setOnPreferencePage(true).setMnemonics(parent); + SystemWidgetHelpers.setCompositeHelp(parent, SystemPlugin.HELPPREFIX+"ufpf0000"); + + } + + public void init(IWorkbench workbench) + { + } + + public static void initDefaults(IPreferenceStore store) + { + store.setDefault(ISystemPreferencesConstants.SHOWHIDDEN, false); + store.setDefault(ISystemPreferencesConstants.DOSUPERTRANSFER, ISystemPreferencesConstants.DEFAULT_DOSUPERTRANSFER); + store.setDefault(ISystemPreferencesConstants.SUPERTRANSFER_ARC_TYPE, ISystemPreferencesConstants.DEFAULT_SUPERTRANSFER_ARCHIVE_TYPE); + store.setDefault(ISystemPreferencesConstants.DOWNLOAD_BUFFER_SIZE, ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE); + store.setDefault(ISystemPreferencesConstants.UPLOAD_BUFFER_SIZE, ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE); + } + + + /** + * Fill the resource type table + */ + protected void fillResourceTypeTable() { + + // Setup the columns (icon, type) + TableLayout tableLayout = new TableLayout(); + resourceTypeTable.setLayout(tableLayout); + resourceTypeTable.setHeaderVisible(true); + + ColumnLayoutData layoutData = new ColumnPixelData(20, false); + tableLayout.addColumnData(layoutData); + TableColumn tableCol = new TableColumn(resourceTypeTable, SWT.NONE); + tableCol.setResizable(false); + tableCol.setText(""); + + layoutData = new ColumnWeightData(40, false); + tableLayout.addColumnData(layoutData); + tableCol = new TableColumn(resourceTypeTable, SWT.NONE); + tableCol.setResizable(false); + tableCol.setText(FileResources.RESID_PREF_UNIVERSAL_FILES_FILETYPES_TABLECOL_LABEL); + + IFileEditorMapping[] mappingArray = editorRegistry.getFileEditorMappings(); + + for (int i = 0; i < mappingArray.length; i++) { + newResourceTableItem(mappingArray[i], i, false); + } + + int defaultFileTransferMode = getFileTransferModeDefaultPreference(); + if (defaultFileTransferMode == ISystemPreferencesConstants.FILETRANSFERMODE_BINARY) + { + defaultBinaryButton.setSelection(true); + } + else if (defaultFileTransferMode == ISystemPreferencesConstants.FILETRANSFERMODE_TEXT) + { + defaultTextButton.setSelection(true); + } + } + + /** + * Used during reset defaults + */ + protected void resetResourceTypeTable() + { + //clear table and reload defaults + editorMappings.clear(); + modeMappings.clear(); + resourceTypeTable.setRedraw(false); + resourceTypeTable.removeAll(); + + + IFileEditorMapping[] mappingArray = editorRegistry.getFileEditorMappings(); + for (int i = 0; i < mappingArray.length; i++) + { + newResourceTableItem(mappingArray[i], i, false); + } + resourceTypeTable.setRedraw(true); + + int defaultFileTransferMode = getFileTransferModeDefaultPreference(); + defaultBinaryButton.setSelection(defaultFileTransferMode == ISystemPreferencesConstants.FILETRANSFERMODE_BINARY); + defaultTextButton.setSelection(defaultFileTransferMode == ISystemPreferencesConstants.FILETRANSFERMODE_TEXT); + + if (resourceTypeTable.getItemCount() > 0) + { + resourceTypeTable.setSelection(0); + resourceTypeTable.setFocus(); + } + + fillMode(); + updateEnabledState(); + } + + protected void resetSuperTransferPrefs() + { + archiveTypeCombo.setText(ISystemPreferencesConstants.DEFAULT_SUPERTRANSFER_ARCHIVE_TYPE); + setSuperTransferTypePreference(ISystemPreferencesConstants.DEFAULT_SUPERTRANSFER_ARCHIVE_TYPE); + doSuperTransferButton.setSelection(ISystemPreferencesConstants.DEFAULT_DOSUPERTRANSFER); + setDoSuperTransfer(ISystemPreferencesConstants.DEFAULT_DOSUPERTRANSFER); + } + + protected void resetBufferSizePrefs() + { + downloadBufferSize.setText(ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE + ""); + uploadBufferSize.setText(ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE + ""); + } + + /** + * Create a new TableItem to represent the resource + * type editor description supplied. + */ + protected TableItem newResourceTableItem(IFileEditorMapping mapping, int index, boolean selected) { + + editorMappings.add(index, ((FileEditorMapping)mapping).clone()); + modeMappings.add(index, modeRegistry.getMapping(mapping).clone()); + + Image image = mapping.getImageDescriptor().createImage(false); + + if (image != null) + imagesToDispose.add(image); + + TableItem item = new TableItem(resourceTypeTable, SWT.NULL, index); + item.setImage(0, image); + item.setText(1, mapping.getLabel()); + + if (selected) + resourceTypeTable.setSelection(index); + + return item; + } + + + /** + * The preference page is going to be disposed. So deallocate all allocated + * SWT resources that aren't disposed automatically by disposing the page + * (i.e. fonts, cursors, etc). Subclasses should reimplement this method to + * release their own allocated SWT resources. + */ + public void dispose() { + + super.dispose(); + + if(imagesToDispose != null) { + + for (Iterator e = imagesToDispose.iterator(); e.hasNext();) { + ((Image)e.next()).dispose(); + } + + imagesToDispose = null; + } + } + + + /** + * @see Listener#handleEvent(Event) + */ + public void handleEvent(Event event) { + + if ((event.widget == resourceTypeTable) && ((event.type == SWT.Selection) || (event.type == SWT.DefaultSelection))) { + fillMode(); + } + if ((event.widget == addResourceTypeButton) && (event.type == SWT.Selection)) { + promptForResourceType(); + } + else if ((event.widget == removeResourceTypeButton) && (event.type == SWT.Selection)) { + removeSelectedResourceType(); + } + else if ((event.widget == binaryButton) && (event.type == SWT.Selection)) { + binaryButtonSelected(); + } + else if ((event.widget == textButton) && (event.type == SWT.Selection)) { + textButtonSelected(); + } + else if ((event.widget == doSuperTransferButton) && (event.type == SWT.Selection)) + { + doSuperTransferButtonSelected(); + } + updateEnabledState(); + } + + + /** + * Fill the mode widgets + */ + public void fillMode() { + + int index = resourceTypeTable.getSelectionIndex(); + SystemFileTransferModeMapping modeMapping = getModeMapping(index); + + if (modeMapping !=null) + { + if (modeMapping.isBinary()) { + binaryButton.setSelection(true); + textButton.setSelection(false); + } + else { + binaryButton.setSelection(false); + textButton.setSelection(true); + } + } + } + + + /** + * Prompt for file type + */ + public void promptForResourceType() { + + FileExtensionDialog dialog = new FileExtensionDialog(getControl().getShell()); + + if (dialog.open() == Window.OK) { + + String name = dialog.getName(); + String extension = dialog.getExtension(); + + if (extension.length() > 0) { + addResourceType(name, extension); + } + } + } + + + /** + * Remove the type from the table + */ + public void removeSelectedResourceType() { + + int index = resourceTypeTable.getSelectionIndex(); + + editorMappings.remove(index); + modeMappings.remove(index); + + TableItem[] items = resourceTypeTable.getSelection(); + + if (items.length > 0) { + items[0].dispose(); + } + } + + + /** + * Add a new resource type to the collection shown in the top of the page. + * This is typically called after the extension dialog is shown to the user. + */ + public void addResourceType(String newName, String newExtension) { + + // no extension is provided + if (newExtension == null || newExtension.length() < 1) { +// Note by DWD - this path is never taken because the dialog that gathers resource types checks for this condition + SystemMessageFile mf = SystemPlugin.getPluginMessageFile(); + Shell shell = getControl().getShell(); + SystemMessage message = mf.getMessage(ISystemMessages.MSG_ERROR_EXTENSION_EMPTY); + SystemMessageDialog.displayErrorMessage(shell, message); +// Removed by DWD - 2004-07-28 - these two messages don't exist +// MessageDialog.openInformation(getControl().getShell(), +// GenericMessages.getString("FileEditorPreference.extensionEmptyTitle"), +// GenericMessages.getString("FileEditorPreference.extensionEmptyMessage")); + return; + } + + if (newName == null || newName.length() < 1) + newName = "*"; + else { + + int index = newName.indexOf('*'); + + if (index > -1) { + + // if the name is more than one character, and it has a '*' in it + if (!(index == 0 && newName.length() == 1)) { +// Note by DWD - this path is never taken because the dialog that gathers resource types checks for this condition. + SystemMessageFile mf = SystemPlugin.getPluginMessageFile(); + Shell shell = getControl().getShell(); + SystemMessage message = mf.getMessage(ISystemMessages.MSG_ERROR_FILENAME_INVALID); + SystemMessageDialog.displayErrorMessage(shell, message); +// removed by DWD - 2004-07-28 - these two messages don't exist +// MessageDialog.openInformation(getControl().getShell(), +// GenericMessages.getString("FileEditorPreference.fileNameInvalidTitle"), +// GenericMessages.getString("FileEditorPreference.fileNameInvalidMessage")); + return; + } + } + } + + // Find the index at which to insert the new entry. + String newFilename = (newName + "." + newExtension).toUpperCase(); + IFileEditorMapping resourceType; + boolean found = false; + int i = 0; + + while (i < editorMappings.size() && !found) { + + resourceType = (FileEditorMapping)(editorMappings.get(i)); + + int result = newFilename.compareTo(resourceType.getLabel().toUpperCase()); + + // if the type already exists + if (result == 0) { + + MessageDialog.openInformation(getControl().getShell(), + // TODO: Cannot use WorkbenchMessages -- it's internal + FileResources.FileEditorPreference_existsTitle, + // TODO: Cannot use WorkbenchMessages -- it's internal + FileResources.FileEditorPreference_existsMessage); + return; + } + + if (result < 0) + found = true; + else + i++; + } + + // Create the new type and insert it + resourceType = new FileEditorMapping(newName, newExtension); + newResourceTableItem(resourceType, i, true); + resourceTypeTable.setFocus(); + fillMode(); + } + + + /** + * Helper method to configure things when binary mode radio button + * is selected + */ + private void binaryButtonSelected() { + //binaryButton.setSelection(true); // causes hang on linux + //textButton.setSelection(false); + + int index = resourceTypeTable.getSelectionIndex(); + SystemFileTransferModeMapping modeMapping = getModeMapping(index); + if (modeMapping != null) + modeMapping.setAsBinary(); + } + + + /** + * Helper method to configure things when text mode is selected + */ + private void textButtonSelected() { + // textButton.setSelection(true); // causes hang on linux + // binaryButton.setSelection(false); + + int index = resourceTypeTable.getSelectionIndex(); + SystemFileTransferModeMapping modeMapping = getModeMapping(index); + if (modeMapping != null) + modeMapping.setAsText(); + } + + private void doSuperTransferButtonSelected() + { + if (doSuperTransferButton.getSelection()) + { + archiveTypeCombo.setEnabled(true); + } + else + { + archiveTypeCombo.setEnabled(false); + } + } + + /** + * Gets the mode mapping given the editor mapping selected + */ + private SystemFileTransferModeMapping getModeMapping(int index) { + + if (index >=0 && index < modeMappings.size()) + return (SystemFileTransferModeMapping)(modeMappings.get(index)); + else + return null; + } + + + /** + * Update enabled state of buttons + */ + public void updateEnabledState() { + + boolean resourceTypeSelected = resourceTypeTable.getSelectionIndex() != -1; + removeResourceTypeButton.setEnabled(resourceTypeSelected); + } + + + protected void performDefaults() + { + super.performDefaults(); + resetResourceTypeTable(); + + resetSuperTransferPrefs(); + resetBufferSizePrefs(); + } + + /** + * Stuff to do when ok is pressed + */ + public boolean performOk() { + + super.performOk(); + + // first save the transfer mode registry + Object[] array1 = modeMappings.toArray(); + SystemFileTransferModeMapping[] mappingArray1 = new SystemFileTransferModeMapping[array1.length]; + + for (int i = 0; i < array1.length; i++) { + mappingArray1[i] = (SystemFileTransferModeMapping)(array1[i]); + } + + modeRegistry.setModeMappings(mappingArray1); + modeRegistry.saveAssociations(); + + // then save the editor registry + Object[] array2 = editorMappings.toArray(); + FileEditorMapping[] mappingArray2 = new FileEditorMapping[array2.length]; + + for (int j = 0; j < array2.length; j++) { + mappingArray2[j] = (FileEditorMapping)(array2[j]); + } + + ((EditorRegistry)editorRegistry).setFileEditorMappings(mappingArray2); + ((EditorRegistry)editorRegistry).saveAssociations(); + + // editorRegistry.removePropertyListener(this); + int defaultFileTransferMode = ISystemPreferencesConstants.FILETRANSFERMODE_BINARY; + if (defaultBinaryButton.getSelection()) + { + defaultFileTransferMode = ISystemPreferencesConstants.FILETRANSFERMODE_BINARY; + } + else + { + defaultFileTransferMode = ISystemPreferencesConstants.FILETRANSFERMODE_TEXT; + } + setFileTransferModeDefaultPreference(defaultFileTransferMode); + setDoSuperTransfer(doSuperTransferButton.getSelection()); + setSuperTransferTypePreference(archiveTypeCombo.getText()); + setDownloadBufferSize(downloadBufferSize.getText()); + setUploadBufferSize(uploadBufferSize.getText()); + + return true; + } + + /** + * Return whether to automatically detect, use binary or text during file transfer + * for unspecified file types + */ + public static int getFileTransferModeDefaultPreference() + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + return store.getInt(ISystemPreferencesConstants.FILETRANSFERMODEDEFAULT); + } + /** + * Set the default file transfer mode to use for unspecified file types + */ + public static void setFileTransferModeDefaultPreference(int defaultMode) + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + store.setValue(ISystemPreferencesConstants.FILETRANSFERMODEDEFAULT,defaultMode); + savePreferenceStore(); + } + + /** + * Return whether to compress directories before transferring them over the network + */ + public static String getSuperTransferTypePreference() + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + return store.getString(ISystemPreferencesConstants.SUPERTRANSFER_ARC_TYPE); + } + /** + * Set the default as to whether or not to compress directories before remote transfer + */ + public static void setSuperTransferTypePreference(String type) + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + store.setValue(ISystemPreferencesConstants.SUPERTRANSFER_ARC_TYPE,type); + savePreferenceStore(); + } + + public static boolean getDoSuperTransfer() + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + return store.getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + } + + public static int getDownloadBufferSize() + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + int result = store.getInt(ISystemPreferencesConstants.DOWNLOAD_BUFFER_SIZE); + if (result == 0) + { + result = ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE; + } + return result; + } + + public static int getUploadBufferSize() + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + int result = store.getInt(ISystemPreferencesConstants.UPLOAD_BUFFER_SIZE); + if (result == 0) + { + result = ISystemPreferencesConstants.DEFAULT_DOWNLOAD_BUFFER_SIZE; + } + return result; + } + + public static void setDoSuperTransfer(boolean flag) + { + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + store.setValue(ISystemPreferencesConstants.DOSUPERTRANSFER,flag); + savePreferenceStore(); + } + + public static void setDownloadBufferSize(String size) + { + setDownloadBufferSize(Integer.parseInt(size)); + } + + public static void setUploadBufferSize(String size) + { + setUploadBufferSize(Integer.parseInt(size)); + } + + public static void setDownloadBufferSize(int size) + { + if (size > 0) + { + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + store.setValue(ISystemPreferencesConstants.DOWNLOAD_BUFFER_SIZE, size); + savePreferenceStore(); + } + } + + public static void setUploadBufferSize(int size) + { + if (size > 0) + { + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + store.setValue(ISystemPreferencesConstants.UPLOAD_BUFFER_SIZE, size); + savePreferenceStore(); + } + } + + /** + * Save the preference store + */ + private static void savePreferenceStore() + { + /* DY: This was causing ClassCastException in 2.0 + * getPreferenceStore retutrns CompatibilityPreferenceStore now + PreferenceStore store = (PreferenceStore)SystemPlugin.getDefault().getPreferenceStore(); + try { + store.save(); + } catch (Exception exc) + { + System.out.println("Error saving preferences: " + exc.getMessage() + ": " + exc.getClass().getName()); + } + */ + // ok, a couple hours of research leads me to believe this is now the new + // thing to do... phil + SystemPlugin.getDefault().savePluginPreferences(); + } + + /** + * Listen for changes to the Editor Registry content. + * Update our registry by changing the hashmap and saving the new + * mappings on disk. + * @see IPropertyListener#propertyChanged(Object, int) + */ + public void propertyChanged(Object source, int propId) { + + if ((source instanceof IEditorRegistry) && (propId == IEditorRegistry.PROP_CONTENTS)) { + + // the OK button was pressed, and we need to incorporate changes from the File Editors preference page + IEditorRegistry registry = (IEditorRegistry)source; + + IFileEditorMapping[] editorMappingArray = registry.getFileEditorMappings(); + + for (int i = 0; i < editorMappingArray.length; i++) { + } + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveDialog.java new file mode 100644 index 00000000000..904e4ea35d9 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveDialog.java @@ -0,0 +1,90 @@ +/******************************************************************************** + * Copyright (c) 2004, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class AddToArchiveDialog extends CombineDialog { + + private String[] _relativePaths; + + public AddToArchiveDialog(Shell shell) + { + super(shell); + setHelp(SystemPlugin.HELPPREFIX + "atad0000"); + } + + public AddToArchiveDialog(Shell shell, String title) { + super(shell, title); + setHelp(SystemPlugin.HELPPREFIX + "atad0000"); + } + + public AddToArchiveDialog(Shell shell, String title, String[] relativePaths) + { + super(shell, title); + setHelp(SystemPlugin.HELPPREFIX + "atad0000"); + _relativePaths = relativePaths; + ((AddToArchiveForm)form).setRelativePathList(_relativePaths); + } + + public AddToArchiveDialog( + Shell shell, + String title, + boolean prePopSelection) + { + super(shell, title, prePopSelection); + setHelp(SystemPlugin.HELPPREFIX + "atad0000"); + } + + public AddToArchiveDialog( + Shell shell, + String title, + boolean prePopSelection, + String[] relativePaths) + { + super(shell, title, prePopSelection); + setHelp(SystemPlugin.HELPPREFIX + "atad0000"); + _relativePaths = relativePaths; + ((AddToArchiveForm)form).setRelativePathList(_relativePaths); + } + + + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + super.getForm(fileMode); + form = new AddToArchiveForm(getMessageLine(), this, fileMode, prePop, _relativePaths); + return form; + } + + public boolean getSaveFullPathInfo() + { + return ((AddToArchiveForm)form).getSaveFullPathInfo(); + } + + public String getRelativePath() + { + return ((AddToArchiveForm)form).getRelativePath(); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveForm.java new file mode 100644 index 00000000000..4fa49744187 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/AddToArchiveForm.java @@ -0,0 +1,177 @@ +/******************************************************************************** + * Copyright (c) 2004, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class AddToArchiveForm extends CombineForm +{ + + protected Button savePathInfoCheckBox; + protected Combo relativeToCombo; + protected String[] _relativePathList = null; + protected String relativePath = ""; + protected boolean saveFullPathInfo = false; + + public AddToArchiveForm( + ISystemMessageLine msgLine, + Object caller, + boolean fileMode) + { + super(msgLine, caller, fileMode); + } + + public AddToArchiveForm( + ISystemMessageLine msgLine, + Object caller, + boolean fileMode, + boolean prePopSelection) + { + super(msgLine, caller, fileMode, prePopSelection); + } + + public AddToArchiveForm( + ISystemMessageLine msgLine, + Object caller, + boolean fileMode, + boolean prePopSelection, + String[] relativePaths) +{ + super(msgLine, caller, fileMode, prePopSelection); + _relativePathList = relativePaths; + enableRelativePathFeature(relativePaths != null); +} + + public void setRelativePathList(String[] relativePathList) + { + if (relativePathList != null) + { + _relativePathList = relativePathList; + if (relativeToCombo != null) relativeToCombo.setItems(relativePathList); + enableRelativePathFeature(true); + } + else + { + enableRelativePathFeature(false); + } + } + + protected void enableRelativePathFeature(boolean enable) + { + if (relativeToCombo != null) relativeToCombo.setEnabled(enable); + if (savePathInfoCheckBox != null) savePathInfoCheckBox.setEnabled(enable); + } + + /** + * In this method, we populate the given SWT container with widgets and return the container + * to the caller. + * @param parent The parent composite + */ + public Control createContents(Shell shell, Composite parent) + { + Control control = super.createContents(shell, parent); + + Composite composite = SystemWidgetHelpers.createComposite(parent, 1); + + savePathInfoCheckBox = SystemWidgetHelpers.createCheckBox(composite, null, FileResources.RESID_ADDTOARCHIVE_SAVEPATH_LABEL, FileResources.RESID_ADDTOARCHIVE_SAVEPATH_TOOLTIP); + relativeToCombo = SystemWidgetHelpers.createLabeledReadonlyCombo(composite, null, FileResources.RESID_ADDTOARCHIVE_RELATIVETO_LABEL, FileResources.RESID_ADDTOARCHIVE_RELATIVETO_LABEL); + + enableRelativePathFeature(_relativePathList != null); + + if (_relativePathList != null) + { + relativeToCombo.setItems(_relativePathList); + relativeToCombo.setEnabled(false); + } + + savePathInfoCheckBox.addSelectionListener(new SelectionListener() { + + public void widgetDefaultSelected(SelectionEvent e) { + setPageComplete(); + relativeToCombo.setEnabled(savePathInfoCheckBox.getSelection()); + if (!savePathInfoCheckBox.getSelection()) relativePath = ""; + setSaveFullPathInfo(); + } + public void widgetSelected(SelectionEvent e) { + setPageComplete(); + relativeToCombo.setEnabled(savePathInfoCheckBox.getSelection()); + if (!savePathInfoCheckBox.getSelection()) relativePath = ""; + setSaveFullPathInfo(); + } + }); + + relativeToCombo.addModifyListener(new ModifyListener() { + + public void modifyText(ModifyEvent e) { + relativePath = relativeToCombo.getText(); + setPageComplete(); + } + }); + + return control; + } + + public boolean isPageComplete() + { + boolean pathInfoChecked = (savePathInfoCheckBox != null && savePathInfoCheckBox.getSelection()); + boolean relPathSelectionMade = relativePath != null && !relativePath.equals(""); + boolean relPathComplete = savePathInfoCheckBox == null || !savePathInfoCheckBox.getEnabled(); + if (!relPathComplete) + { + if (pathInfoChecked) + { + relPathComplete = relPathSelectionMade; + } + else relPathComplete = true; + } + return super.isPageComplete() && relPathComplete; + } + + protected void setSaveFullPathInfo() + { + saveFullPathInfo = savePathInfoCheckBox != null && + savePathInfoCheckBox.getEnabled() && + savePathInfoCheckBox.getSelection(); + } + + public String getRelativePath() + { + return relativePath; + } + + public boolean getSaveFullPathInfo() + { + return saveFullPathInfo; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineDialog.java new file mode 100644 index 00000000000..e420eb7cd51 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineDialog.java @@ -0,0 +1,142 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +/** + * A dialog to select or enter archive files. + */ +public class CombineDialog extends SystemSelectRemoteFileOrFolderDialog { + + protected CombineForm form; + protected boolean prePop = false; + + /** + * Constructor. + * @param shell the parent shell. + */ + public CombineDialog(Shell shell) + { + super(shell, false); + setHelp(SystemPlugin.HELPPREFIX + "cmbd0000"); + } + + /** + * Constructor when you want to supply your own title. + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + */ + public CombineDialog(Shell shell, String title) + { + super(shell, title, false); + setHelp(SystemPlugin.HELPPREFIX + "cmbd0000"); + } + + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param prePopSelection Whether or not the destination name + * and type will be prepopulated with the selection, or given + * a generic name and type. + */ + public CombineDialog(Shell shell, String title, boolean prePopSelection) + { + super(shell, title, false); + prePop = prePopSelection; + if (form != null) form.setPrePopSelection(prePop); + setHelp(SystemPlugin.HELPPREFIX + "cmbd0000"); + } + + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param prePopSelection Whether or not the destination name + * and type will be prepopulated with the selection, or given + * a generic name and type. + * @param relativePaths The relative paths to be inserted as choices + * in the relative path combo box. Null if you wish to disable this feature. + */ + public CombineDialog(Shell shell, String title, boolean prePopSelection, String[] relativePaths) + { + super(shell, title, false); + prePop = prePopSelection; + if (form != null) form.setPrePopSelection(prePop); + setHelp(SystemPlugin.HELPPREFIX + "cmbd0000"); + } + + + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + form = new CombineForm(getMessageLine(), this, fileMode, prePop); + super.getForm(fileMode); + return form; + } + + public Object getOutputObject() + { + String fileName = form.getFileName(); + + IRemoteFile file = (IRemoteFile) super.getOutputObject(); + + // if a file was selected, get reference to its parent + if (file.isFile()) { + file = file.getParentRemoteFile(); + } + + try + { + // return a remote file that is the child of the parent folder + return file.getParentRemoteFileSubSystem().getRemoteFileObject(file, fileName); + } + catch (Exception e) + { + return null; + } + } + + public void setShowLocationPrompt(boolean show) + { + form.setShowLocationPrompt(show); + } + + public void setLocationPrompt(String prompt) + { + form.setLocationPrompt(prompt); + } + + public void setNameAndTypePrompt(String prompt) + { + form.setNameAndTypePrompt(prompt); + } + + /** + * Sets the extensions to disallow. + * @param extensions the archive extensions that will not be allowed. + */ + public void setDisallowedArchiveExtensions(String[] extensions) { + form.setDisallowedArchiveExtensions(extensions); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineForm.java new file mode 100644 index 00000000000..7cabcb8f620 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/CombineForm.java @@ -0,0 +1,451 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import java.util.ArrayList; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.SystemFilterSimple; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.validators.ValidatorArchiveName; +import org.eclipse.rse.ui.validators.ValidatorFileName; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + +/** + * A dialog to select or enter archive files. + */ +public class CombineForm extends SystemSelectRemoteFileOrFolderForm +{ + + protected Text fileNameText; + protected Combo fileTypeCombo; + protected Label nameAndTypeLabel; + protected String fileName, fileType, initialFileName; + protected ValidatorFileName validator; + protected ValidatorArchiveName arcvalidator; + protected boolean prePop; + protected String nameAndTypePrompt = ""; + protected String[] disallowedExtensions; + + /** + * Constructor for ExtractToForm + */ + public CombineForm(ISystemMessageLine msgLine, Object caller, boolean fileMode) + { + super(msgLine, caller, fileMode); + validator = new ValidatorFileName(); + arcvalidator = new ValidatorArchiveName(); + prePop = false; + } + + public CombineForm(ISystemMessageLine msgLine, Object caller, boolean fileMode, boolean prePopSelection) + { + super(msgLine, caller, fileMode); + + validator = new ValidatorFileName(); + arcvalidator = new ValidatorArchiveName(); + prePop = prePopSelection; + } + + /** + * In this method, we populate the given SWT container with widgets and return the container + * to the caller. + * @param parent The parent composite + */ + public Control createContents(Shell shell, Composite parent) + { + Control control = super.createContents(shell, parent); + + Composite composite = SystemWidgetHelpers.createComposite(parent, 1); + + nameAndTypeLabel = SystemWidgetHelpers.createLabel(composite, nameAndTypePrompt); + Composite subcomp1 = SystemWidgetHelpers.createComposite(composite, 2); + fileNameText = SystemWidgetHelpers.createLabeledTextField( + subcomp1, null, FileResources.RESID_COMBINE_NAME_LABEL, FileResources.RESID_COMBINE_NAME_TOOLTIP); + fileTypeCombo = SystemWidgetHelpers.createLabeledReadonlyCombo(subcomp1, null, FileResources.RESID_COMBINE_TYPE_LABEL, FileResources.RESID_COMBINE_TYPE_TOOLTIP); + + String[] allowedExtensions = getAllowedArchiveExtensions(); + + if (allowedExtensions != null && allowedExtensions.length != 0) { + fileTypeCombo.setItems(allowedExtensions); + fileTypeCombo.select(0); + fileType = fileTypeCombo.getText(); + } + + fileNameText.addModifyListener(new ModifyListener() { + + public void modifyText(ModifyEvent e) { + fileName = fileNameText.getText(); + setPageComplete(); + if (fileName.indexOf(".") != -1) + { + SystemMessage isValidMsg = arcvalidator.validate(fileName); + if (isValidMsg == null) + { + int i = fileName.lastIndexOf("."); + fileType = fileName.substring(i+1); + fileTypeCombo.setText(fileType); + } + } + } + }); + + fileTypeCombo.addModifyListener(new ModifyListener() { + + public void modifyText(ModifyEvent e) { + fileType = fileTypeCombo.getText(); + setPageComplete(); + } + }); + + if (fileName != null) + { + fileNameText.setText(fileName); + } + + return control; + } + + protected String[] getAllowedArchiveExtensions() { + + String[] allExtensions = ArchiveHandlerManager.getInstance().getRegisteredExtensions(); + + ArrayList list = new ArrayList(); + + for (int i = 0; i < allExtensions.length; i++) { + + String extension = allExtensions[i]; + + boolean keep = true; + + for (int j = 0; j < disallowedExtensions.length; j++) { + + if (disallowedExtensions[j].toLowerCase().equals(extension)) { + + keep = false; + break; + } + } + + if (keep) { + list.add(extension); + } + } + + String[] allowedExtensions = new String[list.size()]; + + for (int i = 0; i < list.size(); i++) { + allowedExtensions[i] = (String)(list.get(i)); + } + + return allowedExtensions; + } + + public String[] getDisallowedArchiveExtensions() { + return disallowedExtensions; + } + + /** + * Sets the extensions to disallow. + * @param extensions the archive extensions that will not be allowed. + */ + public void setDisallowedArchiveExtensions(String[] extensions) { + this.disallowedExtensions = extensions; + } + + /** + * Completes processing of the dialog. + * Intercept of parent method. + * + * @return true if no errors + */ + public boolean verify() + { + // This method added by Phil to issue warning msg for existing member + boolean ok = super.verify(); + + if (ok) + { + IRemoteFile file = (IRemoteFile)getSelectedObject(); + IRemoteFile saveasFile = null; + + try + { + saveasFile = file.getParentRemoteFileSubSystem().getRemoteFileObject(file, getFileName()); + } + catch (Exception e) + { + } + } + return ok; + } + + public boolean isPageComplete() + { + String nameToCheck = null; + + if (fileName == null) { + nameToCheck = ""; + } + else { + nameToCheck = fileName; + } + + SystemMessage errMsg = validator.validate(nameToCheck); + + if (errMsg != null) + { + setErrorMessage(errMsg); + return false; + } + else + { + clearErrorMessage(); + } + + return fileTypeCombo != null && + fileTypeCombo.getText().length() > 0 && + fileNameText != null && + fileNameText.getText().length() > 0 && + super.isPageComplete(); + } + + public String getFileName() { + + if (fileName.endsWith("." + fileType)) { + return fileName; + } + else { + return fileName + "." + fileType; + } + } + + /** + * Returns the implementation of ISystemViewElement for the given + * object. Returns null if the adapter is not defined or the + * object is not adaptable. + */ + protected ISystemViewElementAdapter getAdapter(Object o) + { + return SystemAdapterHelpers.getAdapter(o); + } + + /** + * Returns the implementation of ISystemRemoteElement for the given + * object. Returns null if this object does not adaptable to this. + */ + protected ISystemRemoteElementAdapter getRemoteAdapter(Object o) + { + return SystemAdapterHelpers.getRemoteAdapter(o); + } + + /** + * User selected something in the tree. + * This is an intercept of the parent's method so we can process a member selection, and + * copy the selected member's name to the entry field. + */ + public void selectionChanged(SelectionChangedEvent e) + { + super.selectionChanged(e); + clearErrorMessage(); + ISelection selection = e.getSelection(); + Object selectedObject = getFirstSelection(e.getSelection()); + if (selectedObject != null && selectedObject instanceof IRemoteFile) + { + IRemoteFile remoteFile = (IRemoteFile)selectedObject; + + ISystemRemoteElementAdapter remoteAdapter = getRemoteAdapter(selectedObject); + if ((remoteAdapter != null)) + { + Object parentFile = remoteFile; + + remoteAdapter = getRemoteAdapter(parentFile); + if (remoteAdapter != null) + { + String fullPath = remoteAdapter.getAbsoluteName(parentFile); + setNameText(fullPath); + outputObjects = new Object[] {parentFile}; + setPageComplete(); + SystemMessage selectionMsg = null; + if (selectionValidator != null) + selectionMsg = selectionValidator.isValid(outputConnection, getSelections(selection), getRemoteAdapters(selection)); + + if (selectionMsg != null) + { + valid = false; + setErrorMessage(selectionMsg); + setPageComplete(); + } + } + } + } + } + + public void setPreSelection(IRemoteFile selection) + { + if (selection.isDirectory()) + { + super.setPreSelection(selection); + } + else if (selection.isFile()) + { + IRemoteFile parentFile = selection.getParentRemoteFile(); + + if (parentFile.isDirectory()) + { + super.setPreSelection(parentFile); + } + } + if (prePop) + { + String file = selection.getName(); + int i = file.lastIndexOf("."); + if (i == -1) + { + fileName = file; + fileType = ""; + } + else + { + fileName = file.substring(0,i); + fileType = selection.getExtension(); + } + } + else + { + fileName = ""; + } + } + + /** + * Set the root folder from which to start listing folders or files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + setDefaultConnection(connection); + setShowNewConnectionPrompt(true); + setAutoExpandDepth(0); + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + IRemoteFileSubSystem ss = RemoteFileUtility.getFileSubSystem(connection); + IRemoteFileSubSystemConfiguration ssf = ss.getParentRemoteFileSubSystemFactory(); + RemoteFileFilterString rffs = new RemoteFileFilterString(ssf); + rffs.setShowFiles(fileMode); // no files if in folders mode + rffs.setShowSubDirs(!fileMode || !filesOnlyMode); // yes folders, always, for now + if (fileTypes != null) + rffs.setFile(fileTypes); + + // set the default filters we will show when the user expands a connection... + String filterName = null; + SystemFilterSimple filter = null; + int filterCount = showRootFilter ? 2 : 1; + if (preSelectRoot) + filterCount = 1; + ISystemFilter[] filters = new ISystemFilter[filterCount]; + int idx = 0; + + // filter one: "Root files"/"Root folders" or "Drives" + if (showRootFilter) + { + if (ssf.isUnixStyle()) + { + if (!preSelectRoot) + { + // "Root files" or "Folders" + filterName = fileMode ? SystemFileResources.RESID_FILTER_ROOTFILES : SystemFileResources.RESID_FILTER_ROOTFOLDERS; + //rffs.setPath(ssf.getSeparator()); // defect 43492. Show the root not the contents of the root + } + else + { + filterName = SystemFileResources.RESID_FILTER_ROOTS; // "Roots" + } + } + else + filterName = fileMode ? SystemFileResources.RESID_FILTER_DRIVES : SystemFileResources.RESID_FILTER_DRIVES; + filter = new SystemFilterSimple(filterName); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx++] = filter; + //System.out.println("FILTER 1: " + filter.getFilterString()); + if (preSelectRoot) + { + preSelectFilter = filter; + preSelectFilterChild = folderAbsolutePath; + //SystemPlugin.logInfo("in setRootFolder. Given: " + folderAbsolutePath); + } + } + + if (!preSelectRoot) + { + + // filter two: "\folder1\folder2" + rffs.setPath(folderAbsolutePath); + + filter = new SystemFilterSimple(rffs.toStringNoSwitches()); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx] = filter; + + preSelectFilter = filter; + //SystemPlugin.logInfo("FILTER 2: " + filter.getFilterString()); + } + inputProvider.setFilterString(null); // undo what ctor did + inputProvider.setQuickFilters(filters); + } + + public void setPrePopSelection(boolean prePopSelection) + { + prePop = prePopSelection; + } + + public void setNameAndTypePrompt(String prompt) + { + nameAndTypePrompt = prompt; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/DefaultMountPathMapper.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/DefaultMountPathMapper.java new file mode 100644 index 00000000000..c3ded4f2117 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/DefaultMountPathMapper.java @@ -0,0 +1,44 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +public class DefaultMountPathMapper implements ISystemMountPathMapper +{ + + public boolean handlesMappingFor(String hostname, String remotePath) + { + return false; + } + + public String getActualHostFor(String hostname, String remotePath) + { + return hostname; + } + + public String getWorkspaceMappingFor(String hostname, String remotePath) + { + return remotePath; + } + + /** + * Returns the remote path. + */ + public String getMountedMappingFor(String hostname, String remotePath) + { + return remotePath; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToDialog.java new file mode 100644 index 00000000000..ab8c018ecfa --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToDialog.java @@ -0,0 +1,73 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +public class ExtractToDialog extends SystemSelectRemoteFileOrFolderDialog { + + /** + * Constructor + * + * @param shell The shell to hang the dialog off of + * @param fileMode True if selecting files, false if selecting folders + * + */ + + private ExtractToForm form; + + + public ExtractToDialog(Shell shell) + { + super(shell, false); + setHelp(SystemPlugin.HELPPREFIX + "exdi0000"); + } + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param fileMode True if selecting files, false if selecting folders + */ + public ExtractToDialog(Shell shell, String title) + { + super(shell, title, false); + setHelp(SystemPlugin.HELPPREFIX + "exdi0000"); + } + + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + form = new ExtractToForm(getMessageLine(), this, fileMode); + super.getForm(fileMode); + return form; + } + + public Object getOutputObject() + { + IRemoteFile file = (IRemoteFile) super.getOutputObject(); + if (file.exists()) + { + return file; + } + return null; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToForm.java new file mode 100644 index 00000000000..53d8d70d884 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ExtractToForm.java @@ -0,0 +1,328 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.SystemFilterSimple; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.validators.ValidatorFolderName; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; + + +/** + * @author mjberger + * + * To change the template for this generated type comment go to + * Window>Preferences>Java>Code Generation>Code and Comments + */ +public class ExtractToForm extends SystemSelectRemoteFileOrFolderForm +{ + + private String fileName; + private ValidatorFolderName validator; + + /** + * Constructor for ExtractToForm + */ + public ExtractToForm(ISystemMessageLine msgLine, Object caller, boolean fileMode) + { + super(msgLine, caller, fileMode); + + validator = new ValidatorFolderName(); + } + + /** + * In this method, we populate the given SWT container with widgets and return the container + * to the caller. + * @param parent The parent composite + */ + public Control createContents(Shell shell, Composite parent) + { + Control control = super.createContents(shell, parent); + +// Composite composite = SystemWidgetHelpers.createComposite(parent, 2); +// SystemWidgetHelpers.createLabel(composite, SystemResources.RESID_NEWFILE_NAME_ROOT_LABEL); +// fileNameText = SystemWidgetHelpers.createTextField(composite, null); + +// fileNameText = SystemWidgetHelpers.createLabeledTextField( +// composite, null, SystemPlugin.getResourceBundle(), ISystemConstants.RESID_EXTRACTTO_NAME_ROOT); + + +// fileNameText.addModifyListener(new ModifyListener() { +// public void modifyText(ModifyEvent e) { +// fileName = fileNameText.getText(); +// setPageComplete(); +// } +// }); + +// if (fileName != null) +// { +// fileNameText.setText(fileName); +// } + + return control; + } + + /** + * Completes processing of the dialog. + * Intercept of parent method. + * + * @return true if no errors + */ + public boolean verify() + { + // This method added by Phil to issue warning msg for existing member + //System.out.println("Inside verify"); + boolean ok = super.verify(); +/* if (ok) + { + IRemoteFile file = (IRemoteFile) getSelectedObject(); + IRemoteFile saveasFile = null; + try + { + saveasFile = file.getParentRemoteFileSubSystem().getRemoteFileObject(file, fileName); + } + catch (Exception e) + { + } + + //System.out.println("...saveasMbr null? "+ (saveasMbr==null)); + if (saveasFile != null && saveasFile.exists()) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_UPLOAD_FILE_EXISTS); + msg.makeSubstitution(fileName); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + ok = dlg.openQuestionNoException(); + } + + }*/ + return ok; + } + + public boolean isPageComplete() + { + String errMsg = null; //validator.isValid(fileName); + + if (errMsg != null) + { + setErrorMessage(errMsg); + return false; + } + else + { + if (valid) clearErrorMessage(); + return valid; + } + + } + + public String getFileName() + { + return fileName; + } + + /** + * Returns the implementation of ISystemViewElement for the given + * object. Returns null if the adapter is not defined or the + * object is not adaptable. + */ + protected ISystemViewElementAdapter getAdapter(Object o) + { + return SystemAdapterHelpers.getAdapter(o); + } + + /** + * Returns the implementation of ISystemRemoteElement for the given + * object. Returns null if this object does not adaptable to this. + */ + protected ISystemRemoteElementAdapter getRemoteAdapter(Object o) + { + return SystemAdapterHelpers.getRemoteAdapter(o); + } + + /** + * User selected something in the tree. + * This is an intercept of the parent's method so we can process a member selection, and + * copy the selected member's name to the entry field. + */ + public void selectionChanged(SelectionChangedEvent e) + { + super.selectionChanged(e); + valid = true; + ISelection selection = e.getSelection(); + Object selectedObject = getFirstSelection(selection); + if (selectedObject != null && selectedObject instanceof IRemoteFile) + { + IRemoteFile remoteFile = (IRemoteFile)selectedObject; + fileName = remoteFile.getName(); + if (remoteFile.isRoot()) + { + if (fileName.endsWith("\\")) fileName = fileName.substring(0,2); + } + ISystemRemoteElementAdapter remoteAdapter = getRemoteAdapter(selectedObject); + if ((remoteAdapter != null)) + { + + Object parentFile = remoteFile; + + remoteAdapter = getRemoteAdapter(parentFile); + if (remoteAdapter != null) + { + String fullPath = remoteAdapter.getAbsoluteName(parentFile); + setNameText(fullPath); + outputObjects = new Object[] {parentFile}; + + SystemMessage selectionMsg = null; + + if (selectionValidator != null) + selectionMsg = selectionValidator.isValid(outputConnection, getSelections(selection), getRemoteAdapters(selection)); + + if (selectionMsg != null) + { + valid = false; + setErrorMessage(selectionMsg); + } + setPageComplete(); + } + } + } + else if (selectedObject != null) + { + valid = false; + setPageComplete(); + } + } + + public void setPreSelection(IRemoteFile selection) + { + if (selection.isDirectory()) + { + super.setPreSelection(selection); + } + else if (selection.isFile()) + { + IRemoteFile parentFile = selection.getParentRemoteFile(); + + if (parentFile.isDirectory()) + { + super.setPreSelection(parentFile); + } + + fileName = parentFile.getName(); + } + } + + /** + * Set the root folder from which to start listing folders or files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + setDefaultConnection(connection); + setShowNewConnectionPrompt(true); + setAutoExpandDepth(0); + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + IRemoteFileSubSystem ss = RemoteFileUtility.getFileSubSystem(connection); + IRemoteFileSubSystemConfiguration ssf = ss.getParentRemoteFileSubSystemFactory(); + RemoteFileFilterString rffs = new RemoteFileFilterString(ssf); + rffs.setShowFiles(fileMode); // no files if in folders mode + rffs.setShowSubDirs(!fileMode || !filesOnlyMode); // yes folders, always, for now + if (fileTypes != null) + rffs.setFile(fileTypes); + + // set the default filters we will show when the user expands a connection... + String filterName = null; + SystemFilterSimple filter = null; + int filterCount = showRootFilter ? 2 : 1; + if (preSelectRoot) + filterCount = 1; + ISystemFilter[] filters = new ISystemFilter[filterCount]; + int idx = 0; + + // filter one: "Root files"/"Root folders" or "Drives" + if (showRootFilter) + { + if (ssf.isUnixStyle()) + { + if (!preSelectRoot) + { + // "Root files" or "Folders" + filterName = fileMode ? SystemFileResources.RESID_FILTER_ROOTFILES : SystemFileResources.RESID_FILTER_ROOTFOLDERS; + //rffs.setPath(ssf.getSeparator()); // defect 43492. Show the root not the contents of the root + } + else + { + filterName = SystemFileResources.RESID_FILTER_ROOTS; // "Roots" + } + } + else + filterName = fileMode ? SystemFileResources.RESID_FILTER_DRIVES : SystemFileResources.RESID_FILTER_DRIVES; + filter = new SystemFilterSimple(filterName); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx++] = filter; + //System.out.println("FILTER 1: " + filter.getFilterString()); + if (preSelectRoot) + { + preSelectFilter = filter; + preSelectFilterChild = folderAbsolutePath; + //SystemPlugin.logInfo("in setRootFolder. Given: " + folderAbsolutePath); + } + } + + if (!preSelectRoot) + { + + // filter two: "\folder1\folder2" + rffs.setPath(folderAbsolutePath); + + filter = new SystemFilterSimple(rffs.toStringNoSwitches()); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx] = filter; + + preSelectFilter = filter; + //SystemPlugin.logInfo("FILTER 2: " + filter.getFilterString()); + } + inputProvider.setFilterString(null); // undo what ctor did + inputProvider.setQuickFilters(filters); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionDialog.java new file mode 100644 index 00000000000..5a74ddf2bae --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionDialog.java @@ -0,0 +1,86 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.swt.widgets.Shell; + + +/** + * Dialog used to select a file based on a dialog similar to the SaveAs + */ +public class FileSelectionDialog + extends SystemSelectRemoteFileOrFolderDialog + implements ISaveAsDialog +{ + + public static final String Copyright = + "(C) Copyright IBM Corp. 2003 All Rights Reserved."; + + /** + * Constructor + * + * @param shell The shell to hang the dialog off of + * @param fileMode True if selecting files, false if selecting folders + * + */ + + private FileSelectionForm form; + + protected FileSelectionDialog(Shell shell) + { + super(shell, false); + } + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param fileMode True if selecting files, false if selecting folders + */ + protected FileSelectionDialog(Shell shell, String title) + { + super(shell, title, true); + } + + public static FileSelectionDialog getFileSelectionDialog( + Shell shell, + String title) + { + return new FileSelectionDialog(shell, title); + } + + public static FileSelectionDialog getFileSelectionDialog(Shell shell) + { + return new FileSelectionDialog(shell); + } + + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + form = new FileSelectionForm(getMessageLine(), this, fileMode); + super.getForm(fileMode); + return form; + } + /** + * Return file name specified + * @return File name + */ + public String getFileName() + { + return form.getFileName(); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionForm.java new file mode 100644 index 00000000000..6cb617bb6c3 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/FileSelectionForm.java @@ -0,0 +1,74 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import org.eclipse.rse.ui.messages.ISystemMessageLine; + +/** + * Form class for selecting a file based on the SaveAS + */ +public class FileSelectionForm extends SaveAsForm +{ + public static final String Copyright = + "(C) Copyright IBM Corp. 2003 All Rights Reserved."; + + /** + * Constructor for FileSelectionForm + */ + public FileSelectionForm( + ISystemMessageLine msgLine, + Object caller, + boolean fileMode) + { + super(msgLine, caller, fileMode); + } + + /** + * Completes processing of the dialog. + * Intercept of parent method. + * + * @return true if no errors + */ + public boolean verify() + { + + return true; + } + + public boolean isPageComplete() + { + //String errMsg = validator.isValid(fileName); + + //if (errMsg != null) + //{ + // setErrorMessage(errMsg); + // return false; + //} + //else + //{ + // clearErrorMessage(); + //} + + return fileNameText != null + && fileNameText.getText().length() > 0; + //&& super.isPageComplete(); + } + public String getFileName() + { + return fileName; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISaveAsDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISaveAsDialog.java new file mode 100644 index 00000000000..6e2d36d880f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISaveAsDialog.java @@ -0,0 +1,33 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; + +public interface ISaveAsDialog { + + + + public Object getOutputObject(); + + public void setMultipleSelectionMode(boolean mode); + + public int open(); + + public void setPreSelection(IRemoteFile selection); + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemCachedRemoteResource.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemCachedRemoteResource.java new file mode 100644 index 00000000000..fc3e2b8f932 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemCachedRemoteResource.java @@ -0,0 +1,86 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * This is the cached remote resource. + */ +public interface ISystemCachedRemoteResource { + + + + /** + * Constant indicating no changes. + */ + public static final int CHANGES_NONE = 0; + + /** + * Constant indicating local copy has changed, but not server copy. + */ + public static final int CHANGES_OUTGOING = 1; + + /** + * Constant indicating server copy has changed, but not local copy. + */ + public static final int CHANGES_INCOMING = 2; + + /** + * Constant indicating both local and server copy have changed. + */ + public static final int CHANGES_CONFLICT = 3; + + /** + * Get the last modified time on the server. Calling this when connected will + * query it from the server, but calling it in disconnected mode will + * query it from disk. + * @return the last modified time on the server + */ + public long lastRemoteModified(); + + /** + * Get the last modified time on the client. + * @return the last modified time on the client + */ + public long lastLocalModified(); + + /** + * Get the last time of download or synchronization. + * @return the time of the last download or synchronization + */ + public long lastSuccessfulSynch(); + + /** + * Returns whether the local and remote copies are synchronized. + * @return true if the local and remote copies are synchronized, + * false otherwise. + */ + public boolean isSynchronized(); + + /** + * Get the state of the cache. + * @return CHANGES_NONE if both local and remote copies are in sync, + * CHANGES_OUTGOING if the local copy has changed but not the server copy, + * CHANGES_INCOMING if the server copy has changed but not the local copy, + * CHANGES_CONFLICT if both the local copy and server copy have changed. + */ + public int getState(); + + /** + * Dispose of the cache. + */ + public void dispose(); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemMountPathMapper.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemMountPathMapper.java new file mode 100644 index 00000000000..99c09e060d4 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemMountPathMapper.java @@ -0,0 +1,68 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * This interface is used to provide a common way of mapping mounted resources to the temp files project. + * Since local mounts can change or be removed (i.e. disconnected) this provides a way for a vender to + * remap a particular resource if the vender software is able to determine the new mount location. + * Implementors of this interface should register their mappers via the mountPathMapper extension point. + */ +public interface ISystemMountPathMapper +{ + + /** + * Indicates whether this mapper handles remapping of the specified resource + * @param hostname the remote host + * @param remotePath the remote path as seen by the local file subsystem + * @return whether this mapper handles remapping of the specified remote resource + */ + public boolean handlesMappingFor(String hostname, String remotePath); + + /** + * Returns the qualified workspace path for a replica of this mounted file. Since the local + * system path is not unique for mounted files, this allows a vender to make sure it is unique. + * The workspace mapping should always be the remote path on the originating host. + * + * @param hostname the remote host + * @param remotePath the remote path as seen by the local file subsystem + * @return the corresponding workspace replica mapping + */ + public String getWorkspaceMappingFor(String hostname, String remotePath); + + + /** + * Returns the corresponding hostname for the specified path on the specified host. If a file is mounted + * via local, then the actual host containing the file will not be local. If there is no mapping, then + * the hostname will be the same as the argument. + * @param hostname the system host + * @param remotePath the path on the system host + * @return the actual host that contains the specified remote path + */ + public String getActualHostFor(String hostname, String remotePath); + + /** + * Returns the local system path that can be used for copying the replica back to remote. When null + * is returned RSE the file is treated as no longer available and thus remote uploads do not occur. Venders + * who would like to disable uploads for some period can implement this to return null during that period. + * + * @param hostname the remote host + * @param remotePath the remote path as seen by the local file subsystem + * @return the local system path that represents the mounted file + */ + public String getMountedMappingFor(String hostname, String remotePath); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteCoreConstants.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteCoreConstants.java new file mode 100644 index 00000000000..515e61fb73f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteCoreConstants.java @@ -0,0 +1,27 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * Interface that contains all constants needed for remote resource management. + */ +public interface ISystemRemoteCoreConstants { + + + + public static final int M_MARKERS_DIRTY = 0x1000; +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditConstants.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditConstants.java new file mode 100644 index 00000000000..e308ba15497 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditConstants.java @@ -0,0 +1,55 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +public interface ISystemRemoteEditConstants { + + + + // Constants for remote editing + public static final String REMOTE_FILE_OBJECT_KEY = "remote_file_object_key"; + + public static final String REMOTE_FILE_SUBSYSTEM_KEY = "remote_file_subsystem_key"; + public static final String REMOTE_FILE_PATH_KEY = "remote_file_path_key"; + + public static final String REMOTE_FILE_MODIFIED_STAMP = "remote_file_modified_stamp"; + public static final String REMOTE_FILE_BINARY_TRANSFER = "remote_file_binary_transfer"; + public static final String TEMP_FILE_DIRTY = "temp_file_dirty"; + public static final String TEMP_FILE_READONLY = "temp_file_readonly"; + + public static final String DOWNLOAD_FILE_MODIFIED_STAMP = "download_file_modified_stamp"; + // for mounted mappings + public static final String REMOTE_FILE_MOUNTED = "remote_file_mounted"; + public static final String RESOLVED_MOUNTED_REMOTE_FILE_PATH_KEY = "resolved_mounted_remote_file_path_key"; + public static final String RESOLVED_MOUNTED_REMOTE_FILE_HOST_KEY = "resolved_mounted_remote_file_host_key"; + + + // Constants related to how the editor will set the document content + public static final String LOAD_TYPE_KEY = "load_type_key"; + public static final String LOAD_TYPE_USE_STRING = "load_type_use_string"; + + + // Universal remote editing profile + public static final String DEFAULT_EDITOR_PROFILE = "default"; + public static final String UNIVERSAL_EDITOR_PROFILE = "universal"; + public static final String UNIVERSAL_LOCAL_EDITOR_PROFILE = "universallocal"; + + + // Local relative directory for various editor actions + public static final String EDITOR_COMPARE_LOCATION = "/compare/"; + public static final String EDITOR_GET_FILE_LOCATION = "/get/"; +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResource.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResource.java new file mode 100644 index 00000000000..19da1268c01 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResource.java @@ -0,0 +1,36 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.core.resources.IFile; + +/** + * This interface defines some common functionality required from all remote + * resources for edit, irrespective of whether the remote system is an + * OS/400, Windows, Linux or Unix operating system. + */ +public interface ISystemRemoteEditResource extends ISystemRemoteResource { + + + + /** + * Returns the local resource. The local resource does not exist if the method + * returns null, or if calling exists() on the returned resource returs false. + * @return the local resource. + */ + public IFile getLocalResource(); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResourceManager.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResourceManager.java new file mode 100644 index 00000000000..18a8787bd6b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteEditResourceManager.java @@ -0,0 +1,56 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * This manager class manages remote resources. + */ +public interface ISystemRemoteEditResourceManager extends ISystemRemoteManager { + + + + /** + * Store a remote edit object with the given remote path as the key. + * The idea is that each unique remote object can have an associated + * edit object associated with it, and this object will take care + * of remote editing of that object. Using the remote path as a key ensures + * that a resource with a unique path will have a unique remote object. + * @param the remote path to use as a key + * @param the editbable object + * @return the previously stored edit object, or null if none + */ + public Object putEditObject(ISystemRemotePath key, Object editObj); + + /** + * Get a remote edit object given the remote path as a key. + * @param the remote path as a key + * @return the stored edit object + */ + public Object getEditObject(ISystemRemotePath key); + + /** + * Save the edit object information to disk. + * Clients must not call this method. + */ + public void save(); + + /** + * Restore the edit object information from disk. + * Clients must not call this method. + */ + public void restore(); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteManager.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteManager.java new file mode 100644 index 00000000000..d36a740a773 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteManager.java @@ -0,0 +1,42 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * This interface should be implemented by all remote resource related + * managers + */ +public interface ISystemRemoteManager { + + + + /** + * This method is called during plugin startup. + * @param a progress monitor for long running operations, or null + * if none is desired. + */ + public void startup(IProgressMonitor monitor); + + /** + * This method is called during plugin shutdown. + * @param a progress monitor for long running operations, or null + * if none is desired. + */ + public void shutdown(IProgressMonitor monitor); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarker.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarker.java new file mode 100644 index 00000000000..83bdaeb6b49 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarker.java @@ -0,0 +1,220 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.Map; + + +/** + * This interface defines a remote marker. It can be used to tag information + * to a any remote resource. + * Clients must not implement this interface. + */ +public interface ISystemRemoteMarker { + + + + /** + * Remote markers extension point id. + */ + public static final String EXTENSION_POINT_ID = "remoteMarkers"; + + /** + * Deletes this marker from its associated resource. This method has no + * effect if this marker does not exist. + */ + public void delete(); + + /** + * Tests this marker for equality with the given object. + * Two markers are equal if and only if their id and resource info are both equal. + * @param object the other object + * @return true if objects are equal, false otherwise + */ + public boolean equals(Object object); + + /** + * Returns whether this marker exists. A marker + * exists if its resource info exists and has a marker with the marker's id. + * + * @return true if this marker exists, otherwise + * false + */ + public boolean exists(); + + /** + * Returns the attribute with the given name. The result is an instance of one + * of the following classes: String, Integer, + * or Boolean. + * Returns null if the attribute is undefined. + * + * @param attributeName the name of the attribute + * @return the value, or null if the attribute is undefined. + */ + public Object getAttribute(String attributeName); + + /** + * Returns the integer-valued attribute with the given name. + * Returns the given default value if the attribute is undefined. + * or the marker does not exist or is not an integer value. + * + * @param attributeName the name of the attribute + * @param defaultValue the value to use if no value is found + * @return the value or the default value if no value was found. + */ + public int getAttribute(String attributeName, int defaultValue); + + /** + * Returns the string-valued attribute with the given name. + * Returns the given default value if the attribute is undefined + * or the marker does not exist or is not a string value. + * + * @param attributeName the name of the attribute + * @param defaultValue the value to use if no value is found + * @return the value or the default value if no value was found. + */ + public String getAttribute(String attributeName, String defaultValue); + + /** + * Returns the boolean-valued attribute with the given name. + * Returns the given default value if the attribute is undefined + * or the marker does not exist or is not a boolean value. + * + * @param attributeName the name of the attribute + * @param defaultValue the value to use if no value is found + * @return the value or the default value if no value was found. + */ + public boolean getAttribute(String attributeName, boolean defaultValue); + + /** + * Returns a map with all the attributes for the marker. + * If the marker has no attributes then null is returned. + * + * @return a map of attribute keys and values (key type : String + * value type : String, Integer, or + * Boolean) or null. + */ + + public Map getAttributes(); + + /** + * Returns the attributes with the given names. The result is an an array + * whose elements correspond to the elements of the given attribute name + * array. Each element is null or an instance of one + * of the following classes: String, Integer, + * or Boolean. + * + * @param attributeNames the names of the attributes + * @return the values of the given attributes. + */ + public Object[] getAttributes(String[] attributeNames); + + /** + * Returns the time at which this marker was created. + * + * @return the difference, measured in milliseconds, between the time at which + * this marker was created and midnight, January 1, 1970 UTC. + */ + public long getCreationTime(); + + /** + * Returns the id of the marker. The id of a marker is unique + * relative to the resource with which the marker is associated. + * Marker ids are not globally unique. + * + * @return the id of the marker + * @see ISystemRemoteResource#findMarker + */ + public long getId(); + + /** + * Returns the resource with which this marker is associated. + * + * @return the remote resource with which this marker is associated + */ + public ISystemRemoteResource getResource(); + + /** + * Returns the type of this marker. + * + * @return the type of this marker + */ + public String getType(); + + /** + * Returns whether the type of this marker is considered to be a subtype of + * the given marker type. + * + * @return boolean trueif the marker's type + * is the same as (or a subtype of) the given type. + */ + public boolean isSubtypeOf(String superType); + + /** + * Sets the integer-valued attribute with the given name. + * + * @param attributeName the name of the attribute + * @param value the value + */ + public void setAttribute(String attributeName, int value); + + /** + * Sets the attribute with the given name. The value must be null or + * an instance of one of the following classes: + * String, Integer, or Boolean. + * If the value is null, the attribute is considered to be undefined. + * + * @param attributeName the name of the attribute + * @param value the value, or null if the attribute is to be undefined + */ + public void setAttribute(String attributeName, Object value); + + /** + * Sets the boolean-valued attribute with the given name. + * + * @param attributeName the name of the attribute + * @param value the value + */ + public void setAttribute(String attributeName, boolean value); + + /** + * Sets the given attribute key-value pairs on this marker. + * The values must be null or an instance of + * one of the following classes: String, + * Integer, or Boolean. + * If a value is null, the new value of the + * attribute is considered to be undefined. + * + * @param attributeNames an array of attribute names + * @param values an array of attribute values + */ + public void setAttributes(String[] attributeNames, Object[] values); + + /** + * Sets the attributes for this marker to be the ones contained in the + * given table. The values must be an instance of one of the following classes: + * String, Integer, or Boolean. + * Attributes previously set on the marker but not included in the given map + * are considered to be removals. Setting the given map to be null + * is equivalent to removing all marker attributes. + * + * @param attributes a map of attribute names to attribute values + * (key type : String value type : String, + * Integer, or Boolean) or null + */ + public void setAttributes(Map attributes); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarkerSetElement.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarkerSetElement.java new file mode 100644 index 00000000000..f4e8177d123 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteMarkerSetElement.java @@ -0,0 +1,31 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * An interface for all marker set elements. + */ +public interface ISystemRemoteMarkerSetElement { + + + + /** + * Get the id. + * @return the id + */ + public long getId(); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemotePath.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemotePath.java new file mode 100644 index 00000000000..d9768e12067 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemotePath.java @@ -0,0 +1,56 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * This interface defines a remote path. It is not intended to be implemented by + * clients. + */ +public interface ISystemRemotePath { + + + + /** + * Get the profile name. + * @return the profile name + */ + public String getProfileName(); + + /** + * Get the connection name. + * @return the connection name + */ + public String getConnectionName(); + + /** + * Get the path of the resource on the server. + * @return the path of the resource on the server + */ + public String getPath(); + + /** + * Returns the complete string representation of the remote path. + * @return complete string representation of the remote path + */ + public String toString(); + + /** + * Returns whether this path equals the given object. + * This is system dependent. + */ + public boolean equals(Object obj); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteResource.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteResource.java new file mode 100644 index 00000000000..d4ffd3866dd --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemRemoteResource.java @@ -0,0 +1,176 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.core.runtime.QualifiedName; + +/** + * This interface defines some common functionality required from all remote + * resources, irrespective of whether the remote system is an OS/400, Windows, Linux + * or Unix operating system. In particular, it allows users to create markers on remote + * resources, and to create both session and persistent properties for them. A session + * property is one that is stored only during the current workbench session, while a + * persistent property is one that is kept between sessions. + * Clients must not implement this interface. + * + * @see org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile + */ +public interface ISystemRemoteResource { + + + + /** + * Creates and returns the marker of the specified type on this resource. + * @param the marker type + * @return the created marker + */ + public ISystemRemoteMarker createMarker(String type); + + /** + * Deletes all markers on this resource of the given type, and optionally deletes + * such markers from its children. Deletion of markers with subtypes is also possible. + * @param the marker type, or null to indicate all types. + * @param whether or not to consider the subtypes of the given type + */ + public void deleteMarkers(String type, boolean includeSubtypes); + + /** + * Returns the marker with the specified id on this resource, or null if there + * is no such marker. + * @param the id of the marker to find + * @return a marker if found, or null + */ + public ISystemRemoteMarker findMarker(long id); + + /** + * Returns all markers of the specified type on this resource, and + * optionally, on its children. Markers with subtypes of the given type + * can also be found optionally. Returns an empty array if there are + * no matching markers. + * @param the marker type, or null to indicate all types. + * @param whether or not to consider the subtypes of the given type + * @return an array of markers, or an empty array if no markers are found + */ + public ISystemRemoteMarker[] findMarkers(String type, boolean includeSubtypes); + + /** + * Gets the marker with the given id. The marker is not guaranteed to exist. + * @param the marker id. + */ + public ISystemRemoteMarker getMarker(long id); + + /** + * Sets the value of the session property of this resource identified + * by the given key. If the supplied value is null, + * the session property is removed from this resource. + *

    + * Sessions properties are intended to be used as a caching mechanism + * by ISV plug-ins. They allow key-object associations to be stored with + * existing resources in the workspace. These key-value associations are + * maintained in memory (at all times), and the information is lost when a + * resource is deleted from the workspace, when the parent project + * is closed, or when the workspace is closed. + *

    + *

    + * The qualifier part of the property name must be the unique identifier + * of the declaring plug-in (e.g. "com.example.plugin"). + *

    + * + * @param key the qualified name of the property + * @param value the value of the session property, + * or null if the property is to be removed + * @see #getSessionProperty + */ + public void setSessionProperty(QualifiedName key, Object value); + + /** + * Returns the value of the session property of this resource identified + * by the given key, or null if this resource has no such property. + * + * @param key the qualified name of the property + * @return the string value of the session property, + * or null if this resource has no such property + * @see #setSessionProperty + */ + public Object getSessionProperty(QualifiedName key); + + /** + * Sets the value of the persistent property of this resource identified + * by the given key. If the supplied value is null, + * the persistent property is removed from this resource. The change + * is made immediately on disk. + *

    + * Persistent properties are intended to be used by plug-ins to store + * resource-specific information that should be persisted across platform sessions. + * The value of a persistent property is a string which should be + * short (i.e., under 2KB). Unlike session properties, persistent properties are + * stored on disk and maintained across workspace shutdown and restart. + *

    + *

    + * The qualifier part of the property name must be the unique identifier + * of the declaring plug-in (e.g. "com.example.plugin"). + *

    + * + * @param key the qualified name of the property + * @param value the string value of the property, + * or null if the property is to be removed + * @see #getPersistentProperty + */ + public void setPersistentProperty(QualifiedName key, String value); + + /** + * Returns the value of the persistent property of this resource identified + * by the given key, or null if this resource has no such property. + * + * @param key the qualified name of the property + * @return the string value of the property, + * or null if this resource has no such property + * @see #setPersistentProperty + */ + public String getPersistentProperty(QualifiedName key); + + /** + * Returns whether this resource exists on the remote server. + * @return true if the resource exists, false otherwise + */ + public boolean exists(); + + /** + * Returns whether a local copy of the file exists. + */ + public boolean isExistsLocally(); + + /** + * Returns the last modified time on the server. + * @param the last modified time on the server + */ + public boolean getRemoteLastModifiedTime(); + + /** + * Returns the last modified time on the client. + * @param the last modified time on the client. + */ + public boolean getLocalLastModifiedTime(); + + /** + * Returns whether the local copy, if there is one, is in sync with the + * remote copy. + * @param true if the local copy is in sync, false otherwise, or if the + * local copy does not exist. + */ + public boolean isSynchronized(); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditor.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditor.java new file mode 100644 index 00000000000..838cca7b1be --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditor.java @@ -0,0 +1,31 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.ui.IEditorInput; + +public interface ISystemTextEditor { + + + public void setReadOnly(boolean readOnly); + + public void updateDirtyIndicator(); + public void refresh(); + public void setInput(IEditorInput input); + public void gotoLine(int line); + public void selectText(int charStart, int charEnd); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditorConstants.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditorConstants.java new file mode 100644 index 00000000000..177bd4e3207 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/ISystemTextEditorConstants.java @@ -0,0 +1,50 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +public interface ISystemTextEditorConstants { + + + + // Editor id + public static final String SYSTEM_TEXT_EDITOR_ID = "org.eclipse.rse.editor"; + public static final String SYSTEM_TEXT_BROWSER_ID = "org.eclipse.rse.browser"; + + // Identifier for profile type + public static final String EDITOR_PROFILE_TYPE = "editorProfileType"; + + // key to identify file has sequence numbers + public static final String SEQUENCE_NUMBERS_KEY = "sequence_numbers_key"; + + // key to identify that a save limit should be set + public static final String MAX_LINE_LENGTH_KEY = "record_length_key"; + + // key to identify that a source encoding should be set + // this is used to emulate the remote encoding of the file + public static final String SOURCE_ENCODING_KEY = "source_encoding_key"; + + // key to identify host ccsid + public static final String CCSID_KEY = "ccsid_key"; + public static final String TEMP_CCSID_KEY = "temp_ccsid_key"; + + // key to identify logical or visual BIDI + public static final String BIDI_LOGICAL_KEY = "bidi_logical_key"; + + // key to identify the local encoding + // NOTE: DO NOT CHANGE THIS!! This is used by the IBM debugger. + public static final String LOCAL_ENCODING_KEY = "encoding"; +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/RemoteSourceLookupDirector.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/RemoteSourceLookupDirector.java new file mode 100644 index 00000000000..bc7a9dda282 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/RemoteSourceLookupDirector.java @@ -0,0 +1,40 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.debug.core.sourcelookup.AbstractSourceLookupDirector; +import org.eclipse.debug.core.sourcelookup.ISourceContainerType; + + +public class RemoteSourceLookupDirector extends AbstractSourceLookupDirector +{ + + /* (non-Javadoc) + * @see org.eclipse.debug.internal.core.sourcelookup.ISourceLookupDirector#initializeParticipants() + */ + public void initializeParticipants() { + //addParticipants(new ISourceLookupParticipant[] {new JavaSourceLookupParticipant()}); + } + /* (non-Javadoc) + * @see org.eclipse.debug.internal.core.sourcelookup.ISourceLookupDirector#supportsSourceContainerType(org.eclipse.debug.internal.core.sourcelookup.ISourceContainerType) + */ + public boolean supportsSourceContainerType(ISourceContainerType type) { + return true; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsDialog.java new file mode 100644 index 00000000000..28ba31f88c2 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsDialog.java @@ -0,0 +1,96 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.rse.files.ui.dialogs.SystemSelectRemoteFileOrFolderDialog; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.swt.widgets.Shell; + + +public class SaveAsDialog extends SystemSelectRemoteFileOrFolderDialog implements ISaveAsDialog { + + + + /** + * Constructor + * + * @param shell The shell to hang the dialog off of + * @param fileMode True if selecting files, false if selecting folders + * + */ + + private SaveAsForm form; + + + protected SaveAsDialog(Shell shell) + { + super(shell, false); + } + /** + * Constructor when you want to supply your own title. + * + * @param shell The shell to hang the dialog off of + * @param title The title to give the dialog + * @param fileMode True if selecting files, false if selecting folders + */ + protected SaveAsDialog(Shell shell, String title) + { + super(shell, title, true); + } + + public static ISaveAsDialog getSaveAsDialog(Shell shell, String title) + { + return new SaveAsDialog(shell, title); + } + + public static ISaveAsDialog getSaveAsDialog(Shell shell) + { + return new SaveAsDialog(shell); + } + + protected SystemSelectRemoteFileOrFolderForm getForm(boolean fileMode) + { + //System.out.println("INSIDE GETFORM"); + //if (form == null) + //{ + form = new SaveAsForm(getMessageLine(), this, fileMode); + super.getForm(fileMode); + + //} + return form; + } + + public Object getOutputObject() + { + IRemoteFile file = (IRemoteFile) super.getOutputObject(); + if (file.isFile()) + { + return file; + } + + try + { + return file.getParentRemoteFileSubSystem().getRemoteFileObject(file, form.getFileName()); + } + catch (Exception e) + { + return null; + } + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsForm.java new file mode 100644 index 00000000000..bdf5259e64f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SaveAsForm.java @@ -0,0 +1,238 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.validators.ValidatorFileName; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + + + +public class SaveAsForm extends SystemSelectRemoteFileOrFolderForm { + + + + + protected Text fileNameText; + protected String fileName, initialFileName; + protected ValidatorFileName validator; + + /** + * Constructor for SaveAsForm + */ + public SaveAsForm(ISystemMessageLine msgLine, Object caller, boolean fileMode) + { + super(msgLine, caller, fileMode); + + validator = new ValidatorFileName(); + } + + /** + * In this method, we populate the given SWT container with widgets and return the container + * to the caller. + * @param parent The parent composite + */ + public Control createContents(Shell shell, Composite parent) + { + Control control = super.createContents(shell, parent); + + Composite composite = SystemWidgetHelpers.createComposite(parent, 2); +// SystemWidgetHelpers.createLabel(composite, SystemResources.RESID_NEWFILE_NAME_ROOT_LABEL); +// fileNameText = SystemWidgetHelpers.createTextField(composite, null); + + fileNameText = SystemWidgetHelpers.createLabeledTextField( + composite, null, FileResources.RESID_NEWFILE_NAME_LABEL, FileResources.RESID_NEWFILE_NAME_TOOLTIP); + + + fileNameText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + fileName = fileNameText.getText(); + setPageComplete(); + } + }); + + if (fileName != null) + { + fileNameText.setText(fileName); + } + + return control; + } + + /** + * Completes processing of the dialog. + * Intercept of parent method. + * + * @return true if no errors + */ + public boolean verify() + { + // This method added by Phil to issue warning msg for existing member + //System.out.println("Inside verify"); + boolean ok = super.verify(); + if (ok) + { + IRemoteFile file = (IRemoteFile) getSelectedObject(); + IRemoteFile saveasFile = null; + try + { + saveasFile = file.getParentRemoteFileSubSystem().getRemoteFileObject(file, fileName); + } + catch (Exception e) + { + } + + //System.out.println("...saveasMbr null? "+ (saveasMbr==null)); + if (saveasFile != null && saveasFile.exists()) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_UPLOAD_FILE_EXISTS); + msg.makeSubstitution(fileName); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + ok = dlg.openQuestionNoException(); + } + } + return ok; + } + + public boolean isPageComplete() + { + SystemMessage errMsg = validator.validate(fileName); + + if (errMsg != null) + { + setErrorMessage(errMsg); + return false; + } + else + { + clearErrorMessage(); + } + + return fileNameText !=null && fileNameText.getText().length() > 0 && super.isPageComplete(); + } + + public String getFileName() + { + return fileName; + } + + public void setPreSelection(IRemoteFile selection) + { + if (selection.isDirectory()) + { + super.setPreSelection(selection); + } + else if (selection.isFile()) + { + IRemoteFile parentFile = selection.getParentRemoteFile(); + + if (parentFile.isDirectory()) + { + super.setPreSelection(parentFile); + } + + fileName = parentFile.getName(); + initialFileName=fileName; + } + } + + /** + * Returns the implementation of ISystemViewElement for the given + * object. Returns null if the adapter is not defined or the + * object is not adaptable. + */ + protected ISystemViewElementAdapter getAdapter(Object o) + { + return SystemAdapterHelpers.getAdapter(o); + } + + /** + * Returns the implementation of ISystemRemoteElement for the given + * object. Returns null if this object does not adaptable to this. + */ + protected ISystemRemoteElementAdapter getRemoteAdapter(Object o) + { + return SystemAdapterHelpers.getRemoteAdapter(o); + } + + /** + * User selected something in the tree. + * This is an intercept of the parent's method so we can process a member selection, and + * copy the selected member's name to the entry field. + */ + public void selectionChanged(SelectionChangedEvent e) + { + super.selectionChanged(e); + Object selectedObject = getFirstSelection(e.getSelection()); + if (selectedObject != null && selectedObject instanceof IRemoteFile) + { + IRemoteFile remoteFile = (IRemoteFile)selectedObject; + + ISystemRemoteElementAdapter remoteAdapter = getRemoteAdapter(selectedObject); + if ((remoteAdapter != null)) + { + + if (fileNameText != null) + { + // simulate the parent file being selected... + Object parentFile = tree.getSelectedParent(); + + if (remoteFile.isFile()) + { + fileName = remoteAdapter.getName(selectedObject); + fileNameText.setText(fileName); + } + else + { + fileName =initialFileName; + fileNameText.setText(fileName); + parentFile = remoteFile; + } + + + remoteAdapter = getRemoteAdapter(parentFile); + if (remoteAdapter != null) + { + String fullPath = remoteAdapter.getAbsoluteName(parentFile); + setNameText(fullPath); + outputObjects = new Object[] {parentFile}; + setPageComplete(); + } + } + } + } + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemEditableRemoteFile.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemEditableRemoteFile.java new file mode 100644 index 00000000000..e1fff1ca778 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemEditableRemoteFile.java @@ -0,0 +1,1622 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.actions.SystemDownloadConflictAction; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.SystemEncodingUtil; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IVirtualRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.swt.program.Program; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IPartListener; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.actions.WorkspaceModifyOperation; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + + +public class SystemEditableRemoteFile implements ISystemEditableRemoteObject, IPartListener, IResourceChangeListener, IResourceDeltaVisitor, ISystemTextEditorConstants, ISystemRemoteEditConstants +{ + + + private IRemoteFile remoteFile; + private String remotePath; + private IRemoteFileSubSystem subsystem; + private String root; + private String localPath; + private IEditorPart editor; + private IFile localFile; + private IWorkbenchPage page; + + /** + * Internal class for downloading file + */ + private class InternalDownloadFileRunnable extends WorkspaceModifyOperation + { + + private Exception e; + private boolean completed = false; + + /** + * Constructor for InternalDownloadFileRunnable + */ + private InternalDownloadFileRunnable() + { + } + + /** + * @see WorkspaceModifyOperation#execute(IProgressMonitor) + */ + protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException + { + + try + { + completed = SystemEditableRemoteFile.this.download(monitor); + monitor.done(); + } + catch (CoreException e) + { + throw e; + } + catch (InvocationTargetException e) + { + throw e; + } + catch (InterruptedException e) + { + // cancel was pressed by user + monitor.setCanceled(true); + throw e; + } + catch (Exception e) + { + SystemBasePlugin.logError("File can not be downloaded", e); + this.e = e; + } + } + + public boolean didComplete() + { + return completed; + } + + /** + * Get the exception that may have been thrown + */ + private void throwException() throws Exception + { + + if (e != null) + { + throw e; + } + } + }; + + private String _editorId = null; + private boolean _isRemoteFileMounted = false; + private String _actualRemoteHost = null; + private String _actualRemotePath = null; + + /** + * Constructor for SystemEditableRemoteFile + */ + public SystemEditableRemoteFile(IWorkbenchPage page, IRemoteFile remoteFile, String editorId) + { + super(); + this.page = page; + this.remoteFile = remoteFile; + this.remotePath = remoteFile.getAbsolutePath(); + this.subsystem = remoteFile.getParentRemoteFileSubSystem(); + SystemRemoteEditManager mgr = SystemRemoteEditManager.getDefault(); + + // if remote edit project doesn't exist, create it + if (!mgr.doesRemoteEditProjectExist()) + mgr.getRemoteEditProject(); + + this.root = mgr.getRemoteEditProjectLocation().makeAbsolute().toOSString(); + this.localPath = getDownloadPath(); + this._editorId = editorId; + } + + /** + * Constructor for SystemEditableRemoteFile + */ + public SystemEditableRemoteFile(IRemoteFile remoteFile, String editorId) + { + this(null, remoteFile, editorId); + } + + /** + * Constructor for SystemEditableRemoteFile + */ + public SystemEditableRemoteFile(IRemoteFile remoteFile) + { + super(); + this.remoteFile = remoteFile; + this.remotePath = remoteFile.getAbsolutePath(); + this.subsystem = remoteFile.getParentRemoteFileSubSystem(); + this.root = SystemRemoteEditManager.getDefault().getRemoteEditProjectLocation().makeAbsolute().toOSString(); + this.localPath = getDownloadPath(); + + // dkm - use registered + String fileName = remoteFile.getName(); + + IEditorRegistry registry = getEditorRegistry(); + + IEditorDescriptor descriptor = registry.getDefaultEditor(fileName); + if (descriptor == null) + { + descriptor = getDefaultTextEditor(); + } + String id = descriptor.getId(); + this._editorId = id; + } + + protected IEditorRegistry getEditorRegistry() + { + return SystemPlugin.getDefault().getWorkbench().getEditorRegistry(); + } + + protected IEditorDescriptor getDefaultTextEditor() + { + IEditorRegistry registry = getEditorRegistry(); + return registry.findEditor("org.eclipse.ui.DefaultTextEditor"); + } + + + /** + * Returns an instance of this class given a local copy of a remote file. + * @param file the local file to create it from. + * @return + */ + public static SystemEditableRemoteFile getInstance(IFile file) { + + // first determine associated remote file + IPath path = file.getFullPath(); + int numSegments = path.segmentCount(); + + // first we need to find the right RemoteFileSubSystem for the remote file + SystemIFileProperties properties = new SystemIFileProperties(file); + + ISubSystem fs = null; + + // get the subsystem ID property from the temporary file + String subsystemId = properties.getRemoteFileSubSystem(); + + // the subsystem ID may not exist if the temporary file existed before this feature + // to handle migration of this smoothly, we can use another method to determine the subsystem + if (subsystemId != null) + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + fs = registry.getSubSystem(subsystemId); + } + + if (fs != null) + { + // use the remote file path property of the temp file to determine the path of the remote file + // on the remote system + String remotePath = properties.getRemoteFilePath(); + + // the uploadPath property may not exist if the temporary file existed before this feature + // to handle migration of this smoothly, we can use another method to determine the remote file path + if (remotePath == null) + { + // derive the path from the temporary file path + IHost connection = fs.getHost(); + + // on windows systems, we need to take into account drives and different separators + boolean isWindows = connection.getSystemType().equals("Local") || fs.getHost().getSystemType().equals("Windows"); + + char fileSeparator = isWindows ? '\\' : '/'; + StringBuffer tempRemotePath = new StringBuffer(""); + for (int i = 3; i < numSegments; i++) + { + if (i == 3) + { + if (!isWindows) + { + tempRemotePath.append(fileSeparator); + } + } + if (i > 3) + { + if (i == 4) + { + if (isWindows) + { + tempRemotePath.append(":"); + } + } + + tempRemotePath.append(fileSeparator); + } + + String seg = path.segment(i); + tempRemotePath.append(seg); + } + + remotePath = tempRemotePath.toString(); + } + + try { + if (remotePath != null && fs instanceof IRemoteFileSubSystem) { + IRemoteFile remoteFile = ((IRemoteFileSubSystem)fs).getRemoteFileObject(remotePath); + + if (remoteFile != null) { + return new SystemEditableRemoteFile(remoteFile); + } + else { + return null; + } + } + else { + return null; + } + } + catch (SystemMessageException e) { + SystemBasePlugin.logError("Error getting remote file object " + remotePath, e); + } + } + + return null; + } + + /** + * Set the remote file + */ + public void setRemoteFile(IRemoteFile remoteFile) + { + this.remoteFile = remoteFile; + this.remotePath = remoteFile.getAbsolutePath(); + this.subsystem = remoteFile.getParentRemoteFileSubSystem(); + this.localPath = getDownloadPath(); + this.localFile = null; + } + + /** + * Get the remote file + */ + public IRemoteFile getRemoteFile() + { + return remoteFile; + } + + /** + * Set the local path + */ + public void setLocalPath(String localPath) + { + this.localPath = localPath; + } + + /** + * Get the local path + */ + public String getLocalPath() + { + return localPath; + } + + /** + * Set the editor + */ + public void setEditor(IEditorPart editor) + { + this.editor = editor; + } + + /** + * Get the editor + */ + public IEditorPart getEditor() + { + return editor; + } + + /** + * Check if user has write authority to the file. + * @return true if the file is readonly + */ + public boolean isReadOnly() + { + + if (!subsystem.isConnected()) + { + try + { + subsystem.connect(); + } + catch (Exception e) + { + } + } + + return !remoteFile.canWrite(); + } + + /** + * Indicate whether the file can be edited + */ + public void setReadOnly(boolean isReadOnly) + { + if (isReadOnly) + { + setEditorAsReadOnly(); + } + else if (editor instanceof ISystemTextEditor) + { + ((ISystemTextEditor) editor).setReadOnly(false); + } + } + + /** + * Download the file. + * @param if the shell is null, no progress monitor will be shown + * @return true if successful, false if cancelled + */ + public boolean download(Shell shell) throws Exception + { + + if (shell != null) + { + + + InternalDownloadFileRunnable downloadFileRunnable = new InternalDownloadFileRunnable(); + ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell); + IFile localFile = getLocalResource(); + SystemUniversalTempFileListener listener = SystemUniversalTempFileListener.getListener(); + listener.addIgnoreFile(localFile); + + pmd.run(false, true, downloadFileRunnable); + + listener.removeIgnoreFile(localFile); + downloadFileRunnable.throwException(); + return downloadFileRunnable.didComplete(); + } + else + { + return download((IProgressMonitor) null); + } + } + + protected void setReadOnly(IFile file, boolean flag) + { + ResourceAttributes attrs = file.getResourceAttributes(); + attrs.setReadOnly(flag); + try + { + file.setResourceAttributes(attrs); + } + catch (CoreException e) + { + } + } + + /** + * Download the file. + * @param the progress monitor + * @returns true if the operation was successful. false if the user cancels. + */ + public boolean download(IProgressMonitor monitor) throws Exception + { + + // DY: check if the file exists and is read-only (because it was previously opened + // in the system editor) + IFile file = getLocalResource(); + SystemIFileProperties properties = new SystemIFileProperties(file); + boolean newFile = !file.exists(); + if (file.isReadOnly()) + { + setReadOnly(file, false); + } + properties.setReadOnly(false); + + // detect whether there exists a temp copy already + if (!newFile && file.exists()) + { + // we have a local copy of this file, so we need to compare timestamps + + // get stored modification stamp + long storedModifiedStamp = properties.getRemoteFileTimeStamp(); + + // get updated remoteFile so we get the current remote timestamp + //remoteFile.markStale(true); + remoteFile = subsystem.getRemoteFileObject(remoteFile.getAbsolutePath()); + + // get the remote modified stamp + long remoteModifiedStamp = remoteFile.getLastModified(); + + // get dirty flag + boolean dirty = properties.getDirty(); + + boolean remoteNewer = (storedModifiedStamp != remoteModifiedStamp); + if (dirty) + { + // we have a dirty file with pending changes + // user may want to replace this with the remote file + // here we prompt user **** Prompt Dialog 2 or 3 + // 1) replace pending changes with remote file + // 2) open editor with our pending changes + SystemDownloadConflictAction conflictAction = new SystemDownloadConflictAction(file, remoteNewer); + Display.getDefault().syncExec(conflictAction); + + switch (conflictAction.getState()) + { + case SystemDownloadConflictAction.CANCELLED : + return false; + case SystemDownloadConflictAction.OPEN_WITH_LOCAL : + return true; + case SystemDownloadConflictAction.REPLACE_WITH_REMOTE : + default : + return doDownload(properties, monitor); + } + } + else + { + if (remoteNewer) + { + return doDownload(properties, monitor); + } + else + { + if (properties.getUsedBinaryTransfer() == remoteFile.isBinary()) + { + // we already have same file, use the current file + refresh(); + } + else + { + // we transferred a different way last time, so we need to transfer again + return doDownload(properties, monitor); + } + } + } + } + + else + { + return doDownload(properties, monitor); + } + + return true; + } + + private boolean doDownload(SystemIFileProperties properties, IProgressMonitor monitor) throws Exception + { + // file hasn't been downloaded before, so do the download now + /* SystemMessage copyMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COPYTHINGGENERIC_PROGRESS); + copyMessage.makeSubstitution(remoteFile.getName()); + monitor.beginTask(copyMessage.getLevelOneText(), (int)remoteFile.getLength()); + */ + if (!subsystem.isConnected()) + { + // don't try to download file if not connected + return false; + } + + subsystem.downloadUTF8(remoteFile, localPath, monitor); + + // get fresh remote file object + remoteFile = subsystem.getRemoteFileObject(remoteFile.getAbsolutePath()); + + refresh(); + + // get fresh file object + IFile file = getLocalResource(); + properties.setRemoteFileTimeStamp(remoteFile.getLastModified()); + properties.setDownloadFileTimeStamp(file.getLocalTimeStamp()); + properties.setDirty(false); + properties.setUsedBinaryTransfer(remoteFile.isBinary()); + properties.setDownloadFileTimeStamp(file.getLocalTimeStamp()); + + return true; + } + + /** + * Saves the local file and uploads it to the host immediately, rather than, in response to a resource change + * event. + */ + public boolean doImmediateSaveAndUpload() + { + if (editor != null) + { + editor.doSave(null); + } + + SystemUniversalTempFileListener listener = SystemUniversalTempFileListener.getListener(); + listener.setEnabled(false); + + IRemoteFile remoteFile = getRemoteFile(); + IFile tempFile = getLocalResource(); + IRemoteFileSubSystem fs = remoteFile.getParentRemoteFileSubSystem(); + SystemIFileProperties properties = new SystemIFileProperties(tempFile); + + // reget the remote file so that we have the right timestamps + try + { + remoteFile = fs.getRemoteFileObject(remoteFile.getAbsolutePath()); + } + catch (Exception e) + { + return false; + } + listener.upload(fs, remoteFile, tempFile, properties, properties.getRemoteFileTimeStamp(), this, null); + + listener.setEnabled(true); + + return !properties.getDirty(); + //return true; + } + + /** + * Upload the file + */ + private void upload() throws Exception + { + + if (!subsystem.isConnected()) + { + subsystem.connect(); + } + + subsystem.uploadUTF8(localPath, remoteFile, null); + + // update timestamp + IFile file = getLocalResource(); + SystemIFileProperties properties = new SystemIFileProperties(file); + + //DKM- saveAS fix + remoteFile = subsystem.getRemoteFileObject(remoteFile.getAbsolutePath()); + properties.setRemoteFileTimeStamp(remoteFile.getLastModified()); + } + + /** + * Get the local resource + */ + public IFile getLocalResource() + { + /* DKM - don't use this because workspace can't always handle case-sensitivity + System.out.println("getting file for " + localPath); + File file = new File(localPath); + System.out.println("file= " + file); + try + { + String path = file.getCanonicalPath(); + return SystemPlugin.getWorkspaceRoot().getFileForLocation(new Path(path)); + } + catch (IOException e) + { + e.printStackTrace(); + } + */ + if (localFile == null || !localFile.exists()) + { + IPath path = getLocalPathObject(); + localFile = SystemBasePlugin.getWorkspaceRoot().getFileForLocation(path); + } + return localFile; + } + + private IPath getLocalPathObject() + { + IPath actualPath = null; + IPath expectedPath = new Path(localPath); + + IPath rootPath = new Path(root); + IContainer container = SystemBasePlugin.getWorkspaceRoot().getContainerForLocation(rootPath); + + if (container != null && container.exists()) + { + IResource lastMatch = null; + for (int i = rootPath.segmentCount(); i < expectedPath.segmentCount(); i++) + { + String expectedFolderOrFile = expectedPath.segment(i).toLowerCase(); + IResource match = null; + + try + { + IResource[] resources = container.members(); + + for (int r = 0; r < resources.length && match == null; r++) + { + IResource resource = resources[r]; + + if (resource instanceof IContainer) + { + String resName = resource.getName().toLowerCase(); + if (expectedFolderOrFile.equals(resName)) + { + match = resource; + lastMatch = match; + } + } + // file match - i.e. last file + else if (i == expectedPath.segmentCount() - 1) + { + String resName = resource.getName().toLowerCase(); + if (expectedFolderOrFile.equals(resName)) + { + //match = resource; + //lastMatch = match; + // we found the resource - need to continue + return resource.getLocation(); + } + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + + if (match != null) + { + container = (IContainer) match; + } + else if (lastMatch != null) + { + IPath newPath = lastMatch.getLocation(); + while (i < expectedPath.segmentCount()) + { + newPath = newPath.append(expectedPath.segment(i)); + i++; + } + + return newPath; + } + else + { + return expectedPath; + } + } + + String fileName = expectedPath.segment(expectedPath.segmentCount() - 1); + actualPath = container.getLocation().append(fileName); + return actualPath; + } + + return expectedPath; + } + + /** + * Delete the local resource + */ + public void delete() + { + + IPath rootPath = (new Path(root)).removeTrailingSeparator(); + + String rootLocation = rootPath.makeAbsolute().toOSString(); + + String resourceLocation = getLocalResource().getLocation().makeAbsolute().toOSString(); + + File tempFile = new File(resourceLocation); + + boolean deleteResult = tempFile.delete(); + + if (!deleteResult) + { + return; + } + + while (resourceLocation.startsWith(rootLocation)) + { + + tempFile = tempFile.getParentFile(); + resourceLocation = tempFile.getAbsolutePath(); + + if (resourceLocation.equals(rootLocation)) + { // do not delete the root folder itself + break; + } + + deleteResult = tempFile.delete(); + + if (!deleteResult) + { + break; + } + } + + // refresh after delete + refresh(); + } + + /** + * Get the download path + */ + private String getDownloadPath() + { + + IPath path = new Path(root); + + _actualRemoteHost = getActualHostFor(remotePath); + + // DKM - now we're using only the hostname to prefix the remote path. Thus multiple connections to the same place will + // yield the temp files + //path = path.append("/" + subsystem.getSystemProfileName() + "/" + subsystem.getSystemConnectionName() + "/"); + path = path.append("/" + _actualRemoteHost + "/"); + + String absolutePath = getWorkspaceRemotePath(remotePath); + + int colonIndex = absolutePath.indexOf(IPath.DEVICE_SEPARATOR); + + if (colonIndex != -1) + { + + if (colonIndex == 0) + { + absolutePath = absolutePath.substring(1); + } + else if (colonIndex == (absolutePath.length() - 1)) + { + absolutePath = absolutePath.substring(0, colonIndex); + } + else + { + absolutePath = absolutePath.substring(0, colonIndex).toLowerCase() + absolutePath.substring(colonIndex + 1); + } + } + + // DY: We should only be escaping the remote portion of the path + IPath remote = new Path(absolutePath); + absolutePath = SystemFileNameHelper.getEscapedPath(remote.toOSString()); + _actualRemotePath = absolutePath; + + //path = path.append(absolutePath); + //return SystemFileNameHelper.getEscapedPath(path.makeAbsolute().toOSString()); + + return path.makeAbsolute().toOSString() + absolutePath; + } + + /** + * Gets the path to use in the workspace for saving the local replica remote file. In most cases + * this path will be the same thing as the remote path however, this mechanism exists so that 3rd parties + * can customize where temp files are saved. + * + * @param remotePath the absolute path to the resource on the host + * @return the workspace mapping of the remote path + */ + public String getWorkspaceRemotePath(String remotePath) + { + if (subsystem != null && subsystem.getHost().getSystemType().equals("Local")) + { + return SystemRemoteEditManager.getDefault().getWorkspacePathFor(subsystem.getHost().getHostName(), remotePath); + } + return remotePath; + } + + public String getActualHostFor(String remotePath) + { + String hostname = subsystem.getHost().getHostName(); + if (subsystem != null && subsystem.getHost().getSystemType().equals("Local")) + { + String result = SystemRemoteEditManager.getDefault().getActualHostFor(hostname, remotePath); + if (!result.equals(hostname)) + { + _isRemoteFileMounted = true; + } + return result; + } + return hostname; + } + + + /** + * Returns the open IEditorPart for this remote object if there is one. + */ + public IEditorPart getEditorPart() + { + return editor; + } + + /** + * Returns the remote object that is editable + */ + public IAdaptable getRemoteObject() + { + return (IAdaptable) remoteFile; + } + + /** + * Is the local file open in an editor + */ + public int checkOpenInEditor() + { + // first we check if it's open in the active page + IWorkbenchPage activePage = this.page; + if (activePage == null) + { + IWorkbenchWindow activeWindow = SystemBasePlugin.getActiveWorkbenchWindow(); + activePage = activeWindow.getActivePage(); + } + + IEditorReference[] activeReferences = activePage.getEditorReferences(); + + IEditorPart part; + java.io.File lFile = new java.io.File(localPath); + + for (int k = 0; k < activeReferences.length; k++) + { + + // Need to think about whether to restore the editor here, + // i.e. whether the argument to the getEditor() should be true + part = activeReferences[k].getEditor(false); + + //DKM***if (part instanceof SystemTextEditor) + if (part != null) + { + + IEditorInput editorInput = part.getEditorInput(); + + if (editorInput instanceof IFileEditorInput) + { + IPath path = ((IFileEditorInput) editorInput).getFile().getLocation(); + java.io.File pathFile = new java.io.File(path.toOSString()); + + if (pathFile.compareTo(lFile) == 0) + { + //if (path.makeAbsolute().toOSString().equalsIgnoreCase(localPath)) + //{ + return OPEN_IN_SAME_PERSPECTIVE; + } + } + } + } + + IWorkbenchWindow[] windows = SystemPlugin.getDefault().getWorkbench().getWorkbenchWindows(); + + for (int i = 0; i < windows.length; i++) + { + + IWorkbenchPage[] pages = windows[i].getPages(); + + for (int j = 0; j < pages.length; j++) + { + + IEditorReference[] references = pages[j].getEditorReferences(); + + if (pages[j] == activePage) + { + continue; + } + + IEditorPart temp; + + for (int k = 0; k < references.length; k++) + { + + // Need to think about whether to restore the editor here, + // i.e. whether the argument to the getEditor() should be true + temp = references[k].getEditor(false); + + IEditorInput editorInput = temp.getEditorInput(); + + if (editorInput instanceof IFileEditorInput) + { + IPath path = ((IFileEditorInput) editorInput).getFile().getLocation(); + + if (path.makeAbsolute().toOSString().equalsIgnoreCase(localPath)) + { + return OPEN_IN_DIFFERENT_PERSPECTIVE; + } + } + + } + } + } + + return NOT_OPEN; + } + + /** + * Open in editor + */ + public void open(Shell shell) + { + open(shell, false); + } + + /** + * Open in editor + */ + public void open(Shell shell, boolean readOnly) + { + + try + { + + + // first check if file is already open in an editor + int result = checkOpenInEditor(); + // ensure the file is stale + remoteFile.markStale(true, false); + { + remoteFile = remoteFile.getParentRemoteFileSubSystem().getRemoteFileObject(remoteFile.getAbsolutePath()); + } + + if (!remoteFile.exists()) + { + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_FILE_NOTFOUND); + message.makeSubstitution(remotePath, subsystem.getHost().getHostName()); + SystemMessageDialog dialog = new SystemMessageDialog(shell, message); + dialog.open(); + return; + } + + if (result == NOT_OPEN) + { + if (readOnly) + { + if (download(shell)) + { + setLocalResourceProperties(); + openEditor(); + setEditorAsReadOnly(); + } + } + else if (!isReadOnly()) + { // we have write access + if (download(shell)) + { + addAsListener(); + setLocalResourceProperties(); + openEditor(); + } + } + else + { // we do not have write access + + IRemoteFile fakeRemoteFile = subsystem.getRemoteFileObject(remotePath); + if (!fakeRemoteFile.exists()) + { // this could be because file doesn't exist + download(shell); + } + + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DOWNLOAD_NO_WRITE); + message.makeSubstitution(remotePath, subsystem.getHost().getHostName()); + SystemMessageDialog dialog = new SystemMessageDialog(shell, message); + + boolean answer = dialog.openQuestion(); + + if (answer) + { + if (download(shell)) + { + setLocalResourceProperties(); + setReadOnly(getLocalResource(), true); + openEditor(); + setEditorAsReadOnly(); + } + } + } + } + else if (result == OPEN_IN_SAME_PERSPECTIVE) + { + openEditor(); + } + else if (result == OPEN_IN_DIFFERENT_PERSPECTIVE) + { + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DOWNLOAD_ALREADY_OPEN_IN_EDITOR); + message.makeSubstitution(remotePath, subsystem.getHost().getHostName()); + SystemMessageDialog dialog = new SystemMessageDialog(shell, message); + + boolean answer = dialog.openQuestion(); + + if (answer) + { + openEditor(); + setEditorAsReadOnly(); // put editor in read only mode, but not file + } + } + } + catch (Exception e) + { + + if (e instanceof InterruptedException) + { + // do nothing since user pressed cancel + } + else if (e instanceof SystemMessageException) + { + SystemMessageDialog dialog = new SystemMessageDialog(shell, ((SystemMessageException) e).getSystemMessage()); + dialog.open(); + } + else + { + RemoteFileIOException exc = new RemoteFileIOException(e); + SystemMessageDialog dialog = new SystemMessageDialog(shell, exc.getSystemMessage()); + dialog.open(); + } + } + } + + /** + * Open in system editor + */ + public void openInSystemEditor(Shell shell) + { + + try + { + if (remoteFile.getSystemConnection().getSystemType().equals("Local")) + { + // Open local files "in-place", i.e. don't copy them to the + // RemoteSystemsTempFiles project first + if (remoteFile instanceof IVirtualRemoteFile) + { + Program.launch(remoteFile.getAbsolutePath()); + } + else + { + Program.launch(remotePath); + } + + } + else + { + download(shell); + IFile file = getLocalResource(); + // DY: set resource as read only when launching in external editor + // because we do not get notified of save events (unless the user selects + // "Refresh from local" on the project) and therefore cannot + // push changes back to the server. + setReadOnly(file, true); + openSystemEditor(); + } + } + catch (Exception e) + { + + if (e instanceof SystemMessageException) + { + SystemMessageDialog dialog = new SystemMessageDialog(shell, ((SystemMessageException) e).getSystemMessage()); + dialog.open(); + } + else + { + RemoteFileIOException exc = new RemoteFileIOException(e); + SystemMessageDialog dialog = new SystemMessageDialog(shell, exc.getSystemMessage()); + dialog.open(); + } + } + } + + /** + * Open in in place editor + */ + public void openInInPlaceEditor(Shell shell) + { + + try + { + download(shell); + IFile file = getLocalResource(); + // DY: set resource as read only when launching in external editor + // because we do not get notified of save events (unless the user selects + // "Refresh from local" on the project) and therefore cannot + // push changes back to the server. + setReadOnly(file, true); + openInPlaceEditor(); + + } + catch (Exception e) + { + + if (e instanceof SystemMessageException) + { + SystemMessageDialog dialog = new SystemMessageDialog(shell, ((SystemMessageException) e).getSystemMessage()); + dialog.open(); + } + else + { + RemoteFileIOException exc = new RemoteFileIOException(e); + SystemMessageDialog dialog = new SystemMessageDialog(shell, exc.getSystemMessage()); + dialog.open(); + } + } + } + + + /** + * Set local resource properties + */ + public void setLocalResourceProperties() throws CoreException + { + IFile file = getLocalResource(); + + SystemIFileProperties properties = new SystemIFileProperties(file); + + String profileID = subsystem.getParentRemoteFileSubSystemFactory().getEditorProfileID(); + properties.setEditorProfileType(profileID); + + // need this to get a reference back to the object + properties.setRemoteFileObject(this); + + // set remote properties + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + String subSystemId = registry.getAbsoluteNameForSubSystem(subsystem); + properties.setRemoteFileSubSystem(subSystemId); + properties.setRemoteFilePath(remoteFile.getAbsolutePath()); + + properties.setRemoteFileMounted(_isRemoteFileMounted); + if (_isRemoteFileMounted) + { + properties.setResolvedMountedRemoteFileHost(_actualRemoteHost); + properties.setResolvedMountedRemoteFilePath(_actualRemotePath); + } + + // if we have an xml file, find the local encoding of the file + SystemEncodingUtil util = SystemEncodingUtil.getInstance(); + String encoding = null; + + String tempPath = file.getLocation().toOSString(); + + if (util.isXML(tempPath)) { + + try { + encoding = util.getXMLFileEncoding(tempPath); + } + catch (IOException e) { + IStatus s = new Status(IStatus.ERROR, SystemPlugin.PLUGIN_ID, IStatus.ERROR, e.getLocalizedMessage(), e); + throw new CoreException(s); + } + } + else { + + if (!properties.getUsedBinaryTransfer()) { + encoding = SystemEncodingUtil.ENCODING_UTF_8; + } + } + + try + { + if (encoding != null) + { + if (!file.getCharset().equals(encoding)) + { + file.setCharset(encoding, null); + } + } + } + catch (Exception e) + { + } + } + + /** + * Register as listener for various events + */ + public void addAsListener() + { + try + { + if (!isReadOnly()) + { + if (SystemBasePlugin.getActiveWorkbenchWindow() != null) + { + if (SystemBasePlugin.getActiveWorkbenchWindow().getActivePage() != null) + { + SystemBasePlugin.getActiveWorkbenchWindow().getActivePage().addPartListener(this); + } + } + SystemUniversalTempFileListener.getListener().registerEditedFile(this); + } + } + catch (Exception e) + { + } + } + + /** + * Open the editor + */ + public void openEditor() throws PartInitException + { + IWorkbenchPage activePage = this.page; + if (activePage == null) + { + activePage = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + } + IFile file = getLocalResource(); + + // set editor as preferred editor for this file + IDE.setDefaultEditor(file, _editorId); + + FileEditorInput finput = new FileEditorInput(file); + + // check for files already open + + // DKM - when _editorId is not lpex, this causes problem + // DY - changed editor from SystemTextEditor to IEditorPart + //editor = (SystemTextEditor)activePage.openEditor(file, _editorId); + editor = activePage.openEditor(finput, _editorId); + } + + /** + * Open the system editor + */ + private void openSystemEditor() throws PartInitException + { + IWorkbenchPage activePage = this.page; + if (activePage == null) + { + activePage = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + } + IFile file = getLocalResource(); + + IEditorRegistry registry = getEditorRegistry(); + FileEditorInput fileInput = new FileEditorInput(file); + activePage.openEditor(fileInput, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + + } + + /** + * Open the in place editor + */ + private void openInPlaceEditor() throws PartInitException + { + IWorkbenchPage activePage = this.page; + if (activePage == null) + { + activePage = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + } + IFile file = getLocalResource(); + + IEditorRegistry registry = getEditorRegistry(); + FileEditorInput fileInput = new FileEditorInput(file); + activePage.openEditor(fileInput, IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); + + } + + /** + * Set editor to read only + */ + private void setEditorAsReadOnly() + { + if (editor instanceof ISystemTextEditor) + { + ((ISystemTextEditor) editor).setReadOnly(true); + } + IFile file = getLocalResource(); + + SystemIFileProperties properties = new SystemIFileProperties(file); + properties.setReadOnly(true); + } + + /** + * Refresh + */ + private void refresh() + { + + SystemRemoteEditManager.getDefault().refreshRemoteEditContainer(localFile.getParent()); + } + + /** + * @see IPartListener#partActivated(IWorkbenchPart) + */ + public void partActivated(IWorkbenchPart part) + { + } + + /** + * @see IPartListener#partBroughtToTop(IWorkbenchPart) + */ + public void partBroughtToTop(IWorkbenchPart part) + { + } + + /** + * @see IPartListener#partClosed(IWorkbenchPart) + */ + public void partClosed(IWorkbenchPart part) + { + /* + if (editor == part) + { + delete(); + } + */ + SystemUniversalTempFileListener.getListener().unregisterEditedFile(this); + + IWorkbenchPage page = SystemBasePlugin.getActiveWorkbenchWindow().getActivePage(); + + if (page != null) + { + page.removePartListener(this); + } + } + + /** + * @see IPartListener#partDeactivated(IWorkbenchPart) + */ + public void partDeactivated(IWorkbenchPart part) + { + } + + /** + * @see IPartListener#partOpened(IWorkbenchPart) + */ + public void partOpened(IWorkbenchPart part) + { + } + + /** + * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent) + */ + public void resourceChanged(IResourceChangeEvent event) + { + /* + if (event.getType() == IResourceChangeEvent.POST_CHANGE) { + + IResourceDelta delta = event.getDelta(); + + try { + delta.accept(this); + } + catch (CoreException e) { + SystemPlugin.logError("Error accepting delta", e); + RemoteFileIOException exc = new RemoteFileIOException(e); + SystemMessageDialog dialog = new SystemMessageDialog(SystemPlugin.getActiveWorkbenchShell(), exc.getSystemMessage()); + dialog.open(); + } + } + */ + } + + /** + * @see IResourceDeltaVisitor#visit(IResourceDelta) + */ + public boolean visit(IResourceDelta delta) throws CoreException + { + + if (delta.getKind() == IResourceDelta.CHANGED) + process(delta); + + return true; + } + + /** + * Process the resource delta + */ + private void process(IResourceDelta delta) + { + + IResource resource = delta.getResource(); + + try + { + + if (resource.getLocation().equals(getLocalResource().getLocation())) + { + upload(); + } + } + catch (Exception e) + { + + SystemBasePlugin.logError("Error uploading file", e); + + if (e instanceof SystemMessageException) + { + SystemMessageDialog dialog = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), ((SystemMessageException) e).getSystemMessage()); + dialog.open(); + } + else + { + RemoteFileIOException exc = new RemoteFileIOException(e); + SystemMessageDialog dialog = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), exc.getSystemMessage()); + dialog.open(); + } + } + } + + /** + * Save as to a remote location + */ + public boolean saveAs(IRemoteFile newRemoteFile, IProgressMonitor progressMonitor) + { + if (editor == null) + { + try + { + openEditor(); + } + catch (Exception e) + { + } + } + + final IDocumentProvider documentProvider = ((ITextEditor) editor).getDocumentProvider(); + + SystemEditableRemoteFile tempFile = new SystemEditableRemoteFile(newRemoteFile); + + IFile newFile = tempFile.getLocalResource(); + + if (newFile.getLocation().equals(getLocalResource().getLocation())) + { + + if (editor != null) + { + editor.doSave(progressMonitor); + return true; + } + else + { + return true; + } + } + + final IFileEditorInput newInput = new FileEditorInput(newFile); + + WorkspaceModifyOperation op = new WorkspaceModifyOperation() + { + + public void execute(final IProgressMonitor monitor) throws CoreException + { + documentProvider.saveDocument(monitor, newInput, documentProvider.getDocument(editor.getEditorInput()), true); + } + }; + + boolean success = false; + + if (editor instanceof ISystemTextEditor) + { + documentProvider.aboutToChange(newInput); + ISystemTextEditor systemEditor = (ISystemTextEditor) editor; + systemEditor.refresh(); + try + { + new ProgressMonitorDialog(SystemBasePlugin.getActiveWorkbenchShell()).run(false, true, op); + success = true; + } + catch (InterruptedException e) + { + } + catch (InvocationTargetException e) + { + SystemBasePlugin.logError("Error in performSaveAs", e); + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_UNEXPECTED); + SystemMessageDialog dialog = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), message); + dialog.open(); + return true; + } + finally + { + documentProvider.changed(newInput); + + if (success) + { + systemEditor.setInput(newInput); + + // Delete the local resource associated with this object + this.delete(); + + // change properties of this object to the new file now + this.setRemoteFile(newRemoteFile); + + try + { + this.setLocalResourceProperties(); + this.upload(); + } + catch (Exception e) + { + SystemBasePlugin.logError("Error in performSaveAs", e); + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_UNEXPECTED); + SystemMessageDialog dialog = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), message); + dialog.open(); + return true; + } + } + } + } + + if (progressMonitor != null) + { + progressMonitor.setCanceled(!success); + } + + return true; + } + + public void updateDirtyIndicator() + { + // for lpex dirty indicator + if (editor != null) + { + if (editor instanceof ISystemTextEditor) + { + ((ISystemTextEditor) editor).updateDirtyIndicator(); + } + } + } + + public boolean isDirty() + { + if (editor != null) + return editor.isDirty(); + return false; + } + + + public String getAbsolutePath() { + return remotePath; + } + + public ISubSystem getSubSystem() { + return subsystem; + } + + public boolean exists() + { + return remoteFile.exists(); + } + + public boolean isStale() + { + return remoteFile.isStale(); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemFileNameHelper.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemFileNameHelper.java new file mode 100644 index 00000000000..925e7de4344 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemFileNameHelper.java @@ -0,0 +1,80 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.File; + +import org.eclipse.rse.model.SystemEscapeCharHelper; + + +/** + * This class converts a remote file name (including path) to a valid local one by + * escaping invalid characters in local file names with an _xx escape sequence. + */ +public class SystemFileNameHelper { + + + + protected static final char[] array = {' ', ':', ';', '*', '?', '\'', '"', '<', '>', '|'}; + + + + + /** + * Get the escaped path name. Changes unsupported characters to _xyz. + */ + public static String getEscapedPath(String path) + { + char c = File.separatorChar; + + // NOTE: if it's Linux, Unix or iSeries, we don't like '\\' character, i.e. escape it + if (c == '/') { + c = '\\'; + } + // or if Windows, we don't like '/' character, i.e. escape it + else if (c == '\\') + { + c = '/'; + } + + // first escape char + array[0] = c; + + + SystemEscapeCharHelper helper = new SystemEscapeCharHelper(array); + + int index = path.indexOf(':'); + + // DKM - 56907 + if (index == -1 || path.charAt(0)==File.separatorChar) + { + return helper.getStringForFileName(path); + } + else + { + return (path.substring(0, index + 1) + helper.getStringForFileName(path.substring(index + 1))); + } + } + + /** + * Gets the unescaped path name. Changes all _xyz to the original unsupported character. + */ + public static String getUnescapedPath( String path ){ + SystemEscapeCharHelper helper = new SystemEscapeCharHelper(array); + return helper.getStringFromFileName( path ); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemIFileProperties.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemIFileProperties.java new file mode 100644 index 00000000000..e7e44e4ce0d --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemIFileProperties.java @@ -0,0 +1,543 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.rse.core.SystemPlugin; + + + +/** + * Class that encapsulates ISeries IResource persistent properties. + */ +public class SystemIFileProperties implements ISystemTextEditorConstants, ISystemRemoteEditConstants { + + + private static final String STRING_EMPTY = ""; + private static final String EXPORT_KEY = "export"; + + private static QualifiedName _nameDirty = new QualifiedName( STRING_EMPTY, TEMP_FILE_DIRTY ); + private static QualifiedName _nameReadOnly = new QualifiedName( STRING_EMPTY, TEMP_FILE_READONLY ); + private static QualifiedName _nameEditorProfileType = new QualifiedName( STRING_EMPTY, EDITOR_PROFILE_TYPE ); + private static QualifiedName _nameEncoding = new QualifiedName( STRING_EMPTY, SOURCE_ENCODING_KEY ); + private static QualifiedName _nameHasSequenceNumbers = new QualifiedName( STRING_EMPTY, SEQUENCE_NUMBERS_KEY ); + private static QualifiedName _nameRecordLength = new QualifiedName( STRING_EMPTY, MAX_LINE_LENGTH_KEY ); + private static QualifiedName _nameRemoteCCSID = new QualifiedName( STRING_EMPTY, CCSID_KEY ); + private static QualifiedName _nameRemoteFileObject = new QualifiedName( STRING_EMPTY, REMOTE_FILE_OBJECT_KEY ); + private static QualifiedName _nameRemoteFilePath = new QualifiedName( STRING_EMPTY, REMOTE_FILE_PATH_KEY ); + private static QualifiedName _nameRemoteFileSubSystem = new QualifiedName( STRING_EMPTY, REMOTE_FILE_SUBSYSTEM_KEY ); + private static QualifiedName _nameRemoteFileTimeStamp = new QualifiedName( STRING_EMPTY, REMOTE_FILE_MODIFIED_STAMP ); + private static QualifiedName _nameDownloadFileTimeStamp = new QualifiedName( STRING_EMPTY, DOWNLOAD_FILE_MODIFIED_STAMP ); + private static QualifiedName _nameUsedBinaryTransfer = new QualifiedName( STRING_EMPTY, REMOTE_FILE_BINARY_TRANSFER ); + private static QualifiedName _nameTempCCSID = new QualifiedName( STRING_EMPTY, TEMP_CCSID_KEY ); + private static QualifiedName _nameRemoteBIDILogical = new QualifiedName( STRING_EMPTY, BIDI_LOGICAL_KEY ); + + // for path mapping + private static QualifiedName _nameRemoteFileMounted = new QualifiedName( STRING_EMPTY, REMOTE_FILE_MOUNTED); + private static QualifiedName _nameResolvedMountedRemoteFileHost = new QualifiedName( STRING_EMPTY, RESOLVED_MOUNTED_REMOTE_FILE_HOST_KEY); + private static QualifiedName _nameResolvedMountedRemoteFilePath = new QualifiedName( STRING_EMPTY, RESOLVED_MOUNTED_REMOTE_FILE_PATH_KEY); + + // local encoding qualified name + // NOTE: DO NOT CHANGE THIS!! This exact qualified name is used by the IBM debugger. + private static QualifiedName _nameLocalEncoding = new QualifiedName(SystemPlugin.getDefault().getSymbolicName(), LOCAL_ENCODING_KEY); + + protected IResource _resource = null; + + /** + * + */ + public SystemIFileProperties( IResource file ){ + _resource = file; + + if( file == null ) + throw new NullPointerException(); + } + + /** + * Returns the temp file dirty persistent property value. + */ + public boolean getDirty(){ + return getPropertyBoolean( _nameDirty ); + } + + /** + * Returns the temp file readonly persistent property value. + */ + public boolean getReadOnly(){ + return getPropertyBoolean( _nameReadOnly); + } + + /** + * Returns whether the original file is marked as a mounted file + */ + public boolean getRemoteFileMounted(){ + return getPropertyBoolean( _nameRemoteFileMounted); + } + + /** + * Returns the editor profile persistent property value. + */ + public String getEditorProfileType(){ + return getPropertyString( _nameEditorProfileType ); + } + + /** + * Returns the source encoding persistent property value. + */ + public String getEncoding(){ + return getPropertyString( _nameEncoding ); + } + + /** + * Gets the local encoding persistent property value. + * @return the local encoding. + */ + public String getLocalEncoding() { + return getPropertyString(_nameLocalEncoding); + } + + /** + * Returns the file that this instance is associated with. + */ + public IResource getFile() { + return _resource; + } + + /** + * Returns the sequence numbers flag persistent property value. + */ + public boolean getHasSequenceNumbers(){ + return getPropertyBoolean( _nameHasSequenceNumbers ); + } + + /** + * Returns the session property value of the given property. + */ + protected Object getParentSessionObject( QualifiedName name ){ + try{ + return _resource.getParent().getSessionProperty( name ); + } + catch( CoreException ex ){ + return null; + } + } + + /** + * Returns the value of a boolean property. + */ + protected boolean getPropertyBoolean( QualifiedName name ){ + try{ + String strValue = _resource.getPersistentProperty( name ); + if( strValue == null ) + return false; + + return strValue.equals( "true" ); + } + catch( CoreException ex ){ + return false; + } + } + + /** + * Returns the value of an integer property. + */ + protected int getPropertyInteger( QualifiedName name ){ + try{ + String strValue = _resource.getPersistentProperty( name ); + + if( strValue == null ) + return 0; + + return Integer.parseInt( strValue ); + } + catch( CoreException ex ){ + return 0; + } + catch( NumberFormatException ex ){ + return 0; + } + } + + /** + * Returns the value of an integer property. + */ + protected long getPropertyLong( QualifiedName name ){ + try{ + String strValue = _resource.getPersistentProperty( name ); + + if( strValue == null ) + return 0; + + return Long.parseLong( strValue ); + } + catch( CoreException ex ){ + return 0; + } + catch( NumberFormatException ex ){ + return 0; + } + } + + /** + * Returns the value of a string persistent or session property. + */ + protected String getPropertyString( QualifiedName name ){ + try{ + return _resource.getPersistentProperty( name ); + } + catch( CoreException ex ){ + return STRING_EMPTY; + } + } + + /** + * Returns the remote file object session property value. + */ + public int getRecordLength() { + return getPropertyInteger( _nameRecordLength ); + } + + /** + * Returns the CCSID persistent property value. + */ + public int getRemoteCCSID(){ + return getPropertyInteger( _nameRemoteCCSID ); + } + + /** + * Returns the remote file object session property value. + */ + public Object getRemoteFileObject(){ + return getSessionObject( _nameRemoteFileObject ); + } + + /** + * Returns the remote file object session property value. + */ + public Object getTempCCSID(){ + return getParentSessionObject( _nameTempCCSID ); + } + + + /** + * Returns the actual file (member) path persistent property value on the originating host. + */ + public String getResolvedMountedRemoteFilePath(){ + return getPropertyString( _nameResolvedMountedRemoteFilePath); + } + + /** + * Returns the actual file (member) host persistent property value for a mounted file. + */ + public String getResolvedMountedRemoteFileHost(){ + return getPropertyString( _nameResolvedMountedRemoteFileHost); + } + + /** + * Returns the full file (member) path persistent property value. + */ + public String getRemoteFilePath(){ + return getPropertyString( _nameRemoteFilePath ); + } + + /** + * Returns the sub-system name persistent property value. + */ + public String getRemoteFileSubSystem(){ + return getPropertyString( _nameRemoteFileSubSystem ); + } + + /** + * Returns the remote file time stamp persistent property value. + */ + public long getRemoteFileTimeStamp(){ + return getPropertyLong( _nameRemoteFileTimeStamp ); + } + + + + /** + * Returns the timestamp of the Eclipse resource after download + */ + public long getDownloadFileTimeStamp(){ + return getPropertyLong( _nameDownloadFileTimeStamp ); + } + + /** + * Returns the session property value of the given property. + */ + protected Object getSessionObject( QualifiedName name ){ + try{ + return _resource.getSessionProperty( name ); + } + catch( CoreException ex ){ + return null; + } + } + + /** + * Returns the binary transfer flag persistent property value. + */ + public boolean getUsedBinaryTransfer(){ + return getPropertyBoolean( _nameUsedBinaryTransfer ); + } + + /** + * Sets the temp file dirty persistent property value. + */ + public void setDirty( boolean bDirty ){ + setPropertyBoolean( _nameDirty, bDirty ); + } + + /** + * Sets the temp file readonly persistent property value. + */ + public void setReadOnly( boolean bReadOnly ){ + setPropertyBoolean( _nameReadOnly, bReadOnly ); + } + + /** + * Sets the remote file mounted indicator property value + */ + public void setRemoteFileMounted( boolean bMounted){ + setPropertyBoolean( _nameRemoteFileMounted, bMounted); + } + + /** + * Sets the editor profile type persistent property value. + */ + public void setEditorProfileType( String strType ){ + setPropertyString( _nameEditorProfileType, strType ); + } + + /** + * Sets the source encoding persistent property value. + */ + public void setEncoding( String strEncoding ){ + setPropertyString( _nameEncoding, strEncoding ); + } + + /** + * Sets the local encoding persistent property value. + * @param strLocalEncoding the local encoding. + */ + public void setLocalEncoding(String strLocalEncoding) { + setPropertyString(_nameLocalEncoding, strLocalEncoding); + } + + /** + * Returns whether the file is stored in BIDI logical format. + * @return true if the file is stored in BIDI logical format, false if the file is stored in BIDI + * visual format. + */ + public boolean getBIDILogical() { + return getPropertyBoolean(_nameRemoteBIDILogical); + } + + /** + * Sets whether the file is stored in BIDI logical format. + * @param logical true if the file is stored in BIDI logical format, false if the file is stored in BIDI + * visual format. + */ + public void setBIDILogical(boolean logical) { + setPropertyBoolean(_nameRemoteBIDILogical, logical); + } + + /** + * Sets the sequence numbers flag persistent property value. + */ + public void setHasSequenceNumbers( boolean bSequenceNumbers ){ + setPropertyBoolean( _nameHasSequenceNumbers, bSequenceNumbers ); + } + + /** + * Sets the session property to the given object. + */ + protected void setParentSessionObject( QualifiedName name, Object objValue ){ + try{ + _resource.getParent().setSessionProperty( name, objValue ); + } + catch( CoreException ex ){ + } + } + + /** + * Sets a boolean property given a property name, and its value. + */ + protected void setPropertyBoolean( QualifiedName name, boolean bValue ){ + setPropertyString( name, bValue == true ? "true" : "false" ); + } + + /** + * Sets a boolean property given a property name, and its value. + */ + protected void setPropertyInteger( QualifiedName name, int iValue ){ + setPropertyString( name, String.valueOf( iValue ) ); + } + + /** + * Sets a boolean property given a property name, and its value. + */ + protected void setPropertyLong( QualifiedName name, long lValue ){ + setPropertyString( name, String.valueOf( lValue ) ); + } + + /** + * Sets a string property given a property name, and its value. + */ + protected void setPropertyString( QualifiedName name, String strValue ){ + + // Setting is expensive, so do get and compare first + //-------------------------------------------------- + String strValueCurrent = null; + + try{ + strValueCurrent = _resource.getPersistentProperty( name ); + } + + catch( CoreException ex ){ + strValueCurrent = STRING_EMPTY; + } + + // If the value to be set is currently set, do nothing + //---------------------------------------------------- + if( strValue != null && strValue.equals( strValueCurrent ) == true ) + return; + + // McCoy the new value + //-------------------- + try{ + _resource.setPersistentProperty( name, strValue ); + } + catch( CoreException ex ){ + } + } + + /** + * Sets the record length persistent property value. + */ + public void setRecordLength( int iRecordLength ){ + setPropertyInteger( _nameRecordLength, iRecordLength ); + } + + /** + * Sets the codepage source encoding such as "Cp937" persistent property value. + */ + public void setRemoteCCSID( int iCCSID ){ + setPropertyInteger( _nameRemoteCCSID, iCCSID ); + } + + /** + * Sets the remote system member path persistent property value. + */ + public void setRemoteFileObject( Object object ) { + setSessionObject( _nameRemoteFileObject, object ); + } + + + /** + * Sets the actual remote system file (member) path persistent property value on the originating host. + */ + public void setResolvedMountedRemoteFilePath( String strPath ){ + setPropertyString( _nameResolvedMountedRemoteFilePath, strPath ); + } + + + /** + * Sets the actual remote system file (member) path persistent property value on the originating host. + */ + public void setResolvedMountedRemoteFileHost( String strHost ){ + setPropertyString( _nameResolvedMountedRemoteFileHost, strHost ); + } + + /** + * Sets the remote system file (member) path persistent property value. + */ + public void setRemoteFilePath( String strPath ){ + setPropertyString( _nameRemoteFilePath, strPath ); + } + + /** + * Sets the sub system name persistent property value. + */ + public void setRemoteFileSubSystem( String strSubSystem ){ + setPropertyString( _nameRemoteFileSubSystem, strSubSystem ); + } + + /** + * Sets the remote file time stamp persistent property value. + */ + public void setRemoteFileTimeStamp( long lTimeStamp ){ + setPropertyLong( _nameRemoteFileTimeStamp, lTimeStamp ); + } + + /** + * Sets the local file time stamp property value of download. + */ + public void setDownloadFileTimeStamp( long lTimeStamp ){ + setPropertyLong( _nameDownloadFileTimeStamp, lTimeStamp ); + } + + /** + * Sets the session property to the given object. + */ + protected void setSessionObject( QualifiedName name, Object objValue ){ + try{ + _resource.setSessionProperty( name, objValue ); + } + catch( CoreException ex ){ + } + } + + /** + * Sets the remote system member path persistent property value. + */ + public void setTempCCSID( Object object ) { + setParentSessionObject( _nameTempCCSID, object ); + } + + /** + * Sets the binary transfer flag persistent property value. + */ + public void setUsedBinaryTransfer( boolean bBinaryTransfer ){ + setPropertyBoolean( _nameUsedBinaryTransfer, bBinaryTransfer ); + } + + public void setModificationStampAtExport(String hostName, String destination, long modificationStamp) { + QualifiedName key = new QualifiedName(STRING_EMPTY, EXPORT_KEY + ":" + hostName + ":" + destination); + setPropertyLong(key, modificationStamp); + } + + public long getModificationStampAtExport(String hostName, String destination) { + QualifiedName key = new QualifiedName(STRING_EMPTY, EXPORT_KEY + ":" + hostName + ":" + destination); + return getPropertyLong(key); + } + + public boolean hasModificationStampAtExport(String hostName, String destination) { + QualifiedName key = new QualifiedName(STRING_EMPTY, EXPORT_KEY + ":" + hostName + ":" + destination); + String val = getPropertyString(key); + + if (val != null) { + return true; + } + else { + return false; + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteEditManager.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteEditManager.java new file mode 100644 index 00000000000..ba13f620104 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteEditManager.java @@ -0,0 +1,771 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Platform; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; + + +/** + * This is a singleton class that manages the remote editing + */ + +public class SystemRemoteEditManager +{ + + + public static final String REMOTE_EDIT_PROJECT_NAME = "RemoteSystemsTempFiles"; + public static final String REMOTE_EDIT_PROJECT_NATURE_ID = "org.eclipse.rse.ui.remoteSystemsTempNature"; + public static final String REMOTE_EDIT_PROJECT_BUILDER_ID = "org.eclipse.rse.ui.remoteSystemsTempBuilder"; + + private static SystemRemoteEditManager inst; + private SystemPlugin plugin; + private List _mountPathMappers; + + /** + * Constructor for SystemRemoteEditManager + */ + private SystemRemoteEditManager() + { + super(); + plugin = SystemPlugin.getDefault(); + registerMountPathMappers(); + } + + /** + * Get the singleton instance + */ + public static SystemRemoteEditManager getDefault() + { + + if (inst == null) + inst = new SystemRemoteEditManager(); + + return inst; + } + + /** + * Return the hostname that corresponds to the resource specified on the host specified. If + * the resource is actually on the specified host, then the result will be the same as hostname. If + * the resource is mounted then a mount path mapper has the opportunity to return the actual host. + * @param hostname the system on which a resource is obtained (may contain the file via a mount) + * @param remotePath the path on the host where the resource is obtained + * @return the actual host where the resource exists + */ + public String getActualHostFor(String hostname, String remotePath) + { + ISystemMountPathMapper mapper = getMountPathMapperFor(hostname, remotePath); + if (mapper != null) + { + return mapper.getActualHostFor(hostname, remotePath); + } + else + { + return hostname; + } + } + + /** + * Return the path to use on the system (i.e. Windows) for saving from the workspace to remote + * @param hostname the remote host + * @param remotePath the file path on the remote host + * @return the system path + */ + public String getMountPathFor(String hostname, String remotePath) + { + ISystemMountPathMapper mapper = getMountPathMapperFor(hostname, remotePath); + if (mapper != null) + { + return mapper.getMountedMappingFor(hostname, remotePath); + } + else + { + return remotePath; + } + } + + /** + * Return the path to use relative to the hostname in the RemoteSystemsTempFiles project for saving a local replica + * @param hostname the originating remote host + * @param remotePath the file path on the system (i.e. Windows) + * @return the relative replica path + */ + public String getWorkspacePathFor(String hostname, String remotePath) + { + ISystemMountPathMapper mapper = getMountPathMapperFor(hostname, remotePath); + if (mapper != null) + { + return mapper.getWorkspaceMappingFor(hostname, remotePath); + } + else + { + return remotePath; + } + } + + /** + * Return the appropriate registered mapper for a host & path + * @param hostname + * @param remotePath + * @return appropriate mapper + */ + public ISystemMountPathMapper getMountPathMapperFor(String hostname, String remotePath) + { + for (int i = 0; i < _mountPathMappers.size(); i++) + { + ISystemMountPathMapper mapper = (ISystemMountPathMapper) _mountPathMappers.get(i); + if (mapper != null) + { + if (mapper.handlesMappingFor(hostname, remotePath)) + { + return mapper; + } + } + } + return null; + } + + protected void registerMountPathMappers() + { + _mountPathMappers = new ArrayList(); + + // Get reference to the plug-in registry + IExtensionRegistry registry = Platform.getExtensionRegistry(); + + // Get configured extenders + IConfigurationElement[] systemTypeExtensions = registry.getConfigurationElementsFor("org.eclipse.rse.ui", "mountPathMappers"); + + for (int i = 0; i < systemTypeExtensions.length; i++) + { + try + { + _mountPathMappers.add(systemTypeExtensions[i].createExecutableExtension("class")); + } + catch (Exception e) + { + } + } + } + + /** + * Check if a remote edit project exists + * @return true if it does + */ + public boolean doesRemoteEditProjectExist() + { + IWorkspaceRoot root = SystemBasePlugin.getWorkspaceRoot(); + + IProject editProject = root.getProject(REMOTE_EDIT_PROJECT_NAME); + + if ((editProject != null) && (editProject.exists()) && (editProject.isOpen())) + return true; + return false; + } + + /** + * Get the project that in which all folders and files are held temporarily + * for remote editing. Create the project if it doesn't exist already, and opens + * it if it is not already open. + * @return the project where all files should be stored during remote edit. + */ + public IProject getRemoteEditProject() + { + IWorkspaceRoot root = SystemBasePlugin.getWorkspaceRoot(); + + IProject editProject = root.getProject(REMOTE_EDIT_PROJECT_NAME); + + if ((editProject != null) && (editProject.exists()) && (editProject.isOpen())) + { + try + { + /* no more java support + if (!editProject.hasNature(JavaCore.NATURE_ID)) + { + addJavaSupport(editProject); + } + * no need for this anymore + * normally there is no cdt - so let's not do this everytime + if (!editProject.hasNature("org.eclipse.cdt.core.cnature")) + { + addCSupport(editProject); + } + */ + } + catch (Exception e) + { + + } + return editProject; + } + + if ((editProject == null) || !(editProject.exists()) || !(editProject.isOpen())) + editProject = createRemoteEditProject(); + + return editProject; + } + + /** + * Creates the remote project, and opens it if it not open. + * @return the project where all files should be stored during remote editing + */ + private IProject createRemoteEditProject() + { + IWorkspaceRoot root = SystemBasePlugin.getWorkspaceRoot(); + + IProject editProject = root.getProject(REMOTE_EDIT_PROJECT_NAME); + + if ((editProject != null) && (editProject.exists()) && (editProject.isOpen())) + { + /* + try + { + // no java or c support - this needs to be contributed from elsewhere + if (!editProject.hasNature(JavaCore.NATURE_ID)) + { + addJavaSupport(editProject); + } + + if (!editProject.hasNature("org.eclipse.cdt.core.cnature")) + { + addCSupport(editProject); + } + + } + catch (CoreException e) + { + } + */ + return editProject; + } + + if (editProject == null) + { + // log error and throw an exception + } + + try + { + if (!editProject.exists()) + editProject.create(null); + + if (!editProject.isOpen()) + editProject.open(null); + + IProjectDescription description = editProject.getDescription(); + String[] natures = description.getNatureIds(); + String[] newNatures = new String[natures.length + 1]; + + // copy all previous natures + for (int i = 0; i < natures.length; i++) + { + newNatures[i] = natures[i]; + } + + + newNatures[newNatures.length - 1] = REMOTE_EDIT_PROJECT_NATURE_ID; + + description.setNatureIds(newNatures); + editProject.setDescription(description, null); + + // add java support + //addJavaSupport(editProject); + + // add c support + //addCSupport(editProject); + } + catch (CoreException e) + { + SystemBasePlugin.logError("Error creating temp project", e); + } + return editProject; + } +/* + public void addCSupport(IProject editProject) + { + + try + { + IProjectDescription description = editProject.getDescription(); + String[] natures = description.getNatureIds(); + ICommand[] buildSpecs = description.getBuildSpec(); + + String[] newNatures = new String[natures.length + 2]; + + // copy all previous natures + for (int i = 0; i < natures.length; i++) + { + newNatures[i] = natures[i]; + } + + newNatures[newNatures.length - 2] = "org.eclipse.cdt.core.cnature"; + newNatures[newNatures.length - 1] = "org.eclipse.cdt.core.ccnature";//CCProjectNature.CC_NATURE_ID; + + description.setNatureIds(newNatures); + + // make sure no build specs added + description.setBuildSpec(buildSpecs); + + editProject.setDescription(description, null); + } + catch (Exception e) + { + + } + } + */ + /* + public void addJavaSupport(IProject editProject) + { + + try + { + IProjectDescription description = editProject.getDescription(); + String[] natures = description.getNatureIds(); + ICommand[] buildSpecs = description.getBuildSpec(); + + String[] newNatures = new String[natures.length + 1]; + + // copy all previous natures + for (int i = 0; i < natures.length; i++) + { + newNatures[i] = natures[i]; + } + + newNatures[newNatures.length - 1] = JavaCore.NATURE_ID; + + description.setNatureIds(newNatures); + description.setBuildSpec(buildSpecs); + + + + editProject.setDescription(description, null); + + + IJavaProject proj = JavaCore.create(editProject); + IPath outputLocation = proj.getOutputLocation(); + + + // classpath + IClasspathEntry[] classpath= new IClasspathEntry[1]; + + IPath jdkLoc = new Path("org.eclipse.jdt.launching.JRE_CONTAINER"); + ClasspathEntry jreEntry = new ClasspathEntry( + IPackageFragmentRoot.K_BINARY, + IClasspathEntry.CPE_CONTAINER, + jdkLoc, + ClasspathEntry.INCLUDE_ALL, + ClasspathEntry.EXCLUDE_NONE, + null, // source attachment + null, // source attachment root + null, // specific output folder + false); + classpath[0]=jreEntry; + + + proj.setRawClasspath(classpath, outputLocation, null); + + ((JavaProject)proj).deconfigure(); + + } + catch (Exception e) + { + e.printStackTrace(); + } + } + */ + + + /** + * Get the location of the project used for remote editing + */ + public IPath getRemoteEditProjectLocation() + { + //if (!doesRemoteEditProjectExist()) + // return null; + // DKM - originally return null if it doesn't exist + // but looks like lots of calls reference this expected to get something back + // so I'll let project creation happen here + + return getRemoteEditProject().getLocation(); + } + + /** + * Get the absolute path of the project used for remote editing + */ + public String getRemoteEditProjectAbsolutePath() + { + return getRemoteEditProjectLocation().makeAbsolute().toOSString(); + } + + protected int caculateCacheSize() + { + if (!doesRemoteEditProjectExist()) + { + return 0; + } + IProject project = getRemoteEditProject(); + String path = project.getLocation().toOSString(); + File file = new File(path); + return calculateSize(file); + } + + private int calculateSize(File file) + { + int size = 0; + if (file.isFile()) + { + size = (int) file.length(); + } + else if (file.isDirectory()) + { + File[] children = file.listFiles(); + for (int i = 0; i < children.length; i++) + { + size += calculateSize(children[i]); + } + } + + return size; + } + + protected IFile getLeastRecentlyChangedFile(List deletedList) + { + // if no project exists, then no file exists + if (!doesRemoteEditProjectExist()) + return null; + + IProject project = getRemoteEditProject(); + + IFile result = getLeastRecentlyChangedFile(project, deletedList); + deletedList.add(result); + return result; + } + + private IFile getLeastRecentlyChangedFile(IContainer file, List deletedList) + { + + IFile result = null; + try + { + IResource[] children = file.members(); + for (int i = 0; i < children.length; i++) + { + IFile candidate = null; + IResource child = children[i]; + if (child instanceof IFolder) + { + candidate = getLeastRecentlyChangedFile((IFolder) child, deletedList); + } + else + { + candidate = (IFile) child; + } + + if (candidate != null && !deletedList.contains(candidate) && !candidate.getName().startsWith(".") && !isFileInUse(candidate, true)) + { + if (result == null) + { + result = candidate; + } + else if (candidate.getLocation().toFile().lastModified() < result.getLocation().toFile().lastModified()) + { + result = candidate; + } + } + } + } + catch (Exception e) + { + } + return result; + } + + public ISystemEditableRemoteObject getEditableFor(IFile fileToDelete, boolean quickCheck) + { + SystemIFileProperties properties = new SystemIFileProperties(fileToDelete); + Object object = properties.getRemoteFileObject(); + if (object != null) + { + ISystemEditableRemoteObject editableFile = (ISystemEditableRemoteObject) object; + return editableFile; + } + else if (!quickCheck) + { + // no object in memory, so try to reconstruct it from ids + String subsystemStr = properties.getRemoteFileSubSystem(); + String pathStr = properties.getRemoteFilePath(); + if (subsystemStr != null && pathStr != null) + { + ISubSystem subsystem = SystemPlugin.getTheSystemRegistry().getSubSystem(subsystemStr); + if (subsystem != null) + { + Object rmtObject = null; + try + { + rmtObject = subsystem.getObjectWithAbsoluteName(pathStr); + } + catch (Exception e) + { + return null; + } + if (rmtObject != null && rmtObject instanceof IAdaptable) + { + ISystemRemoteElementAdapter adapter = (ISystemRemoteElementAdapter) ((IAdaptable) rmtObject).getAdapter(ISystemRemoteElementAdapter.class); + if (adapter != null) + { + return adapter.getEditableRemoteObject(rmtObject); + } + } + } + } + } + return null; + } + + public class DeleteFileRunnable implements Runnable + { + private IFile _theFile; + public DeleteFileRunnable(IFile theFile) + { + _theFile = theFile; + } + + public void run() + { + if (!inUse()) + { + System.out.println("deleting " + _theFile.getName()); + _theFile.getLocation().toFile().delete(); + } + } + + public boolean inUse() + { + // if no temp files project, not in use + if (!doesRemoteEditProjectExist()) + return false; + + IProject tempFilesProject = SystemRemoteEditManager.getDefault().getRemoteEditProject(); + IWorkbenchWindow activeWindow = SystemBasePlugin.getActiveWorkbenchWindow(); + IWorkbenchPage activePage = activeWindow.getActivePage(); + + IEditorReference[] activeReferences = activePage.getEditorReferences(); + + IEditorPart part; + + for (int k = 0; k < activeReferences.length; k++) + { + part = activeReferences[k].getEditor(true); + + if (part != null) + { + IEditorInput editorInput = part.getEditorInput(); + + if (editorInput instanceof IFileEditorInput) + { + IFile file = ((IFileEditorInput) editorInput).getFile(); + if (file.equals(_theFile)) + { + System.out.println(file.getName() + " is in use"); + return true; + } + } + } + + } + return false; + } + } + + public boolean isFileInUse(IFile fileToDelete, boolean quickCheck) + { + // first check for dirty flag + SystemIFileProperties properties = new SystemIFileProperties(fileToDelete); + boolean isDirty = properties.getDirty(); + if (isDirty) + { + return true; + } + else + { + + ISystemEditableRemoteObject editable = getEditableFor(fileToDelete, quickCheck); + if (editable != null && quickCheck) + { + return true; + } + + if (editable != null) + { + try + { + boolean result = editable.checkOpenInEditor() == ISystemEditableRemoteObject.NOT_OPEN; + if (!result) + { + return !result; + } + } + catch (Exception e) + { + } + } + } + return false; + } + + protected void cleanupCache() + { + + IPreferenceStore store = SystemPlugin.getDefault().getPreferenceStore(); + boolean enableMaxSize = store.getBoolean(ISystemPreferencesConstants.LIMIT_CACHE); + if (enableMaxSize) + { + int max = Integer.parseInt(ISystemPreferencesConstants.DEFAULT_MAX_CACHE_SIZE) * 1000000; + + // get the cache limit + try { + String maxSize = store.getString(ISystemPreferencesConstants.MAX_CACHE_SIZE); + + if (maxSize != null && !maxSize.equals("")) { + max = Integer.parseInt(maxSize) * 1000000; + } + } + catch (NumberFormatException nfe) { + SystemBasePlugin.logError("Could not get max cache size", nfe); + max = Integer.parseInt(ISystemPreferencesConstants.DEFAULT_MAX_CACHE_SIZE) * 1000000; + } + + try { + + // get the current cache size + int currentSize = caculateCacheSize(); + if (currentSize > max) + { + // determine what to get rid of + int delta = currentSize - max; + + List deletedList = new ArrayList(); + while (delta > 0) + { + + // need to purge delta from the cache + IFile leastRecent = getLeastRecentlyChangedFile(deletedList); + if (leastRecent != null) + { + + File theFile = leastRecent.getLocation().toFile(); + + int sizeSaved = (int) theFile.length(); + Display.getDefault().asyncExec(new DeleteFileRunnable(leastRecent)); + + // delete file + delta -= sizeSaved; + } + else + { + delta = 0; + } + } + } + } + catch (Exception e) + { + SystemBasePlugin.logError("Error occured trying to clean cache", e); + // e.printStackTrace(); + } + } + } + + /** + * Refresh the remote edit project + */ + public void refreshRemoteEditProject() + { + // no temp files project, then nothing to refresh + if (!doesRemoteEditProjectExist()) + { + return; + } + try + { + IProject project = getRemoteEditProject(); + if (!project.getWorkspace().isTreeLocked()) + { + cleanupCache(); + project.refreshLocal(IResource.DEPTH_INFINITE, null); + } + } + catch (Exception e) + { + SystemBasePlugin.logError("Error refreshing remote edit project", e); + } + } + + /** + * Refresh the remote edit project + */ + public void refreshRemoteEditContainer(IContainer parent) + { + // no project exists, then nothing to refresh + if (!doesRemoteEditProjectExist()) + return; + + try + { + + IProject project = getRemoteEditProject(); + if (!project.getWorkspace().isTreeLocked()) + { + cleanupCache(); + parent.refreshLocal(IResource.DEPTH_ONE, null); + } + } + catch (Exception e) + { + SystemBasePlugin.logError("Error refreshing remote edit project", e); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarker.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarker.java new file mode 100644 index 00000000000..d32e84f9b14 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarker.java @@ -0,0 +1,284 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.Map; + +/** + * This class is an internal implementation of the ISystemRemoteMarker interface. + * It is not intended to be implemented by clients. + */ +public class SystemRemoteMarker implements ISystemRemoteMarker { + + + + /** + * Resource with which this marker is associated. + */ + protected ISystemRemoteResource resource; + + /** + * The marker id. + */ + protected long id; + + /** + * Constructor for SystemRemoteMarker. + */ + public SystemRemoteMarker(ISystemRemoteResource resource, long id) { + this.resource = resource; + this.id = id; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#delete() + */ + public void delete() { + SystemRemoteMarkerManager.getInstance().removeMarker(getResource(), getId()); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#equals(Object) + */ + public boolean equals(Object object) { + + if (!(object instanceof ISystemRemoteMarker)) { + return false; + } + else { + ISystemRemoteMarker other = (ISystemRemoteMarker)object; + return (id == other.getId()) && (resource.equals(other.getResource())); + } + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#exists() + */ + public boolean exists() { + return getInfo() != null; + } + + /** + * Get the marker info. + * @return the marker info. + */ + private SystemRemoteMarkerInfo getInfo() { + return SystemRemoteMarkerManager.getInstance().findMarkerInfo(getResource(), getId()); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttribute(String) + */ + public Object getAttribute(String attributeName) { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return null; + } + + return info.getAttribute(attributeName); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttribute(String, int) + */ + public int getAttribute(String attributeName, int defaultValue) { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return defaultValue; + } + + Object value = info.getAttribute(attributeName); + + if ((value != null) && (value instanceof Integer)) { + return ((Integer)value).intValue(); + } + + return defaultValue; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttribute(String, String) + */ + public String getAttribute(String attributeName, String defaultValue) { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return defaultValue; + } + + Object value = info.getAttribute(attributeName); + + if ((value != null) && (value instanceof String)) { + return (String)value; + } + + return defaultValue; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttribute(String, boolean) + */ + public boolean getAttribute(String attributeName, boolean defaultValue) { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return defaultValue; + } + + Object value = info.getAttribute(attributeName); + + if ((value != null) && (value instanceof Integer)) { + return ((Boolean)value).booleanValue(); + } + + return defaultValue; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttributes() + */ + public Map getAttributes() { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return null; + } + + return info.getAttributes(); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getAttributes(String[]) + */ + public Object[] getAttributes(String[] attributeNames) { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return new Object[0]; + } + + return info.getAttributes(attributeNames); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getCreationTime() + */ + public long getCreationTime() { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return -1; + } + + return info.getCreationTime(); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getId() + */ + public long getId() { + return id; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getResource() + */ + public ISystemRemoteResource getResource() { + return resource; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#getType() + */ + public String getType() { + SystemRemoteMarkerInfo info = getInfo(); + + if (info == null) { + return null; + } + + return info.getType(); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#isSubtypeOf(String) + */ + public boolean isSubtypeOf(String superType) { + String type = getType(); + + if (type == null) { + return false; + } + + return SystemRemoteMarkerManager.getInstance().getCache().isSubtype(type, superType); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#setAttribute(String, int) + */ + public void setAttribute(String attributeName, int value) { + setAttribute(attributeName, new Integer(value)); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#setAttribute(String, Object) + */ + public void setAttribute(String attributeName, Object value) { + SystemRemoteMarkerManager manager = SystemRemoteMarkerManager.getInstance(); + SystemRemoteMarkerInfo info = getInfo(); + info.setAttribute(attributeName, value); + + if (manager.isPersistent(info)) { + ((SystemRemoteResource)resource).getResourceInfo().set(ISystemRemoteCoreConstants.M_MARKERS_DIRTY); // need to change this + } + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#setAttribute(String, boolean) + */ + public void setAttribute(String attributeName, boolean value) { + setAttribute(attributeName, value ? Boolean.TRUE : Boolean.FALSE); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#setAttributes(String[], Object[]) + */ + public void setAttributes(String[] attributeNames, Object[] values) { + SystemRemoteMarkerManager manager = SystemRemoteMarkerManager.getInstance(); + SystemRemoteMarkerInfo info = getInfo(); + info.setAttributes(attributeNames, values); + + if (manager.isPersistent(info)) { + ((SystemRemoteResource)resource).getResourceInfo().set(ISystemRemoteCoreConstants.M_MARKERS_DIRTY); // need to change this + } + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarker#setAttributes(Map) + */ + public void setAttributes(Map attributes) { + SystemRemoteMarkerManager manager = SystemRemoteMarkerManager.getInstance(); + SystemRemoteMarkerInfo info = getInfo(); + info.setAttributes(attributes); + + if (manager.isPersistent(info)) { + ((SystemRemoteResource)resource).getResourceInfo().set(ISystemRemoteCoreConstants.M_MARKERS_DIRTY); // need to change this + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerInfo.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerInfo.java new file mode 100644 index 00000000000..fe1c21c038f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerInfo.java @@ -0,0 +1,233 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.HashMap; +import java.util.Map; + +/** + * Objects of this type contain marker information. + */ +public class SystemRemoteMarkerInfo implements ISystemRemoteMarkerSetElement, Cloneable { + + + + // undefined static id + protected static final long UNDEFINED_ID = -1; + + // marker identifier + protected long id = UNDEFINED_ID; + + // marker type + protected String type = null;; + + // marker attributes + protected Map attributes = null; + + // marker creation type + protected long creationTime = 0; + + /** + * Constructor for SystemRemoteMarkerInfo. + */ + public SystemRemoteMarkerInfo() { + super(); + } + + /** + * Set the marker id. + * @param the id + */ + public void setId(long id) { + this.id = id; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteMarkerSetElement#getId() + */ + public long getId() { + return id; + } + + /** + * Set the type. + * @param the marker type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Get the type. + * @return the marker type + */ + public String getType() { + return type; + } + + /** + * Set the attributes. + * @param the attributes + */ + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + /** + * Get the attributes. + * @return the attributes + */ + public Map getAttributes() { + return getAttributes(true); + } + + /** + * Get the attributes. + * @param specify whether to return a copy or the actual map + * @return the attribute map + */ + public Map getAttributes(boolean makeCopy) { + + if (attributes == null) { + return null; + } + + if (makeCopy) { + HashMap newAttributes = new HashMap(); + newAttributes.putAll(attributes); + return newAttributes; + } + else { + return attributes; + } + } + + /** + * Set the creation time. + * @param the creation time + */ + public void setCreationTime(long creationTime) { + this.creationTime = creationTime; + } + + /** + * Get the creation time. + * @return the creation time + */ + public long getCreationTime() { + return creationTime; + } + + /** + * @see java.lang.Object#clone() + */ + protected Object clone() throws CloneNotSupportedException { + SystemRemoteMarkerInfo copy = (SystemRemoteMarkerInfo)(super.clone()); + copy.setAttributes(getAttributes()); + return copy; + } + + /** + * Get attribute values given the attribute names. + * @param the array of attribute names + * @return the array of attribute values + */ + public Object[] getAttributes(String[] attributeNames) { + Object[] result = new Object[attributeNames.length]; + + for (int i = 0; i < attributeNames.length; i++) + result[i] = getAttribute(attributeNames[i]); + + return result; + } + + /** + * Get the attribute value given the attribute name. + * @param the attribute name + * @return the attribute value + */ + public Object getAttribute(String attributeName) { + + if (attributes == null) { + return null; + } + else { + return attributes.get(attributeName); + } + } + + /** + * Checks if attribute value is valid. + * @param the attribute value + * @return true if value is null, or a String, or an Integer, or a Boolean + */ + protected static boolean isValidAttributeValue(Object value) { + return (value == null || value instanceof String || value instanceof Integer || value instanceof Boolean); + } + + /** + * Set the value of an attribute. + * @param the attribute name + * @param the value of the attribute + */ + public void setAttribute(String attributeName, Object value) { + + if (!isValidAttributeValue(value)) { + return; + } + + if (attributes == null) { + + if (value == null) { + return; + } + else { + attributes = new HashMap(); + attributes.put(attributeName, value); + } + } + else { + + if (value == null) { + attributes.remove(attributeName); + + if (attributes.isEmpty()) { + attributes = null; + } + } + else { + attributes.put(attributeName, value); + } + } + } + + /** + * Set the values of an array of attributes + * @param the attribute names + * @param the attribute values + */ + public void setAttributes(String[] attributeNames, Object[] values) { + + if (!(attributeNames.length == values.length)) { + return; + } + + for (int i = 0; i < attributeNames.length; i++) { + setAttribute(attributeNames[i], values[i]); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerManager.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerManager.java new file mode 100644 index 00000000000..14dff80b94a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerManager.java @@ -0,0 +1,400 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * This singleton class manages all remote markers. + */ +public class SystemRemoteMarkerManager implements ISystemRemoteManager { + + + + private static SystemRemoteMarkerManager instance; + + // cache of marker type definitions + private SystemRemoteMarkerTypeDefinitionCache cache; + + // the next marker id + private long nextMarkerId = 0; + + // constant to indicate no marker infos + private static final SystemRemoteMarkerInfo[] NO_MARKER_INFO = new SystemRemoteMarkerInfo[0]; + + // constant to indicate no markers + private static final ISystemRemoteMarker[] NO_MARKER = new ISystemRemoteMarker[0]; + + /** + * Constructor for SystemRemoteMarkerManager. + */ + private SystemRemoteMarkerManager() { + super(); + cache = new SystemRemoteMarkerTypeDefinitionCache(); + } + + /** + * Get the singleton instance. + * @return the manager object + */ + public static SystemRemoteMarkerManager getInstance() { + + if (instance == null) { + instance = new SystemRemoteMarkerManager(); + } + + return instance; + } + + /** + * Get the cache. + * @return the cache + */ + public SystemRemoteMarkerTypeDefinitionCache getCache() { + return cache; + } + + /** + * Get the next marker id. + * @return the next marker id + */ + public long getNextMarkerId() { + return nextMarkerId++; + } + + /** + * Adds the given markers to the given resource. + * @param the resource + * @param the marker infos + */ + public void add(ISystemRemoteResource resource, SystemRemoteMarkerInfo[] newMarkers) { + + if (newMarkers.length == 0) + return; + + SystemRemoteResource target = (SystemRemoteResource) resource; + SystemRemoteResourceInfo info = target.getResourceInfo(); + + if (info == null) { + return; + } + + // set the flag to indicate that the resource's markers have changed + if (isPersistent(newMarkers)) + info.set(ISystemRemoteCoreConstants.M_MARKERS_DIRTY); + + SystemRemoteMarkerSet markers = info.getMarkers(); + + if (markers == null) { + markers = new SystemRemoteMarkerSet(newMarkers.length); + } + + basicAdd(resource, markers, newMarkers); + + if (!markers.isEmpty()) { + info.setMarkers(markers); + } + } + + /** + * Adds the new markers to the given set of markers for the given resource. + * @param the resource + * @param the set of markers for the resource + * @param the new marker infos + */ + private void basicAdd(ISystemRemoteResource resource, SystemRemoteMarkerSet markers, SystemRemoteMarkerInfo[] newMarkers) { + + for (int i = 0; i < newMarkers.length; i++) { + + SystemRemoteMarkerInfo newMarker = newMarkers[i]; + newMarker.setId(getNextMarkerId()); + markers.add(newMarker); + } + } + + /** + * Removes a marker. + * @param the resource. + * @param the marker id + */ + public void removeMarker(ISystemRemoteResource resource, long id) { + SystemRemoteMarkerInfo markerInfo = findMarkerInfo(resource, id); + + if (markerInfo == null) + return; + + SystemRemoteResourceInfo info = ((SystemRemoteResource)(resource)).getResourceInfo(); + + if (info == null) { + return; + } + + SystemRemoteMarkerSet markers = info.getMarkers(); + int size = markers.size(); + markers.remove(markerInfo); + + // if that was the last marker remove the set to save space. + if (markers.size() == 0) { + info.setMarkers(null); + } + + // if we actually did remove a marker, post a delta for the change. + if (markers.size() != size) { + + if (isPersistent(markerInfo)) { + info.set(ISystemRemoteCoreConstants.M_MARKERS_DIRTY); + } + } + } + + /** + * Finds a marker info given a resource, and the marker id. + * @param the resource. + * @param the marker id + * @return the marker info + */ + public SystemRemoteMarkerInfo findMarkerInfo(ISystemRemoteResource resource, long id) { + SystemRemoteResourceInfo info = ((SystemRemoteResource)(resource)).getResourceInfo(); + + if (info == null) { + return null; + } + + SystemRemoteMarkerSet markers = info.getMarkers(); + + if (markers == null) { + return null; + } + + return (SystemRemoteMarkerInfo)(markers.get(id)); + } + + /** + * Removes markers of the given type, and optionally all the subtypes, from + * the given resource. + * @param the resource + * @param the type + * @param flag indicating whether to include subtypes + */ + public void removeMarkers(ISystemRemoteResource resource, String type, boolean includeSubtypes) { + SystemRemoteResourceInfo info = ((SystemRemoteResource)(resource)).getResourceInfo(); + + if (info == null) { + return; + } + + SystemRemoteMarkerSet markers = info.getMarkers(); + + if (markers == null) { + return; + } + + ISystemRemoteMarkerSetElement[] matching; + + // if type is null, then we want all the markers + // otherwise we need a subset + if (type == null) { + matching = markers.elements(); + info.setMarkers(null); + } + else { + matching = basicFindMatching(markers, type, includeSubtypes); + + // if nothing matches, simply return + if (matching.length == 0) { + return; + } + else { + markers.removeAll(matching); + + // if the marker set is empty, then make it null to save memory + if (markers.size() == 0) { + info.setMarkers(null); + } + } + } + } + + /** + * Returns the markers in the given set of markers which match the given type, + * and optionally including subtypes. + * @param the marker set + * @param the type + * @param flag indicating whether to include subtypes + */ + private SystemRemoteMarkerInfo[] basicFindMatching(SystemRemoteMarkerSet markers, String type, boolean includeSubtypes) { + int size = markers.size(); + + if (size <= 0) { + return NO_MARKER_INFO; + } + + List result = new ArrayList(size); + + ISystemRemoteMarkerSetElement[] elements = markers.elements(); + + for (int i = 0; i < elements.length; i++) { + SystemRemoteMarkerInfo marker = (SystemRemoteMarkerInfo)(elements[i]); + + // if the type is null, then we are looking for all types of markers + if (type == null) { + result.add(marker); + } + else { + if (includeSubtypes) { + + if (cache.isSubtype(marker.getType(), type)) { + result.add(marker); + } + } + else { + + if (marker.getType().equals(type)) { + result.add(marker); + } + } + } + } + + size = result.size(); + + if (size <= 0) { + return NO_MARKER_INFO; + } + + return (SystemRemoteMarkerInfo[])(result.toArray(new SystemRemoteMarkerInfo[size])); + } + + /** + * Returns the marker with the given id or null if none is found. + * @param the resource + * @param the id of the marker to find + * @return the marker, or null if none s found. + */ + public ISystemRemoteMarker findMarker(ISystemRemoteResource resource, long id) { + SystemRemoteMarkerInfo info = findMarkerInfo(resource, id); + return info == null ? null : new SystemRemoteMarker(resource, info.getId()); + } + + /** + * Returns all markers of the specified type on the given target, and optionally the subtypes as well. + * Passing null for the type specifies a matching target for all types. + * @param the resource + * @param the type + * @param flag indicating whether to include subtypes + */ + public ISystemRemoteMarker[] findMarkers(ISystemRemoteResource resource, String type, boolean includeSubtypes) { + SystemRemoteResourceInfo info = ((SystemRemoteResource)resource).getResourceInfo(); + + if (info == null) { + return NO_MARKER; + } + + ArrayList result = new ArrayList(); + + SystemRemoteMarkerSet markers = info.getMarkers(); + + // add the matching markers for this resource + if (markers != null) { + + ISystemRemoteMarkerSetElement[] matching; + + if (type == null) { + matching = markers.elements(); + } + else { + matching = basicFindMatching(markers, type, includeSubtypes); + } + + buildMarkers(resource, matching, result); + } + + return (ISystemRemoteMarker[])(result.toArray(new ISystemRemoteMarker[result.size()])); + } + + /** + * Adds the markers on the given target which match the specified type to the list. + * @param the target resource + * @param the marker elements + * @param the list to add to + */ + private void buildMarkers(ISystemRemoteResource resource, ISystemRemoteMarkerSetElement[] markers, ArrayList list) { + + if (markers.length == 0) { + return; + } + + list.ensureCapacity(list.size() + markers.length); + + for (int i = 0; i < markers.length; i++) { + list.add(new SystemRemoteMarker(resource, ((SystemRemoteMarkerInfo)markers[i]).getId())); + } + } + + /** + * Returns whether marker info is persistent. + * @param the marker info + * @return true if the given marker represented by this info is persistent, + * and false otherwise. + */ + public boolean isPersistent(SystemRemoteMarkerInfo info) { + return cache.isPersistent(info.getType()); + } + + /** + * Returns whether given marker is persistent. + * @param the marker + * @return true if the given marker is persistent, and false + * otherwise. + */ + public boolean isPersistent(ISystemRemoteMarker marker) { + return cache.isPersistent(marker.getType()); + } + + /** + * Returns whether any of the marker infos are persistent. + * @param the marker infos + * @return true if the a marker represented by any of the infos is persistent, + * and false otherwise. + */ + public boolean isPersistent(SystemRemoteMarkerInfo[] infos) { + + for (int i = 0; i < infos.length; i++) { + + if (cache.isPersistent(infos[i].getType())) { + return true; + } + } + + return false; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteManager#startup(IProgressMonitor) + */ + public void startup(IProgressMonitor monitor) { + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteManager#shutdown(IProgressMonitor) + */ + public void shutdown(IProgressMonitor monitor) { + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerSet.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerSet.java new file mode 100644 index 00000000000..da8ef4d10d7 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerSet.java @@ -0,0 +1,354 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * This class represents a set of markers. + */ +public class SystemRemoteMarkerSet { + + + + /** + * constant indicating the minimum size + */ + private static final int MINIMUM_SIZE = 5; + + /** + * Number of elements in the set + */ + private int elementCount = 0; + + /** + * Array of elements in the set + */ + private ISystemRemoteMarkerSetElement[] elements; + + /** + * Constructor for SystemRemoteMarkerSet. + */ + public SystemRemoteMarkerSet() { + this(MINIMUM_SIZE); + } + + /** + * Constructor for SystemRemoteMarkerSet. + * @param the initial capacity + */ + public SystemRemoteMarkerSet(int capacity) { + super(); + this.elements = new ISystemRemoteMarkerSetElement[Math.max(MINIMUM_SIZE, capacity * 2)]; + } + + /** + * Add an element to the set. + * @param the element to add to the set + */ + public void add(ISystemRemoteMarkerSetElement element) { + + if (element == null) + return; + + int hash = hashFor(element.getId()) % elements.length; + + // search for an empty slot at the end of the array + for (int i = hash; i < elements.length; i++) { + + if (elements[i] == null) { + elements[i] = element; + elementCount++; + + // grow if necessary + if (shouldGrow()) { + expand(); + } + + return; + } + } + + // search for an empty slot at the beginning of the array + for (int i = 0; i < hash - 1; i++) { + + if (elements[i] == null) { + elements[i] = element; + elementCount++; + + // grow if necessary + if (shouldGrow()) { + expand(); + } + + return; + } + } + + // if we didn't find a free slot, then try again with the expanded set + expand(); + add(element); + } + + /** + * Add multiple elements. + * @param the elements to add to the set + */ + public void addAll(ISystemRemoteMarkerSetElement[] elements) { + + for (int i = 0; i < elements.length; i++) { + add(elements[i]); + } + } + + /** + * Returns whether the set contains an element with the given id. + * @param the id to search for + * @return true if there is an element with the given id, false otherwise + */ + public boolean contains(long id) { + return get(id) != null; + } + + /** + * Get the elements in the set as an array. + * @return an array of elements that are in the set + */ + public ISystemRemoteMarkerSetElement[] elements() { + ISystemRemoteMarkerSetElement[] result = new ISystemRemoteMarkerSetElement[elementCount]; + + int j = 0; + + for (int i = 0; i < elements.length; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element != null) { + result[j] = element; + j++; + } + } + + return result; + } + + /** + * Doubles the size of the internal array, and rehash all the values + */ + private void expand() { + ISystemRemoteMarkerSetElement[] array = new ISystemRemoteMarkerSetElement[elements.length * 2]; + + int maxArrayIndex = array.length - 1; + + for (int i = 0; i < elements.length; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element != null) { + + int hash = hashFor(element.getId()) % array.length; + + while (array[hash] != null) { + + hash++; + + if (hash > maxArrayIndex) { + hash = 0; + } + } + + array[hash] = element; + } + } + + elements = array; + } + + /** + * Returns the set element with the given id, or null if none + * is found. + * @param the id to search for + * @return the element, if found, or null + */ + public ISystemRemoteMarkerSetElement get(long id) { + + if (elementCount == 0) { + return null; + } + + int hash = hashFor(id) % elements.length; + + // search the last half of the array + for (int i = hash; i < elements.length; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element == null) { + return null; + } + + if (element.getId() == id) { + return element; + } + } + + // search the beginning of the array + for (int i = 0; i < hash - 1; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element == null) { + return null; + } + + if (element.getId() == id) { + return element; + } + } + + // no element found, so return null + return null; + } + + /** + * Hash key for the id. + * @param the id + * @return the hash value + */ + private int hashFor(long id) { + return Math.abs((int) id); + } + + /** + * Returns if the set is empty. + * @return true if the set is empty, false otherwise. + */ + public boolean isEmpty() { + return elementCount == 0; + } + + /** + * Does a rehash when the element from the given index is removed. + * @param the index of the element removed. + */ + private void rehashTo(int anIndex) { + int target = anIndex; + int index = anIndex + 1; + + if (index >= elements.length) { + index = 0; + } + + ISystemRemoteMarkerSetElement element = elements[index]; + + while (element != null) { + + int hashIndex = hashFor(element.getId()) % elements.length; + boolean match; + + if (index < target) { + match = !(hashIndex > target || hashIndex <= index); + } + else { + match = !(hashIndex > target && hashIndex <= index); + } + if (match) { + elements[target] = element; + target = index; + } + + index++; + + if (index >= elements.length) { + index = 0; + } + + element = elements[index]; + } + + elements[target] = null; + } + + /** + * Removes an element with the given id from the set. + * @param the id of the element to remove. + */ + public void remove(long id) { + int hash = hashFor(id) % elements.length; + + for (int i = hash; i < elements.length; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element == null) { + return; + } + if (element.getId() == id) { + rehashTo(i); + elementCount--; + } + } + + for (int i = 0; i < hash - 1; i++) { + + ISystemRemoteMarkerSetElement element = elements[i]; + + if (element == null) { + return; + } + if (element.getId() == id) { + rehashTo(i); + elementCount--; + } + } + } + + /** + * Removes the given element from the set. Uses the element id + * to search for the element in the set. + * @param the element + */ + public void remove(ISystemRemoteMarkerSetElement element) { + remove(element.getId()); + } + + /** + * Removes all of the elements in the given array from the set. + * @param the array of elements to remove + */ + public void removeAll(ISystemRemoteMarkerSetElement[] elements) { + + for (int i = 0; i < elements.length; i++) { + remove(elements[i]); + } + } + + /** + * Returns whether the internal storage should grow. Currently, returns true + * if internal array is more that 75% full. + * @return true if the internal storage should grow, false otherwise + */ + private boolean shouldGrow() { + return elementCount > elements.length * 0.75; + } + + /** + * Returns the number of elements in the set. + * @return the number of elements in the set. + */ + public int size() { + return elementCount; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinition.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinition.java new file mode 100644 index 00000000000..ccc7f01c2dd --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinition.java @@ -0,0 +1,141 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtension; + +/** + * This class represents a marker type definition. + */ +public class SystemRemoteMarkerTypeDefinition { + + + + protected String type = null; + protected String name = null; + protected boolean isPersistent = false; + protected Set superTypes = null; + protected Set attributeNames = null; + + /** + * Constructor for SystemRemoteMarkerTypeDefinition. + */ + public SystemRemoteMarkerTypeDefinition(IExtension ext) { + super(); + this.type = ext.getUniqueIdentifier(); + this.name = ext.getLabel(); + process(ext); + } + + /** + * Processes the extension + * @param the extension + */ + private void process(IExtension ext) { + Set types = null; + Set attributes = null; + IConfigurationElement[] elements = ext.getConfigurationElements(); + + for (int i = 0; i < elements.length; i++) { + IConfigurationElement element = elements[i]; + + // supertype + if (element.getName().equalsIgnoreCase("super")) { + String type = element.getAttribute("type"); + + if (type != null) { + + if (types == null) { + types = new HashSet(3); + } + + types.add(type); + } + } + + // attribute name + if (element.getName().equalsIgnoreCase("attribute")) { + String name = element.getAttribute("name"); + + if (name != null) { + + if (attributes == null) { + attributes = new HashSet(3); + } + + attributes.add(name); + } + } + + // persistence + if (element.getName().equalsIgnoreCase("persistent")) { + String bool = element.getAttribute("value"); + + if (bool != null) { + this.isPersistent = (new Boolean(bool)).booleanValue(); + } + } + } + + this.superTypes = types; + this.attributeNames = attributes; + } + + /** + * Get the type. + * @return the type + */ + public String getType() { + return type; + } + + /** + * Get the name. + * @return the name + */ + public String getName() { + return name; + } + + /** + * Returns whether it is persistent. + * @return true if persistent, false othwerwise + */ + public boolean isPersistent() { + return isPersistent; + } + + /** + * Get super types. + * @return the super types + */ + public Set getSuperTypes() { + return superTypes; + } + + /** + * Get the attribute names. + * @return the attribute names + */ + public Set getAttributeNames() { + return attributeNames; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinitionCache.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinitionCache.java new file mode 100644 index 00000000000..55df65abac1 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteMarkerTypeDefinitionCache.java @@ -0,0 +1,123 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.eclipse.core.runtime.IExtension; +import org.eclipse.core.runtime.IExtensionPoint; +import org.eclipse.core.runtime.Platform; +import org.eclipse.rse.core.SystemPlugin; + + +/** + * This class is a cache of all marker type definitions. + */ +public class SystemRemoteMarkerTypeDefinitionCache { + + + + // cache of marker definitions + protected HashMap definitions; + + // cache of marker type hierarchies + protected HashMap lookup; + + /** + * Constructor for SystemRemoteMarkerTypeDefinitionCache. + */ + public SystemRemoteMarkerTypeDefinitionCache() { + super(); + initializeCache(); + } + + /** + * Initialize the cache. + */ + private void initializeCache() { + loadDefinitions(); + lookup = new HashMap(definitions.size()); + + for (Iterator i = definitions.keySet().iterator(); i.hasNext();) { + computeSuperTypes((String)(i.next())); + } + } + + /** + * Load marker type definitions. + */ + private void loadDefinitions() { + IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(SystemPlugin.PLUGIN_ID, ISystemRemoteMarker.EXTENSION_POINT_ID); + IExtension[] types = point.getExtensions(); + definitions = new HashMap(types.length); + + for (int i = 0; i < types.length; i++) { + definitions.put(types[i].getUniqueIdentifier(), new SystemRemoteMarkerTypeDefinition(types[i])); + } + } + + /** + * Compute the super types given a marker id. + * @param a marker id + */ + private void computeSuperTypes(String id) { + Set entry = new HashSet(5); + List queue = new ArrayList(5); + queue.add(id); + + while (!queue.isEmpty()) { + String type = (String)(queue.remove(0)); + entry.add(type); + SystemRemoteMarkerTypeDefinition def = (SystemRemoteMarkerTypeDefinition)(definitions.get(type)); + + if (def != null) { + Set newEntries = def.getSuperTypes(); + + if (newEntries != null) + queue.addAll(newEntries); + } + } + + lookup.put(id, entry); + } + + /** + * Returns whether the given marker type is defined to be persistent. + * @param the marker type + * @return true if marker type is persistent, false otherwise + */ + public boolean isPersistent(String type) { + SystemRemoteMarkerTypeDefinition def = (SystemRemoteMarkerTypeDefinition)(definitions.get(type)); + return (def != null) && (def.isPersistent()); + } + + /** + * Returns whether the given type is a subtype of the given supertype. + * @param a marker type + * @param another marker type + * @return true if type is a subtype of supertype, false otherwise + */ + public boolean isSubtype(String type, String superType) { + Set entry = (Set)(lookup.get(type)); + return (entry != null) && (entry.contains(superType)); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemotePath.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemotePath.java new file mode 100644 index 00000000000..a37712890db --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemotePath.java @@ -0,0 +1,96 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * A default implementation of a remote path. + */ +public class SystemRemotePath implements ISystemRemotePath { + + + + public static final ISystemRemotePath ROOT = new SystemRemotePath("", "", "/"); + + protected String profileName; + protected String connectionName; + protected String path; + + /** + * Constructor for SystemRemotePath. + * @param profile name + * @param connection name + * @param path + */ + public SystemRemotePath(String profileName, String connectionName, String path) { + super(); + setProfileName(profileName); + setConnectionName(connectionName); + setPath(path); + } + + /** + * Set the profile name. + * @param the profile name + */ + public void setProfileName(String profileName) { + this.profileName = profileName; + } + + /** + * Set the connection name. + * @param the connection name + */ + public void setConnectionName(String connectionName) { + this.connectionName = connectionName; + } + + /** + * Set the remote path. + * @param the path + */ + public void setPath(String path) { + this.path = path; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemotePath#getProfileName() + */ + public String getProfileName() { + return profileName; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemotePath#getConnectionName() + */ + public String getConnectionName() { + return connectionName; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemotePath#getPath() + */ + public String getPath() { + return path; + } + + /** + * @see java.lang.Object#equals(Object) + */ + public boolean equals(Object obj) { + return (profileName.equalsIgnoreCase(profileName)) && (connectionName.equalsIgnoreCase(connectionName)) && (path.equalsIgnoreCase(path)); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResource.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResource.java new file mode 100644 index 00000000000..0772c41edb7 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResource.java @@ -0,0 +1,175 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.File; + +import org.eclipse.core.runtime.QualifiedName; + +/** + * This class is the internal implementation of the ISystemRemoteResource interface. + */ +public class SystemRemoteResource implements ISystemRemoteResource { + + + + protected ISystemRemotePath path; + + /** + * Constructor for SystemRemoteResource. + */ + public SystemRemoteResource(ISystemRemotePath path) { + this.path = path; + } + + /** + * Get the resource info. + * @return the resource info for the resource + */ + public SystemRemoteResourceInfo getResourceInfo() { + return SystemRemoteResourceManager.getInstance().getResourceInfo(path); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#createMarker(String) + */ + public ISystemRemoteMarker createMarker(String type){ + SystemRemoteResourceInfo resourceInfo = getResourceInfo(); + + if (resourceInfo == null) { + return null; + } + + SystemRemoteMarkerInfo info = new SystemRemoteMarkerInfo(); + info.setType(type); + info.setCreationTime(System.currentTimeMillis()); + SystemRemoteMarkerManager.getInstance().add(this, new SystemRemoteMarkerInfo[] { info }); + return new SystemRemoteMarker(this, info.getId()); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#deleteMarkers(String, boolean) + */ + public void deleteMarkers(String type, boolean includeSubtypes) { + SystemRemoteMarkerManager.getInstance().removeMarkers(this, type, includeSubtypes); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#findMarker(long) + */ + public ISystemRemoteMarker findMarker(long id) { + return SystemRemoteMarkerManager.getInstance().findMarker(this, id); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#findMarkers(String, boolean) + */ + public ISystemRemoteMarker[] findMarkers(String type, boolean includeSubtypes) { + return SystemRemoteMarkerManager.getInstance().findMarkers(this, type, includeSubtypes); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#getMarker(long) + */ + public ISystemRemoteMarker getMarker(long id) { + return new SystemRemoteMarker(this, id); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#exists() + */ + public boolean exists() { + return false; + } + + /** + * + */ + public ISystemRemotePath getLocation() { + return null; + } + + + /** + * + */ + public boolean existsLocally() { + return false; + } + + /** + * + */ + public File getLocalCopy() { + return null; + } + + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#getPersistentProperty(QualifiedName) + */ + public String getPersistentProperty(QualifiedName key) { + return null; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#getSessionProperty(QualifiedName) + */ + public Object getSessionProperty(QualifiedName key) { + return null; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#setPersistentProperty(QualifiedName, String) + */ + public void setPersistentProperty(QualifiedName key, String value) { + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#setSessionProperty(QualifiedName, Object) + */ + public void setSessionProperty(QualifiedName key, Object value) { + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#getLocalLastModifiedTime() + */ + public boolean getLocalLastModifiedTime() { + return false; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#getRemoteLastModifiedTime() + */ + public boolean getRemoteLastModifiedTime() { + return false; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#isExistsLocally() + */ + public boolean isExistsLocally() { + return false; + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteResource#isSynchronized() + */ + public boolean isSynchronized() { + return false; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceInfo.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceInfo.java new file mode 100644 index 00000000000..cef7562ae9b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceInfo.java @@ -0,0 +1,92 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +/** + * Class that keeps information about a remote resource. Clients should not + * use this class. + */ +public class SystemRemoteResourceInfo implements Cloneable { + + + + /** + * Set of flags which reflect various states of the info. + */ + private int flags = 0; + + /** + * The set of markers belonging to the resource. + */ + private SystemRemoteMarkerSet markers; + + /** + * Constructor for SystemRemoteResourceInfo. + */ + public SystemRemoteResourceInfo() { + super(); + } + + /** + * Sets all of the bits indicated by the mask. + * @param the mask + */ + public void set(int mask) { + flags |= mask; + } + + /** + * Clears all of the bits indicated by the mask. + * @param the mask + */ + public void clear(int mask) { + flags &= ~mask; + } + + /** + * Returns the flags for this info. + * @return the flags + */ + public int getFlags() { + return flags; + } + + /** + * Sets the flags for this info. + * @return the flags + */ + public void setFlags(int value) { + flags = value; + } + + /** + * Set the markers for the resource info. null can be used + * to indicate that the resource has no markers. + * @param the marker set + */ + public void setMarkers(SystemRemoteMarkerSet markerSet) { + this.markers = markerSet; + } + + /** + * Get the markers from the resource info. + * @return the marker set + */ + public SystemRemoteMarkerSet getMarkers() { + return markers; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceManager.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceManager.java new file mode 100644 index 00000000000..c63d2b4c6de --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemRemoteResourceManager.java @@ -0,0 +1,84 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.util.Hashtable; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * This class manages remote resources. + */ +public class SystemRemoteResourceManager implements ISystemRemoteManager { + + + + private static SystemRemoteResourceManager instance; + + // resource info hash table + private Hashtable resourceInfos = new Hashtable(); + + /** + * Constructor for SystemRemoteResourceManager. + */ + private SystemRemoteResourceManager() { + super(); + restore(); + } + + /** + * Get the singleton instance. + * @return the singleton instance. + */ + public static SystemRemoteResourceManager getInstance() { + + if (instance == null) { + instance = new SystemRemoteResourceManager(); + } + + return instance; + } + + /** + * Get a resource info given a path. + */ + public SystemRemoteResourceInfo getResourceInfo(ISystemRemotePath path) { + return (SystemRemoteResourceInfo)(resourceInfos.get(path.toString())); + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteManager#startup(IProgressMonitor) + */ + public void startup(IProgressMonitor monitor) { + } + + /** + * @see org.eclipse.rse.files.ui.resources.ISystemRemoteManager#shutdown(IProgressMonitor) + */ + public void shutdown(IProgressMonitor monitor) { + } + + /** + * Read all resource information from disk. + */ + public void restore() {} + + /** + * Write all resource information to disk. + */ + public void save() {} +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemSafeFileOutputStream.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemSafeFileOutputStream.java new file mode 100644 index 00000000000..50486d7b8b3 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemSafeFileOutputStream.java @@ -0,0 +1,220 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * This class should be used when there's a file already in the + * destination and we don't want to lose its contents if a + * failure writing this stream happens. + * Basically, the new contents are written to a temporary location. + * If everything goes OK, it is moved to the right place. + * The user has the option to define the temporary location or + * it will be created in the default-temporary directory + */ +public class SystemSafeFileOutputStream extends OutputStream { + + + + protected File destination = null; + protected File temp = null; + protected OutputStream output = null; + protected boolean failed = false; + protected static final String BACKUP_EXTENSION = ".bak"; + + /** + * Constructor for SystemSafeFileOutputStream. + * @param the destination file. + */ + public SystemSafeFileOutputStream(File file) throws IOException { + this(file.getAbsolutePath(), null); + } + + /** + * Constructor for SystemSafeFileOutputStream. + * @param the destination file name + */ + public SystemSafeFileOutputStream(String destinationName) throws IOException { + this(destinationName, null); + } + + /** + * Constructor for SystemSafeFileOutputStream. + * @param the destination file name + * @param the temporary file name + */ + public SystemSafeFileOutputStream(String destinationPath, String tempPath) throws IOException { + destination = new File(destinationPath); + createTempFile(tempPath); + + if (!destination.exists()) { + + if (!temp.exists()) { + output = new BufferedOutputStream(new FileOutputStream(destination)); + return; + } + + // If we do not have a file at destination location, but we do have at temp location, + // it probably means something wrong happened the last time we tried to write it. + // So, try to recover the backup file. And, if successful, write the new one. + copy(temp, destination); + } + + output = new BufferedOutputStream(new FileOutputStream(temp)); + } + + /** + * Close the stream. + */ + public void close() throws IOException { + + try { + output.close(); + } + catch (IOException e) { + failed = true; + throw e; + } + + if (failed) { + temp.delete(); + } + else { + commit(); + } + } + + /** + * Commit the temporary file to the destination. + */ + protected void commit() throws IOException { + + if (!temp.exists()) { + return; + } + + destination.delete(); + copy(temp, destination); + temp.delete(); + } + + /** + * Copy contents of one file to another. + * @param the source file + * @param the destination file + */ + protected void copy(File sourceFile, File destinationFile) throws IOException { + + if (!sourceFile.exists()) { + return; + } + + FileInputStream source = new FileInputStream(sourceFile); + FileOutputStream destination = new FileOutputStream(destinationFile); + transferData(source, destination); + } + + /** + * Create the temporary file at the given path. + * @param the path of the temporary file to be created + */ + protected void createTempFile(String tempPath) throws IOException { + + if (tempPath == null) { + tempPath = destination.getAbsolutePath() + BACKUP_EXTENSION; + } + + temp = new File(tempPath); + } + + /** + * Flush the stream. + */ + public void flush() throws IOException { + try { + output.flush(); + } catch (IOException e) { + failed = true; + throw e; // rethrow + } + } + + /** + * Get the temporary file path. + * @return the path of the temporary file + */ + public String getTempFilePath() { + return temp.getAbsolutePath(); + } + + /** + * Transfers data from one stream to another. + * @param source stream + * @param destination stream + */ + protected void transferData(InputStream source, OutputStream destination) throws IOException { + + try { + byte[] buffer = new byte[8192]; + + while (true) { + int bytesRead = source.read(buffer); + + if (bytesRead == -1) { + break; + } + + destination.write(buffer, 0, bytesRead); + } + } + finally { + try { + source.close(); + } + catch (IOException e) { + } + + try { + destination.close(); + } + catch (IOException e) { + } + } + } + + /** + * Write an integer. + * @param the integer to write + */ + public void write(int b) throws IOException { + + try { + output.write(b); + } + catch (IOException e) { + failed = true; + throw e; + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemTempFileListener.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemTempFileListener.java new file mode 100644 index 00000000000..ac599e5e000 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemTempFileListener.java @@ -0,0 +1,661 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.dialogs.ProgressMonitorDialog; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.filters.ISystemFilterReference; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.progress.WorkbenchJob; + + +/** + * This class manages listening for resource changes within our temp file project + * It is used for listening to saves made in the editor so that we can upload + * changes to the remote files. */ +public abstract class SystemTempFileListener implements IResourceChangeListener +{ + + private ArrayList _changedResources; + private ArrayList _ignoredFiles = new ArrayList(); + private boolean _isSynching; + private boolean _isEnabled; + + public SystemTempFileListener() + { + _changedResources = new ArrayList(); + _isSynching = false; + _isEnabled = true; + } + + public void setEnabled(boolean flag) + { + _isEnabled = flag; + } + + public void addIgnoreFile(IFile toIgnore) + { + _ignoredFiles.add(toIgnore); + } + + public void removeIgnoreFile(IFile toNotIgnore) + { + _ignoredFiles.remove(toNotIgnore); + } + + public boolean isIgnorable(IFile file) + { + if (_ignoredFiles.contains(file)) + { + return true; + } + else + { + String path = file.getLocation().toString().toLowerCase(); + + for (int i = 0; i < _ignoredFiles.size(); i++) + { + IFile cfile = (IFile)_ignoredFiles.get(i); + String cpath = cfile.getLocation().toString().toLowerCase(); + if (path.equals(cpath)) + { + return true; + } + } + } + return false; + } + + /** + * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent) + */ + public void resourceChanged(IResourceChangeEvent event) + { + if (_isEnabled) + { + + Object source = event.getSource(); + IResourceDelta delta = event.getDelta(); + if (delta != null) + { + if (preScanForTempFiles(delta)) + { + // a temp file has changed + // synchronize temp file with remote file + processDelta(delta); + + if (_changedResources.size() > 0 && !_isSynching) + { + refreshRemoteResourcesOnUIThread(); + } + } + else + { + if (!SystemPlugin.getThePersistenceManager().isExporting()) + { + List changes = new ArrayList(); + checkLocalChanges(delta, changes); + refreshRemoteResourcesOnMainThread(changes); + } + } + } + } + } + + public class RefreshResourcesJob extends Job + { + private List _resources; + public RefreshResourcesJob(List resources) + { + super(FileResources.RSEOperation_message); + _resources = resources; + } + + public IStatus run(IProgressMonitor monitor) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_SYNCHRONIZE_PROGRESS); + monitor.beginTask(msg.getLevelOneText(), _resources.size()); + for (int i = 0; i < _resources.size(); i++) + { + Object resource = _resources.get(i); + refreshRemoteResource(resource); + monitor.worked(1); + } + monitor.done(); + return Status.OK_STATUS; + } + } + + public class RefreshResourcesUIJob extends WorkbenchJob + { + public RefreshResourcesUIJob() + { + super(FileResources.RSEOperation_message); + } + + public IStatus runInUIThread(IProgressMonitor monitor) + { + _isSynching = true; + synchronized (_changedResources) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_SYNCHRONIZE_PROGRESS); + monitor.beginTask(msg.getLevelOneText(), IProgressMonitor.UNKNOWN); + setName(msg.getLevelOneText()); + for (int i = 0; i < _changedResources.size(); i++) + { + IFile file = (IFile) _changedResources.get(i); + synchronizeTempWithRemote(file, monitor); + } + monitor.done(); + + _changedResources.clear(); + } + _isSynching = false; + return Status.OK_STATUS; + } + } + + private void refreshRemoteResourcesOnMainThread(List resources) + { + RefreshResourcesJob job = new RefreshResourcesJob(resources); + job.setPriority(Job.INTERACTIVE); + job.schedule(); + } + + private void refreshRemoteResourcesOnUIThread() + { + RefreshResourcesUIJob job = new RefreshResourcesUIJob(); + job.setPriority(Job.INTERACTIVE); + job.schedule(); + } + + protected void checkLocalChanges(IResourceDelta delta, List changes) + { + IResourceDelta[] children = delta.getAffectedChildren(); + for (int i = 0; i < children.length; i++) + { + IResourceDelta child = children[i]; + + // DKM - case where local resource changes that local subsystem happens to be looking at + int kind = child.getKind(); + boolean noChange = (kind == IResourceDelta.NO_CHANGE); + if (noChange) + return; + + boolean isChanged = (kind == IResourceDelta.CHANGED); + boolean isDeleted = (kind == IResourceDelta.REMOVED); + boolean isAdded = (kind == IResourceDelta.ADDED); + boolean isMovedTo = (kind == IResourceDelta.MOVED_TO); + boolean isMovedFrom = (kind == IResourceDelta.MOVED_FROM); + + IResource resource = child.getResource(); + + String pathOfChild = null; + String pathOfParent = null; + + IPath location = resource.getLocation(); + if (location == null) + { + // deleted resource + String projectPath = child.getFullPath().toOSString(); + String workspacePath = SystemBasePlugin.getWorkspaceRoot().getLocation().toOSString(); + + pathOfChild = workspacePath + projectPath; + pathOfParent = (new File(pathOfChild)).getParent(); + } + else + { + pathOfChild = resource.getLocation().toOSString(); + pathOfParent = resource.getParent().getLocation().toOSString(); + } + + + + if (isChanged) + { + checkLocalChanges(child, changes); + } + else + { + RemoteFileSubSystem fs = (RemoteFileSubSystem)getLocalFileSubSystem(); + if (fs == null) return; // MJB: Defect 45678 + + IRemoteFile remoteFile = fs.getCachedRemoteFile(pathOfChild); + if (remoteFile != null) + { + remoteFile.markStale(true); + } + + IRemoteFile cachedParent = fs.getCachedRemoteFile(pathOfParent); + if (cachedParent == null) + return; + + cachedParent.markStale(true); + if (!changes.contains(cachedParent)) + { + changes.add(cachedParent); + } + if (isDeleted) + { + //System.out.println("deleted="+isDeleted); + } + else if (isAdded) + { + //System.out.println("added="+isAdded); + } + else if (isMovedTo) + { + //System.out.println("movedto="+isMovedTo); + } + else if (isMovedFrom) + { + //System.out.println("movedfrom="+isMovedFrom); + } + } + + } + } + + protected IRunnableContext getRunnableContext(Shell shell) + { + IRunnableContext irc = SystemPlugin.getTheSystemRegistry().getRunnableContext(); + if (irc != null) + { + return irc; + } + else + { + // for other cases, use statusbar + IWorkbenchWindow win = SystemBasePlugin.getActiveWorkbenchWindow(); + + if (win != null) + { + Shell winShell = SystemBasePlugin.getActiveWorkbenchShell(); + if (winShell != null && !winShell.isDisposed() && winShell.isVisible()) + { + shell = winShell; + return win; + } + else + { + win = null; + } + } + + return new ProgressMonitorDialog(shell); + } + } + /** + * Check the delta for changed temporary files. If + * any are found, synchronize the temporary files with + * the corresponding remote files. + * + * @param delta the delta to compare + */ + protected void processDelta(IResourceDelta delta) + { + IResourceDelta[] children = delta.getAffectedChildren(); + for (int i = 0; i < children.length; i++) + { + IResourceDelta child = children[i]; + + IResource resource = child.getResource(); + + if (resource instanceof IFile) + { + String loc = resource.getLocation().toString(); + + // see if this temp file has been changed + int ckind = child.getKind(); + boolean isChanged = ckind == IResourceDelta.CHANGED; + int flags = child.getFlags(); + boolean contentChanged = (isChanged && (flags & IResourceDelta.CONTENT) != 0); + + if (contentChanged) + { + //TODO PROBLEM!! - Eclipse threading means the file may not be ignorable when this event comes in + // - we need to know if this is via edit or not! + if (!_changedResources.contains(resource) && !isIgnorable((IFile)resource)) + { + SystemIFileProperties properties = new SystemIFileProperties(resource); + if (properties.getDownloadFileTimeStamp() != resource.getLocalTimeStamp()) + { + String ssStr = properties.getRemoteFileSubSystem(); + if (ssStr != null) + { + ISubSystem ss = SystemPlugin.getTheSystemRegistry().getSubSystem(ssStr); + if (doesHandle(ss)) + { + _changedResources.add(resource); + } + } + } + } + + // KM - commenting out everything below to avoid doing checks as to whether + // the file is opened in an editor. The check means that for cases + // where the remote file was opened using an external editor, there + // won't be a save back to the host, even when the user refreshes the temp project + // or the file. + + /* DKM - can't remember why I did this, but it might be obsolete now + * need to be able to save remotely regardless whether it's being edited that way or not + */ + ///* + // check if this file is being edited + /*IWorkbenchWindow window = SystemPlugin.getActiveWorkbenchWindow(); + if (window == null) + { + // DKM: + //no window, so forget about editors...just save + // whenever refresh() is done (regardless of changes we hit this + // we should only do something here when on main thread + //_changedResources.add(resource); + } + else + { + IWorkbenchPage page = window.getActivePage(); + if (page != null) + { + IEditorReference[] references = page.getEditorReferences(); + for (int e = 0; e < references.length; e++) + { + IEditorReference ref = references[e]; + IEditorPart editorPart = ref.getEditor(false); + if (editorPart != null) + { + IEditorInput input = editorPart.getEditorInput(); + if (input != null && input instanceof FileEditorInput) + { + FileEditorInput finput = (FileEditorInput) input; + IFile eFile = finput.getFile(); + String eLoc = eFile.getLocation().toString(); + + if (eLoc.equals(loc)) + { + // add to list of pending resource changes + if (!_changedResources.contains(resource)) + { + _changedResources.add(resource); + } + /// DKM - shouldn't return + //return; + } + } + else if (input != null && input instanceof SystemCompareInput) + { + SystemCompareInput compareInput = (SystemCompareInput) input; + IResource lFile = compareInput.getLeftResource(); + IResource rFile = compareInput.getRightResource(); + + String lLoc = lFile.getLocation().toString(); + if (lLoc.equals(loc)) + { + // add to list of pending resource changes + if (!_changedResources.contains(resource)) + { + _changedResources.add(resource); + } + } + + String rLoc = rFile.getLocation().toString(); + if (rLoc.equals(loc)) + { + // add to list of pending resource changes + if (!_changedResources.contains(resource)) + { + _changedResources.add(resource); + } + } + } + } + } + } + }*/ + + // DKM - shouldn't return + //return; + } + } + else + { + // recursively check the subdelta of this delta + processDelta(child); + } + } + } + + /** + * Synchronize a temporary file with it's corresponding remote file. + * First we need to determine what the corresponding remote file is. + * Then we need to compare timestamps to determine how to synchronize. + * + * @param file the temporary file to synchronize + */ + protected void synchronizeTempWithRemote(IFile file, IProgressMonitor monitor) + { + // first determine associated remote file + IPath path = file.getFullPath(); + int numSegments = path.segmentCount(); + + // first we need to find the right RemoteFileSubSystem for the remote file + SystemIFileProperties properties = new SystemIFileProperties(file); + + // before doing anything, check that the stored time stamp is not empty + if (properties.getRemoteFileTimeStamp() == 0) + { + // we just downloaded this and that's why we hit an event + return; + } + + ISubSystem fs = null; + + // get the subsystem ID property from the temporary file + String subsystemId = properties.getRemoteFileSubSystem(); + + // the subsystem ID may not exist if the temporary file existed before this feature + // to handle migration of this smoothly, we can use another method to determine the subsystem + if (subsystemId != null) + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + fs = registry.getSubSystem(subsystemId); + } + + if (fs != null) + { + // use the remote file path property of the temp file to determine the path of the remote file + // on the remote system + String uploadPath = properties.getRemoteFilePath(); + + // the uploadPath property may not exist if the temporary file existed before this feature + // to handle migration of this smoothly, we can use another method to determine the remote file path + if (uploadPath == null) + { + // derive the path from the temporary file path + IHost connection = fs.getHost(); + + // on windows systems, we need to take into account drives and different separators + boolean isWindows = connection.getSystemType().equals("Local") || fs.getHost().getSystemType().equals("Windows"); + + char fileSeparator = isWindows ? '\\' : '/'; + StringBuffer remotePath = new StringBuffer(""); + for (int i = 3; i < numSegments; i++) + { + if (i == 3) + { + if (!isWindows) + { + remotePath.append(fileSeparator); + } + } + if (i > 3) + { + if (i == 4) + { + if (isWindows) + { + remotePath.append(":"); + } + } + + remotePath.append(fileSeparator); + } + + String seg = path.segment(i); + remotePath.append(seg); + } + + uploadPath = remotePath.toString(); + } + + // attemp the remote file synchronization + if (doesHandle(fs)) + { + // see if we're connected + try + { + // check that the remote file system is connected + // if not, attemp to connect to it + if (!fs.isConnected()) + { + Shell theShell = SystemBasePlugin.getActiveWorkbenchShell(); + fs.connect(theShell); + } + } + catch (Exception e) + { + // unable to connect to the remote server + // do not attempt synchronization + // instead, defer synchronization to later but allow user to edit + // set the dirty flag to indicate that this file needs resynchronization + properties.setDirty(true); + return; + } + + doResourceSynchronization(fs, file, uploadPath, monitor); + } + } + } + + protected void refreshRemoteResource(Object parent) + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + // refresh + if (parent != null) + { + registry.fireEvent(new SystemResourceChangeEvent(parent, ISystemResourceChangeEvents.EVENT_REFRESH, null)); + + + List filterReferences = registry.findFilterReferencesFor(parent, getLocalFileSubSystem()); + for (int i = 0; i < filterReferences.size(); i++) + { + ISystemFilterReference filterRef = (ISystemFilterReference)filterReferences.get(i); + filterRef.markStale(true); + registry.fireEvent(new SystemResourceChangeEvent(filterRef, ISystemResourceChangeEvents.EVENT_REFRESH, null)); + } + } + } + + + /** + * Synchronize the specified remote file with the temporary local file using the + * specified remote file subsystem. + * + * @param fs the remote file subsystem of the remote file + * @param tempFile the temporary file + * @param remoteFile the remote file + * @param monitor the progress monitor + */ + protected abstract void doResourceSynchronization(ISubSystem subsystem, IFile tempFile, String resourceId, IProgressMonitor monitor); + + /** + * Indicate whether this tempfile listener handles the specified + * @param subsystem the subsystem to check + * @return whether it handles this or not + */ + protected abstract boolean doesHandle(ISubSystem subsystem); + + private IRemoteFileSubSystem getLocalFileSubSystem() + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + IHost con = registry.getLocalHost(); + if (con != null) + { + return RemoteFileUtility.getFileSubSystem(con); + } + return null; + } + + + /** + * Prescan for changes that correspond the temp files project + */ + protected boolean preScanForTempFiles(IResourceDelta delta) + { + if (delta == null) + { + return true; // not sure when we'd get this + } + + // does temp files exist + if (!SystemRemoteEditManager.getDefault().doesRemoteEditProjectExist()) + return false; + + IResourceDelta[] subdeltas = delta.getAffectedChildren(); + if (subdeltas.length > 0) + { + IResource resource = subdeltas[0].getResource(); + if ((resource != null) && (resource.getType() == IResource.PROJECT)) + { + if (resource.getName().equals(SystemRemoteEditManager.REMOTE_EDIT_PROJECT_NAME)) + { + return true; + } + } + } + return false; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemUniversalTempFileListener.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemUniversalTempFileListener.java new file mode 100644 index 00000000000..b7f9252b2dd --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/SystemUniversalTempFileListener.java @@ -0,0 +1,317 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; +import java.util.ArrayList; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.actions.SystemUploadConflictAction; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.ui.actions.DisplaySystemMessageAction; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + + +/** + * This class manages listening for resource changes within our temp file project + * It is used for listening to saves made in the editor so that we can upload + * changes to the remote files. This class specifically handles universal files + * and doesn't do anything for iSeries. For iSeries members we need to subclass this. + */ +public class SystemUniversalTempFileListener extends SystemTempFileListener +{ + + private static SystemUniversalTempFileListener _instance = null; + + private ArrayList _editedFiles = new ArrayList(); + + /** + * Return singleton + */ + public static SystemUniversalTempFileListener getListener() + { + if (_instance == null) + { + _instance = new SystemUniversalTempFileListener(); + } + return _instance; + } + + public void registerEditedFile(SystemEditableRemoteFile editMember) + { + _editedFiles.add(editMember); + } + + public void unregisterEditedFile(SystemEditableRemoteFile editMember) + { + _editedFiles.remove(editMember); + } + + public SystemEditableRemoteFile getEditedFile(IRemoteFile file) + { + for (int i = 0; i < _editedFiles.size(); i++) + { + SystemEditableRemoteFile efile = (SystemEditableRemoteFile) _editedFiles.get(i); + if (efile != null) + { + IRemoteFile editedFile = efile.getRemoteFile(); + if (editedFile.getAbsolutePathPlusConnection().equals(file.getAbsolutePathPlusConnection())) + { + return efile; + } + } + } + + return null; + } + + /** + * Indicate whether this tempfile listener handles the specified + * @param subsystem the subsystem to check + * @return whether it handles this or not + */ + protected boolean doesHandle(ISubSystem subsystem) + { + if (subsystem instanceof IRemoteFileSubSystem) + { + return true; + } + return false; + } + + /** + * Synchronize the specified remote file with the temporary local file using the + * specified remote file subsystem. + * + * @param fs the remote file subsystem of the remote file + * @param tempFile the temporary file + * @param remoteFile the remote file + */ + protected void doResourceSynchronization(ISubSystem subsystem, IFile tempFile, String resourceId, IProgressMonitor monitor) + { + if (subsystem instanceof IRemoteFileSubSystem) + { + Shell shell = SystemPlugin.getTheSystemRegistry().getShell(); + IRemoteFileSubSystem fs = (IRemoteFileSubSystem) subsystem; + + // first we need to get the stored timestamp property and the actual remote timestamp + SystemIFileProperties properties = new SystemIFileProperties(tempFile); + + // make sure we're working online - not offline + if (fs.isOffline()) + { + properties.setDirty(true); + return; + } + else + { + // for mounting... + if (fs.getHost().getSystemType().equals("Local")) + { + boolean isMounted = properties.getRemoteFileMounted(); + if (isMounted) + { + String mappedHostPath = properties.getResolvedMountedRemoteFilePath(); + String mappedHostName = properties.getResolvedMountedRemoteFileHost(); + String systemRemotePath = SystemRemoteEditManager.getDefault().getMountPathFor(mappedHostName, mappedHostPath); + + if (systemRemotePath == null) + { + // mount no longer exists - just return for now + return; + } + if (!systemRemotePath.equals(resourceId)) + { + // remote path + resourceId = systemRemotePath; + properties.setRemoteFilePath(systemRemotePath); + } + } + } + } + + try + { + IRemoteFile remoteFile = fs.getRemoteFileObject(resourceId); + + if (remoteFile != null) + { + + // make sure we have uptodate file + remoteFile.markStale(true); + remoteFile = fs.getRemoteFileObject(resourceId); + + // get modification stamp and dirty state + long storedModifiedStamp = properties.getRemoteFileTimeStamp(); + + // get associated editable + SystemEditableRemoteFile editable = getEditedFile(remoteFile); + if (editable != null && storedModifiedStamp == 0) + { + return; + + } + else if (editable == null) + { + Object remoteObject = properties.getRemoteFileObject(); + if (remoteObject != null && remoteObject instanceof SystemEditableRemoteFile) + { + editable = (SystemEditableRemoteFile) remoteObject; + } + else + { + editable = new SystemEditableRemoteFile(remoteFile); + } + + // defect - we get a save event when saving during a close + // in that case, we shouldn't reopen the editor + // I think this was originally here so that, if a save is done on + // a file that hasn't yet been wrapped with an editable, we can + // set the editor member + // now call check method before + if (editable.checkOpenInEditor() != ISystemEditableRemoteObject.NOT_OPEN) + { + editable.openEditor(); + } + editable.addAsListener(); + editable.setLocalResourceProperties(); + } + + upload(fs, remoteFile, tempFile, properties, storedModifiedStamp, editable, monitor); + } + } + catch (Exception e) + { + SystemBasePlugin.logError(e.getMessage()); + } + } + + } + + public void upload(IRemoteFileSubSystem fs, IRemoteFile remoteFile, IFile tempFile, SystemIFileProperties properties, + long storedModifiedStamp, SystemEditableRemoteFile editable, IProgressMonitor monitor) + { + try + { + // get the remote modified timestamp + long remoteModifiedStamp = remoteFile.getLastModified(); + + boolean remoteFileDeleted = !remoteFile.exists(); + // compare timestamps + if (remoteFileDeleted || (storedModifiedStamp == remoteModifiedStamp)) + { + // timestamps are the same, so the remote file hasn't changed since our last download + try + { + // upload our pending changes to the remote file + fs.uploadUTF8(tempFile, remoteFile,monitor); + } + + catch (RemoteFileSecurityException e) + { + DisplaySystemMessageAction msgAction = new DisplaySystemMessageAction(e.getSystemMessage()); + Display.getDefault().syncExec(msgAction); + } + catch (RemoteFileIOException e) + { + DisplaySystemMessageAction msgAction = new DisplaySystemMessageAction(e.getSystemMessage()); + Display.getDefault().syncExec(msgAction); + } + catch (Exception e) + { + RemoteFileIOException exc = new RemoteFileIOException(e); + DisplaySystemMessageAction msgAction = new DisplaySystemMessageAction(exc.getSystemMessage()); + Display.getDefault().syncExec(msgAction); + } + + // get the remote file object again so that we have a fresh remote timestamp + remoteFile.markStale(true); + + + IRemoteFile parent = remoteFile.getParentRemoteFile(); + + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + // refresh + if (parent != null) + { + registry.fireEvent(new SystemResourceChangeEvent(parent, ISystemResourceChangeEvents.EVENT_REFRESH, null)); + } + + remoteFile = fs.getRemoteFileObject(remoteFile.getAbsolutePath()); + + registry.fireEvent(new SystemResourceChangeEvent(remoteFile, ISystemResourceChangeEvents.EVENT_PROPERTY_CHANGE, remoteFile)); + + + // set the stored timestamp to be the same as the remote timestamp + properties.setRemoteFileTimeStamp(remoteFile.getLastModified()); + + // indicate that the temp file is no longer dirty + properties.setDirty(false); + editable.updateDirtyIndicator(); + + } + else if (storedModifiedStamp == -1) + { + // hack because Eclipse send out event after replacing local file with remote + // we don't want to save this! + // set the stored timestamp to be the same as the remote timestamp + properties.setRemoteFileTimeStamp(remoteFile.getLastModified()); + } + else + { + // conflict + // determine which file has a newer timestamp + boolean remoteNewer = remoteModifiedStamp > storedModifiedStamp; + + // case 1: the remote file has changed since our last download + // it's new timestamp is newer than our stored timestamp (file got + // updated) + + // case 2: the remote file has changed since our last download + // it's new timestamp is older than our stored timestamp (file got + // replaced with an older version) + + // prompt user with dialog **** Prompt Dialog 1 + // 1) Overwrite local + // 2) Overwrite remote + // 3) Save as... + // 4) Cancel + Shell shell = SystemPlugin.getTheSystemRegistry().getShell(); + + SystemUploadConflictAction conflictAction = new SystemUploadConflictAction(shell, tempFile, remoteFile, remoteNewer); + conflictAction.run(); + editable.updateDirtyIndicator(); + + + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/UniversalFileTransferUtility.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/UniversalFileTransferUtility.java new file mode 100644 index 00000000000..31f321a839f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/resources/UniversalFileTransferUtility.java @@ -0,0 +1,1511 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.resources; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.SystemRemoteResourceSet; +import org.eclipse.rse.model.SystemWorkspaceResourceSet; +import org.eclipse.rse.services.clientserver.SystemEncodingUtil; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.archiveutils.ISystemArchiveHandler; +import org.eclipse.rse.services.clientserver.archiveutils.VirtualChild; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.model.SystemFileTransferModeRegistry; +import org.eclipse.rse.subsystems.files.core.servicesubsystem.FileServiceSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IVirtualRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFolderNotEmptyException; +import org.eclipse.rse.subsystems.files.core.util.ValidatorFileUniqueName; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.dialogs.SystemRenameSingleDialog; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + + +/** + * Utility class for doing file transfers on universal systems + */ +public class UniversalFileTransferUtility +{ + static final boolean doCompressedTransfer = true;//false; + + static final String _rootPath = SystemRemoteEditManager.getDefault().getRemoteEditProjectLocation().makeAbsolute().toOSString(); + + /** + * Transfer a remote file or folder from one remote location to another. + * @param srcFileOrFolder the file or folder to copy + * @param tgtFolder the folder to copy to + * @param monitor the progress monitor + * @param shell + */ + public static void transferRemoteResource(IRemoteFile srcFileOrFolder, IRemoteFile tgtFolder, IProgressMonitor monitor) + { + Object tempSrc = copyRemoteResourceToWorkspace(srcFileOrFolder, monitor); + if (tempSrc instanceof IResource) + { + copyWorkspaceResourceToRemote((IResource) tempSrc, tgtFolder, monitor); + } + } + + /** + * replicates a remote file to the temp files project in the workspace + * + * @param srcFileOrFolder the file to copy + * @param monitor the progress monitor + * @param shell + * @return the resulting local replica + */ + public static IFile copyRemoteFileToWorkspace(IRemoteFile srcFileOrFolder, IProgressMonitor monitor) + { + IRemoteFileSubSystem srcFS = srcFileOrFolder.getParentRemoteFileSubSystem(); + IResource tempResource = getTempFileFor(srcFileOrFolder); + + IFile tempFile = (IFile) tempResource; + + // before we make the transfer to the temp file check whether a temp file already exists + if (tempFile.exists()) + { + SystemIFileProperties properties = new SystemIFileProperties(tempFile); + + long storedModifiedStamp = properties.getRemoteFileTimeStamp(); + + // compare timestamps + if (storedModifiedStamp > 0) + { + // ;if they're the same, just use temp file + long remoteModifiedStamp = srcFileOrFolder.getLastModified(); + + if (storedModifiedStamp == remoteModifiedStamp) + { + return tempFile; + } + } + } + + /* + if (monitor != null) + { + SystemMessage copyMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COPYTHINGGENERIC_PROGRESS); + copyMessage.makeSubstitution(srcFileOrFolder.getName()); + + monitor.beginTask(copyMessage.getLevelOneText(), IProgressMonitor.UNKNOWN); + } +*/ + + try + { + // copy remote file to workspace + srcFS.download(srcFileOrFolder, tempFile, SystemEncodingUtil.ENCODING_UTF_8, monitor); + + if (!tempFile.exists()) + { + tempFile.refreshLocal(IResource.DEPTH_ZERO, null/*monitor*/); + } + if (tempFile.exists()) + { + // if the file is virtual, set read only if necessary + // TODO: why set this here? And why for virtual only?? + if (srcFileOrFolder instanceof IVirtualRemoteFile) + { + setReadOnly(tempFile, srcFileOrFolder.canWrite()); + } + + if (srcFileOrFolder.isText()) + { + try + { + tempFile.setCharset(SystemEncodingUtil.ENCODING_UTF_8, null/*monitor*/); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } + catch (RemoteFileIOException e) + { + SystemMessageDialog dlg = new SystemMessageDialog(SystemBasePlugin.getActiveWorkbenchShell(), e.getSystemMessage()); + dlg.open(); + return null; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } + + return (IFile) tempResource; + } + + protected static void setIFileProperties(IFile tempFile, IRemoteFile remoteFile, IRemoteFileSubSystem subSystem) + { + // set it's properties for use later + SystemIFileProperties properties = new SystemIFileProperties(tempFile); + + // set remote properties + properties.setRemoteFileTimeStamp(remoteFile.getLastModified()); + properties.setDirty(false); + + String remotePath = remoteFile.getAbsolutePath(); + + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + String subSystemId = registry.getAbsoluteNameForSubSystem(subSystem); + properties.setRemoteFileSubSystem(subSystemId); + properties.setRemoteFilePath(remotePath); + properties.setDownloadFileTimeStamp(tempFile.getLocalTimeStamp()); + + boolean isMounted = isRemoteFileMounted(subSystem, remotePath); + properties.setRemoteFileMounted(isMounted); + if (isMounted) + { + String actualRemoteHost = getActualHostFor(subSystem, remotePath); + String actualRemotePath = getWorkspaceRemotePath(subSystem, remotePath); + properties.setResolvedMountedRemoteFileHost(actualRemoteHost); + properties.setResolvedMountedRemoteFilePath(actualRemotePath); + } + } + + + /** + * Replicates a set of remote files or folders to the workspace + * @param remoteSet the objects which are being copied + * @param monitor a progress monitor + * @param shell + * @return the temporary objects that was created after the download + */ + public static SystemWorkspaceResourceSet copyRemoteResourcesToWorkspace(SystemRemoteResourceSet remoteSet, IProgressMonitor monitor) + { + + + boolean ok = true; + SystemWorkspaceResourceSet resultSet = new SystemWorkspaceResourceSet(); + IRemoteFileSubSystem srcFS = (IRemoteFileSubSystem)remoteSet.getSubSystem(); + + if (!srcFS.isConnected()) + { + return null; + } + + boolean doSuperTransferProperty = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + + + List set = remoteSet.getResourceSet(); + for (int i = 0; i < set.size() && !resultSet.hasMessage(); i++) + { + if (monitor != null && monitor.isCanceled()) + { + return resultSet; + } + + + IRemoteFile srcFileOrFolder = (IRemoteFile)set.get(i); + if (!srcFileOrFolder.exists()) + { + SystemMessage errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_FILE_NOTFOUND); + errorMessage.makeSubstitution(srcFileOrFolder.getAbsolutePath(), srcFS.getHostAliasName()); + resultSet.setMessage(errorMessage); + } + else + { + if (srcFileOrFolder.isFile()) // file transfer + { + IFile tempFile = copyRemoteFileToWorkspace(srcFileOrFolder, monitor); + resultSet.addResource(tempFile); + } + else // folder transfer + { + IResource tempFolder = null; + + if (doCompressedTransfer && doSuperTransferProperty && !srcFileOrFolder.isRoot() + && !(srcFileOrFolder.getParentRemoteFileSubSystem().getHost().getSystemType().equals("Local"))) + { + try + { + tempFolder = compressedCopyRemoteResourceToWorkspace(srcFileOrFolder, monitor); + } + catch (Exception e) + { + e.printStackTrace(); + ok = false; + } + ok = tempFolder != null; + if (ok) + { + resultSet.addResource(tempFolder); + } + } + else + { + tempFolder = getTempFileFor(srcFileOrFolder); + IRemoteFile[] children = srcFS.listFoldersAndFiles(srcFileOrFolder); + + + SystemRemoteResourceSet childSet = new SystemRemoteResourceSet(srcFS, children); + SystemWorkspaceResourceSet childResults = copyRemoteResourcesToWorkspace(childSet, monitor); + if (childResults.hasMessage()) + { + resultSet.setMessage(childResults.getMessage()); + } + resultSet.addResource(tempFolder); + } + } + } + } + + + // refresh and set IFile properties + for (int r = 0; r < resultSet.size(); r++) + { + IResource tempResource = (IResource)resultSet.get(r); + IRemoteFile rmtFile = (IRemoteFile)remoteSet.get(r); + + if (!tempResource.exists()) + { + // refresh temp file in project + try + { + tempResource.refreshLocal(IResource.DEPTH_ONE, null /*monitor*/); + } + catch (CoreException e) + { + e.printStackTrace(); + } + } + if (tempResource instanceof IFile) + { + setIFileProperties((IFile)tempResource, rmtFile, srcFS); + } + /* + else + { + // refresh temp file in project + try + { + tempResource.refreshLocal(IResource.DEPTH_INFINITE, monitor); + } + catch (CoreException e) + { + e.printStackTrace(); + } + } + */ + } + + return resultSet; + } + + + /** + * Replicates a remote file or folder to the workspace + * @param srcFileOrFolder the object which is being copied + * @param monitor a progress monitor + * @param shell + * @return the temporary object that was created after the download + */ + public static Object copyRemoteResourceToWorkspace(IRemoteFile srcFileOrFolder, IProgressMonitor monitor) + { + + boolean ok = true; + + IRemoteFileSubSystem srcFS = srcFileOrFolder.getParentRemoteFileSubSystem(); + + if (!srcFS.isConnected()) + { + return null; + } + if (!srcFileOrFolder.exists()) + { + SystemMessage errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_FILE_NOTFOUND); + errorMessage.makeSubstitution(srcFileOrFolder.getAbsolutePath(), srcFS.getHostAliasName()); + return errorMessage; + } + + if (srcFileOrFolder.isFile()) + { + IFile tempFile = copyRemoteFileToWorkspace(srcFileOrFolder, monitor); + + if (!tempFile.exists()) + { + // refresh temp file in project + try + { + tempFile.refreshLocal(IResource.DEPTH_ONE, monitor); + } + catch (CoreException e) + { + e.printStackTrace(); + } + } + + tempFile = (IFile) getTempFileFor(srcFileOrFolder); + if (tempFile.exists()) + { + setIFileProperties(tempFile, srcFileOrFolder, srcFS); + } + + return tempFile; + } + else + { + IResource tempFolder = null; + + boolean doSuperTransferProperty = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + + if (doCompressedTransfer && doSuperTransferProperty && !srcFileOrFolder.isRoot() + && !(srcFileOrFolder.getParentRemoteFileSubSystem().getHost().getSystemType().equals("Local"))) + { + try + { + tempFolder = compressedCopyRemoteResourceToWorkspace(srcFileOrFolder, monitor); + } + catch (Exception e) + { + e.printStackTrace(); + ok = false; + } + ok = tempFolder != null; + if (ok) + { + return tempFolder; + } + } + else + { + tempFolder = getTempFileFor(srcFileOrFolder); + IRemoteFile[] children = srcFS.listFoldersAndFiles(srcFileOrFolder); + IResource[] childResources = new IResource[children.length]; + + if (children != null) + { + if (children.length == 0) + { + File tempFolderFile = tempFolder.getLocation().toFile(); + tempFolderFile.mkdirs(); + } + + for (int i = 0; i < children.length && ok; i++) + { + IRemoteFile child = children[i]; + IResource childResource = null; + if (child.isFile()) + { + childResource = copyRemoteFileToWorkspace(child, monitor); + } + else + { + childResource = (IResource) copyRemoteResourceToWorkspace(child, monitor); + } + if (childResource == null) + { + ok = false; + } + if (monitor != null && monitor.isCanceled()) + { + ok = false; + } + childResources[i] = childResource; + } + } + + if (ok) + { + refreshResourceInWorkspace(tempFolder); + + // set properties of files + if (tempFolder.exists() && children != null) + { + for (int i = 0; i < childResources.length; i++) + { + IResource tempFile = childResources[i]; + + if (tempFile.exists() && tempFile instanceof IFile) + { + IRemoteFile child = children[i]; + setIFileProperties((IFile)tempFile, child, srcFS); + } + } + } + + return tempFolder; + } + } + } + + return null; + } + + /** + * Helper method to get the local file subsystem. + * @return the local file subsystem + */ + private static IRemoteFileSubSystem getLocalFileSubSystem() + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + IHost[] connections = registry.getHosts(); + for (int i = 0; i < connections.length; i++) + { + IHost connection = connections[i]; + IRemoteFileSubSystem anFS = RemoteFileUtility.getFileSubSystem(connection); + if (anFS.getHost().getSystemType().equals("Local")) + { + return anFS; + } + } + + return null; + } + + + /** + * Perform a copy via drag and drop. + * @param src the object to be copied. If the target and source are not on the same system, then this is a + * temporary object produced by the doDrag. + * @param target the object to be copied to. + * @param monitor the progress monitor + * @param shell + * @return the resulting remote object + */ + public static Object copyWorkspaceResourceToRemote(IResource srcFileOrFolder, IRemoteFile targetFolder, IProgressMonitor monitor) + { + return copyWorkspaceResourceToRemote(srcFileOrFolder, targetFolder, monitor, true); + } + +/** + * Perform a copy via drag and drop. + * @param workspaceSet the objects to be copied. If the target and sources are not on the same system, then this is a + * temporary object produced by the doDrag. + * @param target the object to be copied to. + * @param monitor the progress monitor + * @param shell + * @param indicates whether to check for colllisions or not + * @return the resulting remote objects + */ + public static SystemRemoteResourceSet copyWorkspaceResourcesToRemote(SystemWorkspaceResourceSet workspaceSet, IRemoteFile targetFolder, IProgressMonitor monitor, Shell shell, boolean checkForCollisions) + { + boolean doSuperTransferPreference = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER) + && targetFolder.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + + IRemoteFileSubSystem targetFS = targetFolder.getParentRemoteFileSubSystem(); + SystemRemoteResourceSet resultSet = new SystemRemoteResourceSet(targetFS); + + if (targetFolder.isStale()) + { + try + { + targetFolder = targetFS.getRemoteFileObject(targetFolder.getAbsolutePath()); + } + catch (Exception e) + { + } + } + + if (!targetFolder.canWrite()) + { + SystemMessage errorMsg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_SECURITY_ERROR); + errorMsg.makeSubstitution(targetFS.getHostAliasName()); + resultSet.setMessage(errorMsg); + return resultSet; + } + + if (!targetFS.isConnected()) + { + return null; + } + boolean isTargetArchive = targetFolder.isArchive(); + if (isTargetArchive && !targetFolder.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) return null; + StringBuffer newPathBuf = new StringBuffer(targetFolder.getAbsolutePath()); + if (isTargetArchive) + { + newPathBuf.append(ArchiveHandlerManager.VIRTUAL_SEPARATOR); + } + else + { + newPathBuf.append(targetFolder.getSeparatorChar()); + } + + List resources = workspaceSet.getResourceSet(); + List newFilePathList = new ArrayList(); + + + // query what we're going to create + for (int n = 0; n < resources.size(); n++) + { + IResource srcFileOrFolder = (IResource)resources.get(n); + newFilePathList.add(newPathBuf.toString() + srcFileOrFolder.getName()); + } + // one big query + SystemRemoteResourceSet existingFiles = null; + try + { + existingFiles = targetFS.getRemoteFileObjects(newFilePathList); + } + catch (Exception e) + { + e.printStackTrace(); + } + + + // clear the list so that next time we use renamed names + newFilePathList.clear(); + + + for (int i = 0; i < resources.size() && !resultSet.hasMessage(); i++) + { + if (monitor != null && monitor.isCanceled()) + { + return resultSet; + } + + + IResource srcFileOrFolder = (IResource)resources.get(i); + String name = srcFileOrFolder.getName(); + + if (srcFileOrFolder instanceof IFile) + { + String oldPath = newPathBuf.toString() + name; + if (checkForCollisions) + { + name = checkForCollision(shell, existingFiles, targetFolder, name, oldPath); + if (name == null) + { + continue; + //return null; + } + } + + String newPath = newPathBuf.toString() + name; + + try + { + + String srcCharSet = null; + + + try + { + srcCharSet = ((IFile)srcFileOrFolder).getCharset(false); + if (srcCharSet == null || srcCharSet.length() == 0) + { + srcCharSet = SystemEncodingUtil.ENCODING_UTF_8; + } + } + catch (CoreException e) + { + srcCharSet = SystemEncodingUtil.ENCODING_UTF_8; + } + + + String srcFileLocation = srcFileOrFolder.getLocation().toOSString(); + targetFS.upload(srcFileLocation, srcCharSet, newPath, targetFS.getRemoteEncoding(),monitor); + newFilePathList.add(newPath); + } + + catch (RemoteFileIOException e) + { + resultSet.setMessage(e.getSystemMessage()); + } + catch (SystemMessageException e) + { + resultSet.setMessage(e.getSystemMessage()); + } + + if (resultSet.hasMessage()) + { + return resultSet; + } + } + + else if (srcFileOrFolder instanceof IContainer) + { + IContainer directory = (IContainer) srcFileOrFolder; + if (!directory.exists()) + { + try + { + directory.refreshLocal(IResource.DEPTH_ONE, monitor); + } + catch (Exception e) + { + + } + } + + String newPath = newPathBuf.toString() + name; + + // this is a directory + // recursively copy + try + { + IRemoteFile newTargetFolder = (IRemoteFile)existingFiles.get(newPath); + if (!newTargetFolder.exists()) + { + newTargetFolder = targetFS.createFolder(newTargetFolder); + } + + + boolean isTargetLocal = newTargetFolder.getParentRemoteFileSubSystem().getHost().getSystemType().equals("Local"); + boolean destInArchive = (newTargetFolder instanceof IVirtualRemoteFile) || newTargetFolder.isArchive(); + + if (doCompressedTransfer && doSuperTransferPreference && !destInArchive && !isTargetLocal) + { + compressedCopyWorkspaceResourceToRemote(directory, newTargetFolder, monitor); + } + else + { + IResource[] children = directory.members(); + SystemWorkspaceResourceSet childSet = new SystemWorkspaceResourceSet(directory.members()); + SystemRemoteResourceSet childResults = copyWorkspaceResourcesToRemote(childSet, newTargetFolder, monitor, shell, checkForCollisions); + if (childResults == null) + { + return null; + } + if (childResults.hasMessage()) + { + resultSet.setMessage(childResults.getMessage()); + } + } + + newFilePathList.add(newPath); + } + catch (CoreException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + + + try + { + resultSet = targetFS.getRemoteFileObjects(newFilePathList); + } + catch (Exception e) + { + e.printStackTrace(); + } + return resultSet; + } + + /** + * Perform a copy via drag and drop. + * @param srcFileOrFolder the object to be copied. If the target and source are not on the same system, then this is a + * temporary object produced by the doDrag. + * @param target the object to be copied to. + * @param monitor the progress monitor + * @param shell + * @param indicates whether to check for colllisions or not + * @return the result remote object + */ + public static Object copyWorkspaceResourceToRemote(IResource srcFileOrFolder, IRemoteFile targetFolder, IProgressMonitor monitor, boolean checkForCollisions) + { + Object result = null; + + IRemoteFileSubSystem targetFS = targetFolder.getParentRemoteFileSubSystem(); + + if (targetFolder.isStale()) + { + try + { + targetFolder = targetFS.getRemoteFileObject(targetFolder.getAbsolutePath()); + } + catch (Exception e) + { + } + } + + if (!targetFolder.canWrite()) + { + SystemMessage errorMsg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_SECURITY_ERROR); + errorMsg.makeSubstitution(targetFS.getHostAliasName()); + return errorMsg; + } + + if (!targetFS.isConnected()) + { + return null; + } + + /* + SystemMessage copyMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COPY_PROGRESS); + copyMessage.makeSubstitution(srcFileOrFolder.getName(), targetFolder.getAbsolutePath()); + */ + + String name = srcFileOrFolder.getName(); + + if (srcFileOrFolder instanceof IFile) + { + if (checkForCollisions) + { + name = checkForCollision(targetFolder, name); + if (name == null) + { + return null; + } + } + + boolean isTargetArchive = targetFolder.isArchive(); + if (isTargetArchive && !targetFolder.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) return null; + StringBuffer newPathBuf = new StringBuffer(targetFolder.getAbsolutePath()); + if (isTargetArchive) + { + newPathBuf.append(ArchiveHandlerManager.VIRTUAL_SEPARATOR); + } + else + { + newPathBuf.append(targetFolder.getSeparatorChar()); + } + newPathBuf.append(name); + + String newPath = newPathBuf.toString(); + + try + { + String srcFileLocation = srcFileOrFolder.getLocation().toOSString(); + + String srcCharSet = null; + + boolean isText = SystemFileTransferModeRegistry.getDefault().isText(newPath); + if (isText) + { + try + { + srcCharSet = ((IFile)srcFileOrFolder).getCharset(false); + if (srcCharSet == null || srcCharSet.length() == 0) + { + srcCharSet = SystemEncodingUtil.ENCODING_UTF_8; + } + } + catch (CoreException e) + { + srcCharSet = SystemEncodingUtil.ENCODING_UTF_8; + } + } + + + targetFS.upload(srcFileLocation, srcCharSet, newPath, targetFS.getRemoteEncoding(), monitor); + IRemoteFile copiedFile = targetFS.getRemoteFileObject(targetFolder, name); + + return copiedFile; + } + + catch (RemoteFileIOException e) + { + return e.getSystemMessage(); + } + catch (SystemMessageException e) + { + return e.getSystemMessage(); + } + } + else if (srcFileOrFolder instanceof IContainer) + { + if (checkForCollisions) + { + name = checkForCollision(targetFolder, name); + if (name == null) + { + return null; + } + } + + boolean isTargetArchive = targetFolder.isArchive(); + StringBuffer newPathBuf = new StringBuffer(targetFolder.getAbsolutePath()); + if (isTargetArchive) + { + newPathBuf.append(ArchiveHandlerManager.VIRTUAL_SEPARATOR); + } + else + { + newPathBuf.append(targetFolder.getSeparatorChar()); + } + newPathBuf.append(name); + + String newPath = newPathBuf.toString(); + + IContainer directory = (IContainer) srcFileOrFolder; + + // this is a directory + // recursively copy + try + { + IRemoteFile newTargetFolder = targetFS.getRemoteFileObject(newPath); + if (!newTargetFolder.exists()) + { + targetFS.createFolder(newTargetFolder); + newTargetFolder.markStale(true); + newTargetFolder = targetFS.getRemoteFileObject(newPath); + } + + directory.refreshLocal(IResource.DEPTH_ONE, monitor); + + boolean isTargetLocal = newTargetFolder.getParentRemoteFileSubSystem().getHost().getSystemType().equals("Local"); + boolean destInArchive = (newTargetFolder instanceof IVirtualRemoteFile) || newTargetFolder.isArchive(); + boolean doSuperTransferPreference = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + + if (doCompressedTransfer && doSuperTransferPreference && !destInArchive && !isTargetLocal) + { + compressedCopyWorkspaceResourceToRemote(directory, newTargetFolder, monitor); + } + else + { + IResource[] children = directory.members(); + for (int i = 0; i < children.length; i++) + { + if (monitor.isCanceled()) + { + return null; + } + else + { + IResource child = children[i]; + if (copyWorkspaceResourceToRemote(child, newTargetFolder, monitor, false) == null) + { + return null; + } + } + } + } + return newTargetFolder; + + } + catch (CoreException e) + { + e.printStackTrace(); + } + catch (Exception e) + { + e.printStackTrace(); + } + + return null; + } + + return result; + } + + public static void compressedCopyWorkspaceResourceToRemote(IContainer directory, IRemoteFile newTargetFolder, IProgressMonitor monitor) throws Exception + { + if (!newTargetFolder.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) return; + if (ArchiveHandlerManager.isVirtual(newTargetFolder.getAbsolutePath())) + { + return; + } + IRemoteFile destinationArchive = null; + String newPath = null; + try + { + monitor.beginTask(FileResources.RESID_SUPERTRANSFER_PROGMON_MAIN,IProgressMonitor.UNKNOWN); + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_CREATE); + destinationArchive = getLocalFileSubSystem().getRemoteFileObject(File.createTempFile("supertransfer", getArchiveExtensionFromProperties()).getAbsolutePath()); + FileServiceSubSystem localSS = (FileServiceSubSystem)getLocalFileSubSystem(); + try + { + localSS.delete(destinationArchive, monitor); + } + catch (Exception e) + { + + } + localSS.createFile(destinationArchive); + + if (destinationArchive == null) + { + return; + } + if (!destinationArchive.isArchive()) + { + return; + } + IRemoteFile newTargetParent = newTargetFolder.getParentRemoteFile(); + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_POPULATE); + IRemoteFile sourceDir = localSS.getRemoteFileObject(directory.getLocation().toOSString()); + IRemoteFileSubSystem targetFS = newTargetFolder.getParentRemoteFileSubSystem(); + + + // FIXME + //localSS.copyToArchiveWithEncoding(sourceDir, destinationArchive, sourceDir.getName(), targetFS.getRemoteEncoding(), monitor); + localSS.copy(sourceDir, destinationArchive, sourceDir.getName(), monitor); + + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_TRANSFER); + newPath = newTargetParent.getAbsolutePath() + targetFS.getSeparator() + destinationArchive.getName(); + + // copy local zip to remote + targetFS.upload(destinationArchive.getAbsolutePath(), newPath, monitor); + IRemoteFile remoteArchive = targetFS.getRemoteFileObject(newPath); + + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_EXTRACT); + String compressedFolderPath = newPath + ArchiveHandlerManager.VIRTUAL_SEPARATOR + directory.getName(); + IRemoteFile compressedFolder = targetFS.getRemoteFileObject(compressedFolderPath); + + // extract the compressed folder from the temp archive on remote + targetFS.copy(compressedFolder, newTargetParent, newTargetFolder.getName(), monitor); + + // delete the temp remote archive + targetFS.delete(remoteArchive, monitor); + + monitor.done(); + + } + catch (Exception e) + { + e.printStackTrace(); + if (newPath == null) cleanup(destinationArchive, null); + else cleanup(destinationArchive, new File(newPath)); + throw e; + } + if (newPath == null) cleanup(destinationArchive, null); + else cleanup(destinationArchive, new File(newPath)); + } + + protected static void setReadOnly(IFile file, boolean flag) + { + ResourceAttributes attrs = file.getResourceAttributes(); + attrs.setReadOnly(flag); + try + { + file.setResourceAttributes(attrs); + } + catch (CoreException e) + { + } + } + public static void transferProperties(IResource source, IRemoteFile target, IProgressMonitor monitor) throws CoreException, RemoteFileSecurityException, RemoteFileIOException, SystemMessageException + { + if (monitor.isCanceled()) return; + if (source instanceof IFile) + { + SystemIFileProperties properties = new SystemIFileProperties(source); + target.getParentRemoteFileSubSystem().setLastModified(target, properties.getRemoteFileTimeStamp()); + } + else if (source instanceof IContainer) + { + source.refreshLocal(IResource.DEPTH_ONE, null); + IResource[] children = ((IContainer)source).members(); + for (int i = 0; i < children.length; i++) + { + if (monitor.isCanceled()) + { + return; + } + else + { + IResource child = children[i]; + IRemoteFile newtarget = target.getParentRemoteFileSubSystem().getRemoteFileObject(target, child.getName()); + if (!newtarget.exists()) return; + transferProperties(child, newtarget, monitor); + } + } + } + } + + protected static String getArchiveExtensionFromProperties() + { + + IPreferenceStore store= SystemPlugin.getDefault().getPreferenceStore(); + String archiveType = store.getString(ISystemPreferencesConstants.SUPERTRANSFER_ARC_TYPE); + if (archiveType == null || !ArchiveHandlerManager.getInstance().isRegisteredArchive("test." + archiveType)) + { + archiveType = ".zip"; + } + else + { + archiveType = "." + archiveType; + } + //String archiveType = ".zip"; + return archiveType; + } + + public static IResource compressedCopyRemoteResourceToWorkspace(IRemoteFile directory, IProgressMonitor monitor) throws Exception + { + if (!directory.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) return null; + IRemoteFile destinationArchive = null; + IRemoteFile cpdest = null; + File dest = null; + IResource targetResource = null; + FileServiceSubSystem localSS = (FileServiceSubSystem)getLocalFileSubSystem(); + try + { + monitor.beginTask(FileResources.RESID_SUPERTRANSFER_PROGMON_MAIN,IProgressMonitor.UNKNOWN); + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_CREATE); + File file = File.createTempFile("supertransfer", getArchiveExtensionFromProperties()); + file.delete(); + String separator = ""; + IRemoteFile destinationParent = directory.getParentRemoteFile(); + if (!destinationParent.getAbsolutePath().endsWith(directory.getSeparator())) + separator = directory.getSeparator(); + + + if (destinationParent.canWrite()) + { + try + { + String destArchPath = destinationParent.getAbsolutePath() + separator + file.getName(); + destinationArchive = directory.getParentRemoteFileSubSystem().getRemoteFileObject(destArchPath); + if (destinationArchive.exists()) + { + directory.getParentRemoteFileSubSystem().delete(destinationArchive, monitor); + } + directory.getParentRemoteFileSubSystem().createFile(destinationArchive); + } + catch (RemoteFileSecurityException e) + { + // can't write to this directory + } + } + if (destinationArchive == null) + { + String homeFolder = directory.getParentRemoteFileSubSystem().getRemoteFileObject("./").getAbsolutePath(); + String destArchPath = homeFolder + separator + file.getName(); + destinationArchive = directory.getParentRemoteFileSubSystem().getRemoteFileObject(destArchPath); + if (destinationArchive.exists()) directory.getParentRemoteFileSubSystem().delete(destinationArchive,monitor); + destinationArchive = directory.getParentRemoteFileSubSystem().createFile(destinationArchive); + } + + targetResource = getTempFileFor(directory); + + if (destinationArchive == null) + { + return null; + } + if (!destinationArchive.isArchive()) + { + return null; + } + + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_POPULATE); + IRemoteFileSubSystem sourceFS = directory.getParentRemoteFileSubSystem(); + IRemoteFile sourceDir = sourceFS.getRemoteFileObject(directory.getAbsolutePath()); + + // DKM - copy src dir to remote temp archive + sourceFS.copy(sourceDir, destinationArchive, sourceDir.getName(), monitor); + destinationArchive.markStale(true); + + // reget it so that it's properties (namely "size") are correct + cpdest = destinationArchive = destinationArchive.getParentRemoteFileSubSystem().getRemoteFileObject(destinationArchive.getAbsolutePath()); + + monitor.subTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_TRANSFER); + String name = destinationArchive.getName(); + + // DKM - use parent folder as dest + dest = new File(targetResource.getParent().getLocation().toOSString() + File.separator + name); + sourceFS.download(cpdest, dest, monitor); + + + ISystemArchiveHandler handler = ArchiveHandlerManager.getInstance().getRegisteredHandler(dest); + String sourceEncoding = sourceFS.getRemoteEncoding(); + + VirtualChild[] arcContents = handler.getVirtualChildrenList(); + Display display = Display.getCurrent(); + monitor.beginTask(FileResources.RESID_SUPERTRANSFER_PROGMON_SUBTASK_EXTRACT, arcContents.length); + + for (int i = 0; i < arcContents.length; i++) + { + if (arcContents[i].isDirectory && handler.getVirtualChildren(arcContents[i].fullName) == null) continue; + String currentTargetPath = targetResource.getParent().getLocation().toOSString() + localSS.getSeparator() + useLocalSeparator(arcContents[i].fullName); + IRemoteFile currentTarget = localSS.getRemoteFileObject(currentTargetPath); + boolean replace = false; + + if (currentTarget != null && currentTarget.exists()) + { + IResource currentTargetResource = SystemBasePlugin.getWorkspaceRoot().getContainerForLocation(new Path(currentTarget.getAbsolutePath())); + SystemIFileProperties properties = new SystemIFileProperties(currentTargetResource); + + if (properties.getRemoteFileTimeStamp() != arcContents[i].getTimeStamp()) + { + replace = true; + } + } + else + { + replace = true; + } + + if (replace) + { + + if (!monitor.isCanceled()) + { + String currentSourcePath = dest.getAbsolutePath() + ArchiveHandlerManager.VIRTUAL_SEPARATOR + arcContents[i].fullName; + IRemoteFile currentSource = localSS.getRemoteFileObject(currentSourcePath); + boolean shouldExtract = currentSource.isFile(); + + if (!shouldExtract) + { + // check for empty dir + IRemoteFile[] children = localSS.listFiles(currentSource); + + if (children == null || children.length == 0) + { + shouldExtract = true; + } + } + + if (shouldExtract) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_EXTRACT_PROGRESS); + msg.makeSubstitution(currentSource.getName()); + monitor.subTask(msg.getLevelOneText()); + + boolean isText = currentSource.isText(); + + while (display.readAndDispatch()) { + } + + boolean canWrite = true; + IResource currentTargetResource = SystemBasePlugin.getWorkspaceRoot().getContainerForLocation(new Path(currentTarget.getAbsolutePath())); + if (currentTargetResource != null && currentTargetResource.exists()) + { + try + { + currentTargetResource.delete(false, monitor); + } + catch (Exception e) + { + // don't extract this one + canWrite = false; + } + } + + if (canWrite) + { + localSS.copy(currentSource, currentTarget.getParentRemoteFile(), currentSource.getName(), monitor); + // FIXME localSS.copyFromArchiveWithEncoding(currentSource, currentTarget.getParentRemoteFile(), currentSource.getName(), sourceEncoding, isText, monitor); + + SystemIFileProperties properties = new SystemIFileProperties(currentTargetResource); + properties.setRemoteFileTimeStamp(arcContents[i].getTimeStamp()); + monitor.worked(1); + } + } + } + else + { + //return null; + } + while (display.readAndDispatch()) { + } + } + } + } + catch (Exception e) + { + e.printStackTrace(); + cleanup(cpdest, dest); + throw e; + } + + cleanup(cpdest, dest); + monitor.done(); + return targetResource; + } + + protected static void cleanup(IRemoteFile arc1, File arc2) throws RemoteFileIOException, RemoteFileSecurityException, RemoteFolderNotEmptyException + { + if (arc1 != null) + { + try + { + arc1.getParentRemoteFileSubSystem().delete(arc1, null); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + if (arc2 != null && arc2.exists()) + arc2.delete(); + } + /** + * + */ + protected static String useLocalSeparator(String virtualPath) + { + return virtualPath.replace('/', getLocalFileSubSystem().getSeparatorChar()); + } + + /** + * Returns the corresponding temp file location for a remote file or folder + * @param srcFileOrFolder the remote file or folder + * @return the local replica location + */ + public static IResource getTempFileFor(IRemoteFile srcFileOrFolder) + { + SystemRemoteEditManager editMgr = SystemRemoteEditManager.getDefault(); + if (!editMgr.doesRemoteEditProjectExist()) + { + editMgr.getRemoteEditProject(); + } + + //char separator = IFileConstants.PATH_SEPARATOR_CHAR_WINDOWS; + char separator = '/'; + StringBuffer path = new StringBuffer(editMgr.getRemoteEditProjectLocation().makeAbsolute().toOSString()); + + String actualHost = getActualHostFor(srcFileOrFolder.getParentRemoteFileSubSystem(), srcFileOrFolder.getAbsolutePath()); + path = path.append(separator + actualHost + separator); + + String absolutePath = srcFileOrFolder.getAbsolutePath(); + if (srcFileOrFolder.getSystemConnection().getSystemType().equals("Local")) + { + absolutePath = editMgr.getWorkspacePathFor(actualHost, srcFileOrFolder.getAbsolutePath()); + } + + int colonIndex = absolutePath.indexOf(IPath.DEVICE_SEPARATOR); + + if (colonIndex != -1) + { + if (colonIndex == 0) + { + absolutePath = absolutePath.substring(1); + } + else if (colonIndex == (absolutePath.length() - 1)) + { + absolutePath = absolutePath.substring(0, colonIndex); + } + else + { + absolutePath = absolutePath.substring(0, colonIndex).toLowerCase() + absolutePath.substring(colonIndex + 1); + } + } + + path = path.append(absolutePath); + IPath workspacePath = getLocalPathObject(path.toString()); + + IResource result = null; + if (srcFileOrFolder.isDirectory()) + { + result = SystemBasePlugin.getWorkspaceRoot().getContainerForLocation(workspacePath); + } + else + { + result = SystemBasePlugin.getWorkspaceRoot().getFileForLocation(workspacePath); + } + + return result; + } + + + private static IPath getLocalPathObject(String localPath) + { + IPath actualPath = null; + IPath expectedPath = new Path(localPath); + + IPath rootPath = new Path(_rootPath); + IContainer container = SystemBasePlugin.getWorkspaceRoot().getContainerForLocation(rootPath); + + if (container != null && container.exists()) + { + IResource lastMatch = null; + for (int i = rootPath.segmentCount(); i < expectedPath.segmentCount() - 1; i++) + { + String expectedFolder = expectedPath.segment(i).toLowerCase(); + IResource match = null; + + try + { + IResource[] resources = container.members(); + + for (int r = 0; r < resources.length && match == null; r++) + { + IResource resource = resources[r]; + if (resource instanceof IContainer) + { + String resName = resource.getName().toLowerCase(); + if (expectedFolder.equals(resName)) + { + match = resource; + lastMatch = match; + } + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + + if (match != null) + { + container = (IContainer) match; + } + else if (lastMatch != null) + { + IPath newPath = lastMatch.getLocation(); + while (i < expectedPath.segmentCount()) + { + newPath = newPath.append(expectedPath.segment(i)); + i++; + } + + return newPath; + } + else + { + return expectedPath; + } + } + + String fileName = expectedPath.segment(expectedPath.segmentCount() - 1); + actualPath = container.getLocation().append(fileName); + return actualPath; + } + + return expectedPath; + } + + + public static String getActualHostFor(ISubSystem subsystem, String remotePath) + { + String hostname = subsystem.getHost().getHostName(); + if (subsystem != null && subsystem.getHost().getSystemType().equals("Local")) + { + String result = SystemRemoteEditManager.getDefault().getActualHostFor(hostname, remotePath); + return result; + } + return hostname; + } + + private static void refreshResourceInWorkspace(IResource parent) + { + if (!parent.exists()) + { + refreshResourceInWorkspace(parent.getParent()); + } + else + { + try + { + parent.refreshLocal(IResource.DEPTH_INFINITE, null); + } + catch (Exception e) + { + } + } + } + + protected static boolean isRemoteFileMounted(ISubSystem subsystem, String remotePath) + { + String hostname = subsystem.getHost().getHostName(); + if (subsystem != null && subsystem.getHost().getSystemType().equals("Local")) + { + String result = SystemRemoteEditManager.getDefault().getActualHostFor(hostname, remotePath); + if (!result.equals(hostname)) + { + return true; + } + } + return false; + } + + protected static String getWorkspaceRemotePath(ISubSystem subsystem, String remotePath) + { + if (subsystem != null && subsystem.getHost().getSystemType().equals("Local")) + { + return SystemRemoteEditManager.getDefault().getWorkspacePathFor(subsystem.getHost().getHostName(), remotePath); + } + return remotePath; + } + + protected static String checkForCollision(Shell shell, SystemRemoteResourceSet existingFiles, IRemoteFile targetFolder, String oldName, String oldPath) + { + String newName = oldName; + + IRemoteFileSubSystem ss = targetFolder.getParentRemoteFileSubSystem(); + IRemoteFile targetFileOrFolder = (IRemoteFile)existingFiles.get(oldPath); + + if (targetFileOrFolder != null && targetFileOrFolder.exists()) + { + ValidatorFileUniqueName validator = null; + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(shell, true, targetFileOrFolder, validator); // true => copy-collision-mode + + dlg.open(); + if (!dlg.wasCancelled()) + newName = dlg.getNewName(); + else + newName = null; + } + + + return newName; + } + + protected static String checkForCollision(IRemoteFile targetFolder, String oldName) + { + String newName = oldName; + + try + { + + IRemoteFileSubSystem ss = targetFolder.getParentRemoteFileSubSystem(); + IRemoteFile targetFileOrFolder = ss.getRemoteFileObject(targetFolder, oldName); + + //SystemPlugin.logInfo("CHECKING FOR COLLISION ON '"+srcFileOrFolder.getAbsolutePath() + "' IN '" +targetFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...TARGET FILE: '"+tgtFileOrFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...target.exists()? "+tgtFileOrFolder.exists()); + if (targetFileOrFolder.exists()) + { + //monitor.setVisible(false); wish we could! + + // we no longer have to set the validator here... the common rename dialog we all now use queries the input + // object's system view adaptor for its name validator. See getNameValidator in SystemViewRemoteFileAdapter. phil + ValidatorFileUniqueName validator = null; // new ValidatorFileUniqueName(shell, targetFolder, srcFileOrFolder.isDirectory()); + //SystemCollisionRenameDialog dlg = new SystemCollisionRenameDialog(shell, validator, oldName); + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(SystemBasePlugin.getActiveWorkbenchShell(), true, targetFileOrFolder, validator); // true => copy-collision-mode + + dlg.open(); + if (!dlg.wasCancelled()) + newName = dlg.getNewName(); + else + newName = null; + } + } + catch (SystemMessageException e) + { + SystemBasePlugin.logError("SystemCopyRemoteFileAction.checkForCollision()", e); + } + + return newName; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemOpenSearchPageAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemOpenSearchPageAction.java new file mode 100644 index 00000000000..f731576d30a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemOpenSearchPageAction.java @@ -0,0 +1,62 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.search; + +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.search.ui.NewSearchUI; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.IWorkbenchWindowActionDelegate; + + +public class SystemOpenSearchPageAction implements IWorkbenchWindowActionDelegate { + + private IWorkbenchWindow window; + + /** + * Constructor for open remote search page action. + */ + public SystemOpenSearchPageAction() { + super(); + } + + /** + * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose() + */ + public void dispose() { + } + + /** + * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow) + */ + public void init(IWorkbenchWindow window) { + this.window = window; + } + + /** + * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) + */ + public void run(IAction action) { + NewSearchUI.openSearchDialog(window, SystemSearchPage.SYSTEM_SEARCH_PAGE_ID); + } + + /** + * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchPage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchPage.java new file mode 100644 index 00000000000..c8093f5a9ab --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchPage.java @@ -0,0 +1,1463 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.search; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.actions.SystemSelectRemoteFolderAction; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemProfile; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.SystemSearchString; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.services.clientserver.search.SystemSearchUtil; +import org.eclipse.rse.services.search.HostSearchResultSet; +import org.eclipse.rse.services.search.IHostSearchResultConfiguration; +import org.eclipse.rse.services.search.IHostSearchResultConfigurationFactory; +import org.eclipse.rse.services.search.IHostSearchResultSet; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.servicesubsystem.FileServiceSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.search.SystemSearchUI; +import org.eclipse.rse.ui.view.search.SystemSearchViewPart; +import org.eclipse.search.ui.ISearchPage; +import org.eclipse.search.ui.ISearchPageContainer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + + +/** + * This class provides the universal search page in the Search. + */ +public class SystemSearchPage extends DialogPage implements ISearchPage { + + public static final String SYSTEM_SEARCH_PAGE_ID = "com.ibm.etools.systems.core.search.searchPage"; + + // search utility + private SystemSearchUtil util; + + // search page container + private ISearchPageContainer container; + + // flag to indicate whether showing the dialog for the first time + private boolean isFirstShow = true; + + // search string controls + private Label stringLabel; + private Combo stringCombo; + private Button caseButton; + private Label stringHintLabel; + private Button stringRegexButton; + private boolean initialCaseSensitive; + private boolean initialStringRegex; + + // file name controls + private Label fileNameLabel; + private Combo fileNameCombo; + private Button fileNameBrowseButton; + private Label fileNameHintLabel; + private Button fileNameRegexButton; + private boolean initialFileNameRegex; + + // file name editor + private FileNameEditor fileNameEditor; + + // folder name controls + private Label folderNameLabel; + private Combo folderNameCombo; + private Button folderNameBrowseButton; + + // folder name editor + private FolderNameEditor folderNameEditor; + + // advanced controls + private Button searchArchivesButton; + private Button searchSubfoldersButton; + private boolean initialSearchArchives; + private boolean initialSearchSubfolders; + + // constants for storing configuration + private static final String REMOTE_SEARCH_PAGE_NAME = "RemoteSearchPage"; + private static final String STORE_CONFIG_CASE_SENSITIVE = "caseSensitive"; + private static final String STORE_CONFIG_STRING_REGEX = "stringRegex"; + private static final String STORE_CONFIG_FILENAME_REGEX = "fileNameRegex"; + private static final String STORE_CONFIG_INCLUDE_ARCHIVES = "includeArchives"; + private static final String STORE_CONFIG_INCLUDE_SUBFOLDERS = "includeSubfolders"; + + private static final String STORE_CONFIG_DATA_SIZE = "dataSize"; + + // constants for storing data + private static final String STORE_DATA_PREFIX = REMOTE_SEARCH_PAGE_NAME + ".data"; + private static final String STORE_DATA_SEARCH_STRING = "searchString"; + private static final String STORE_DATA_CASE_SENSITIVE = "caseSensitive"; + private static final String STORE_DATA_STRING_REGEX = "stringRegex"; + private static final String STORE_DATA_FILE_NAMES = "fileNames"; + private static final String STORE_DATA_FILE_NAME_REGEX = "fileNameRegex"; + private static final String STORE_DATA_PROFILE_NAME = "profileName"; + private static final String STORE_DATA_CONNECTION_NAME = "connectionName"; + private static final String STORE_DATA_FOLDER_NAME = "folderName"; + private static final String STORE_DATA_INCLUDE_ARCHIVES = "includeArchives"; + private static final String STORE_DATA_INCLUDE_SUBFOLDERS = "includeSubfolders"; + + // a list to hold previous searche data + private List previousSearchData = new ArrayList(); + + // maximum size of data list + private static final int MAX_DATA_SIZE = 20; + + // inner class to hold search data + private class RemoteSearchData { + + private String searchString; + private boolean caseSensitive; + private boolean stringRegex; + private String fileNames; + private boolean fileNameRegex; + private String profileName; + private String connectionName; + private String folderName; + private boolean includeArchives; + private boolean includeSubfolders; + + /** + * Constructor for search data. + * @param searchString the search string. + * @param caseSensitive true if case sensitive, false otherwise. + * @param stringRegex true if search string is a regular expression, false otherwise. + * @param fileNames set of file names. + * @param fileNameRegex true if the file name is a regular expression, false otherwise. + * @param profileName the profile name. + * @param connectionName the connection name. + * @param folderName the folder name. + * @param includeArchives true if archives should also be searched, false otherwise. + * @param includeSubfolders true if subfolders should also be searched, false otherwise. + */ + private RemoteSearchData(String searchString, boolean caseSensitive, boolean stringRegex, + String fileNames, boolean fileNameRegex, String profileName, String connectionName, + String folderName, boolean includeArchives, boolean includeSubfolders) { + this.searchString = searchString; + this.caseSensitive = caseSensitive; + this.stringRegex = stringRegex; + this.fileNames = fileNames; + this.fileNameRegex = fileNameRegex; + this.profileName = profileName; + this.connectionName = connectionName; + this.folderName = folderName; + this.includeArchives = includeArchives; + this.includeSubfolders = includeSubfolders; + } + } + + // abstract inner class for handling a combo and browse button combination + abstract private class CommonEditor extends SelectionAdapter implements DisposeListener { + + protected Combo nameCombo; + protected Button browseButton; + + /** + * Constructor for editor. + * @param nameCombo the combo. + * @param browseButton the browse button. + */ + private CommonEditor(Combo nameCombo, Button browseButton) { + this.nameCombo = nameCombo; + this.browseButton = browseButton; + + // add dispose listeners to both the combo and the button + // we make them null when they are disposed for cleanup to occur + nameCombo.addDisposeListener(this); + browseButton.addDisposeListener(this); + + // add selection listener to the browse button + browseButton.addSelectionListener(this); + } + + /** + * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent) + */ + public void widgetDisposed(DisposeEvent e) { + + if (e.widget == nameCombo) { + nameCombo = null; + } + else if (e.widget == browseButton) { + browseButton = null; + } + } + + /** + * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + public void widgetSelected(SelectionEvent e) { + + if (e.widget == browseButton) { + handleBrowseSelected(); + } + } + + protected abstract void handleBrowseSelected(); + } + + // inner class to handle file name editing + private class FileNameEditor extends CommonEditor { + + /** + * Constructor for folder name editor. + * @param fileCombo the file combo. + * @param browseButton the file types browse button. + */ + private FileNameEditor(Combo fileCombo, Button browseButton) { + super(fileCombo, browseButton); + } + + /** + * @see org.eclipse.rse.files.ui.search.SystemSearchPage.CommonEditor#handleBrowseSelected() + */ + protected void handleBrowseSelected() { + + // get the shell from the page + Shell shell = SystemSearchPage.this.getShell(); + + // create select file types action that opens the select file types dialog + SystemSearchSelectFileTypesAction action = new SystemSearchSelectFileTypesAction(shell); + + // get current types list from the combo + List prevTypes = util.typesStringToList(getFileNamesText()); + + // set the preselection of the select file types dialog to the current list of types in the combo + action.setTypes(prevTypes); + + // run the action + action.run(); + + // if the user did not cancel from the dialog + if (!action.wasCancelled()) { + + // get the types the user chose in the dialog + List newTypes = action.getTypes(); + + // set the combo to have the new types + setFileNamesText(util.typesListToString(newTypes)); + } + } + + /** + * Sets the file names text. + * @param fileNames the file names string. + */ + private void setFileNamesText(String fileNames) { + nameCombo.setText(fileNames); + } + + /** + * Gets the text in the file names combo. + * @return the file names text. + */ + private String getFileNamesText() { + return nameCombo.getText(); + } + } + + // inner class to handle folder name editing + private class FolderNameEditor extends CommonEditor { + + // holds info for each item in the folder combo + private class Info { + private String profileName; + private String connectionName; + private String folderPath; + + private Info(String profileName, String connectionName, String folderPath) { + this.profileName = profileName; + this.connectionName = connectionName; + this.folderPath = folderPath; + } + } + + // the current info + // TODO: needs to go when we show profile name in the folder combo + private Info currInfo; + + /** + * Constructor for folder name editor. + * @param folderCombo the folder name combo. + * @param browseButton the folder browse button. + */ + private FolderNameEditor(Combo folderCombo, Button browseButton) { + super(folderCombo, browseButton); + + // add selection listener to the folder combo + folderCombo.addSelectionListener(this); + } + + /** + * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + public void widgetSelected(SelectionEvent e) { + + // if the selected widget is the browse button, let the super class handle it + if (e.widget == browseButton) { + super.widgetSelected(e); + } + // otherwise if the selected widget is the folder combo, then get the selection index + // and get the data associated with that index + // TODO: needs to go when we show profile name in the folder combo + else if (e.widget == nameCombo){ + int selectionIndex = nameCombo.getSelectionIndex(); + currInfo = getInfo(selectionIndex); + } + else { + super.widgetSelected(e); + } + } + + /** + * @see org.eclipse.rse.files.ui.search.SystemSearchPage.CommonEditor#handleBrowseSelected() + */ + protected void handleBrowseSelected() { + + // get the shell from the page + Shell shell = SystemSearchPage.this.getShell(); + + // create select folder action which opens the select folder dialog + SystemSelectRemoteFolderAction selectFolderAction = new SystemSelectRemoteFolderAction(shell); + selectFolderAction.setShowNewConnectionPrompt(true); + selectFolderAction.setShowPropertySheet(true, false); + selectFolderAction.setNeedsProgressMonitor(true); + selectFolderAction.setMultipleSelectionMode(false); + + // run the action + selectFolderAction.run(); + + // if the user did not cancel out of the dialog + if (!selectFolderAction.wasCancelled()) { + // store remote path + IRemoteFile remoteFile = selectFolderAction.getSelectedFolder(); + String folderPath = remoteFile.getAbsolutePath(); + + // store connection and profile + IHost conn = selectFolderAction.getSelectedConnection(); + String profileName = conn.getSystemProfileName(); + String connectionName = conn.getAliasName(); + + setFolderText(profileName, connectionName, folderPath); + } + } + + /** + * Sets the folder name combo text. Also sets the profile name, connection name and folder path. + * @param profileName the profile name. + */ + private void setFolderText(String profileName, String connectionName, String folderPath) { + + String text = getFormattedText(profileName, connectionName, folderPath); + + // get existing items in the combo + String[] currItems = nameCombo.getItems(); + int selectionIndex = -1; + boolean matchFound = false; + + // see if one of the entries match + for (int i = 0; i < currItems.length; i++) { + + if (currItems[i].equals(text)) { + selectionIndex = i; + matchFound = true; + break; + } + } + + // if no matches found, we add our text to the end of the list of items in the combo and select it + // note that we can't simply call setText() because this is a read-only combo + if (!matchFound) { + int oldLength = currItems.length; + String[] newItems = new String[oldLength + 1]; + System.arraycopy(currItems, 0, newItems, 0, currItems.length); + newItems[oldLength] = text; + nameCombo.setItems(newItems); + selectionIndex = oldLength; + + // TODO: needs to go when we show profile name in the folder combo + addData(selectionIndex, profileName, connectionName, folderPath); + } + + // select from the current index + nameCombo.select(selectionIndex); + + currInfo = getInfo(selectionIndex); + } + + /** + * Convert to text. + * @return the string representation. + */ + private String getFormattedText(String profileName, String connectionName, String folderPath) { + // TODO: prefix with profile name after checking preference ?? + // then we will no longer need to store data in the combo, which is a very inelegant solution + // we can simply parse whatever comes out of getText() and get profile name, connection name + // and folder path + return connectionName + ":" + folderPath; + } + + /** + * Add data. + * @param index the index for which this data applies. + * @param profileName the profile name. + * @param connectionName the connection name. + * @param folderPath the folder path. + */ + private void addData(int index, String profileName, String connectionName, String folderPath) { + Info info = new Info(profileName, connectionName, folderPath); + nameCombo.setData(String.valueOf(index), info); + } + + /** + * Gets the info for a given index. + * @param index the index. + * @return the info for the index. + */ + private Info getInfo(int index) { + return (Info)(nameCombo.getData(String.valueOf(index))); + } + + /** + * Returns the profile name. + * @return the profile name, or null if none specified. + */ + private String getProfileName() { + return currInfo.profileName; + } + + /** + * Returns the connection name. + * @return the connection name, or null if none specified. + */ + private String getConnectionName() { + return currInfo.connectionName; + } + + /** + * Returns the folder path. + * @return the folder path, or null if none specified. + */ + private String getFolderPath() { + return currInfo.folderPath; + } + } + + /** + * This contructor instantiates a remote search page. + */ + public SystemSearchPage() { + super(); + this.util = SystemSearchUtil.getInstance(); + } + + /** + * Gets the search data from current state of the dialog. If the search string matches a previous + * search data search string, then that data is deleted and replaced with the new data. + * @return the search data corresponding to the current state of the dialog. + */ + private RemoteSearchData getSearchData() { + RemoteSearchData data = null; + String searchString = stringCombo.getText(); + + int i = previousSearchData.size() - 1; + + boolean matchFound = false; + + // go through stored search data, and see if one has the search string + // matching our current search string + while (i >= 0) { + data = (RemoteSearchData)previousSearchData.get(i); + + if (searchString.equals(data.searchString)) { + matchFound = true; + break; + } + + i--; + } + + // if a match has been found, modify its properties + if (matchFound) { + data.searchString = searchString; + data.caseSensitive = caseButton.getSelection(); + data.stringRegex = stringRegexButton.getSelection(); + data.fileNames = getFileNames(); + data.fileNameRegex = fileNameRegexButton.getSelection(); + data.profileName = getProfileName(); + data.connectionName = getConnectionName(); + data.folderName = getFolderName(); + data.includeArchives = searchArchivesButton.getSelection(); + data.includeSubfolders = searchSubfoldersButton.getSelection(); + + // remove data from the list because it will be later added + // we want to basically move the data to the end of the list + previousSearchData.remove(data); + } + // otherwise create new data + else { + data = new RemoteSearchData(searchString, caseButton.getSelection(), stringRegexButton.getSelection(), + getFileNames(), fileNameRegexButton.getSelection(), getProfileName(), getConnectionName(), + getFolderName(), searchArchivesButton.getSelection(), searchSubfoldersButton.getSelection()); + } + + // if the data size is the maximum size allowable, + // remove the first entry from the list + if (previousSearchData.size() == MAX_DATA_SIZE) { + previousSearchData.remove(0); + } + + // now add the data to the data list + previousSearchData.add(data); + + return data; + } + + /** + * Gets the file names string. + * @return the file names string. + */ + private String getFileNames() { + return fileNameEditor.getFileNamesText(); + } + + /** + * Gets the profile name from the folder selection. + * @return the profile name. + */ + private String getProfileName() { + return folderNameEditor.getProfileName(); + } + + /** + * Gets the connection name from the folder selection. + * @return the connection name. + */ + private String getConnectionName() { + return folderNameEditor.getConnectionName(); + } + + /** + * Gets the folder name from the folder selection. + * @return the folder name. + */ + private String getFolderName() { + return folderNameEditor.getFolderPath(); + } + + /** + * @see org.eclipse.search.ui.ISearchPage#performAction() + */ + public boolean performAction() { + + // if the string is a regex, check that the regular expression is valid + // if not show error and return false + if (stringRegexButton.getSelection()) { + String searchString = stringCombo.getText(); + + if (searchString != null && searchString.length() != 0) { + + if (!util.isValidRegex(searchString)) { + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_REMOTE_SEARCH_INVALID_REGEX); + message.makeSubstitution(searchString); + SystemMessageDialog.displayErrorMessage(getShell(), message); + stringCombo.setFocus(); + return false; + } + } + } + + // if the file name is a regex, check that the regular expression is valid + // if not show error and return false + if (fileNameRegexButton.getSelection()) { + String fileNameString = fileNameEditor.getFileNamesText(); + + if (fileNameString != null && fileNameString.length() != 0) { + + if (!util.isValidRegex(fileNameString)) { + SystemMessage message = SystemPlugin.getPluginMessage(ISystemMessages.MSG_REMOTE_SEARCH_INVALID_REGEX); + message.makeSubstitution(fileNameString); + SystemMessageDialog.displayErrorMessage(getShell(), message); + fileNameCombo.setFocus(); + return false; + } + } + } + + // get the data corresponding to the current dialog state + RemoteSearchData data = getSearchData(); + + SystemSearchString searchString = new SystemSearchString(data.searchString, data.caseSensitive, data.stringRegex, data.fileNames, data.fileNameRegex, data.includeArchives, data.includeSubfolders); + + IRemoteFileSubSystem subsys = getRemoteFileSubSystem(data.profileName, data.connectionName); + + if (subsys == null) { + return false; + } + + IRemoteFile remoteFile; + + try { + remoteFile = subsys.getRemoteFileObject(data.folderName); + } + catch (SystemMessageException e) { + // TODO: show error + SystemBasePlugin.logError("Error occured trying to get remote file object", e); + return false; + } + + + + + // create a search result set to contain all the results + IHostSearchResultSet set = new HostSearchResultSet(); + + if (subsys instanceof FileServiceSubSystem) + { + + + // set the name + String name = remoteFile.getAbsolutePath() + " - " + searchString.getFileNamesString() + "(" + searchString.getTextString() + ")"; + set.setName(name); + + FileServiceSubSystem ss = (FileServiceSubSystem)subsys; + IHostSearchResultConfiguration config = ss.createSearchConfiguration(set, remoteFile, searchString); + + // show results in remote search view + showInView(set); + + // kick off the search + ss.search(config); + + // save the configuration + writeConfiguration(); + + // finally save the data + writeData(); + } + + + + + return true; + } + + /** + * Show the search results in the remote search view. + * @param resultSet the search result set. + */ + private void showInView(IHostSearchResultSet resultSet) + { + SystemSearchUI searchUI = SystemSearchUI.getInstance(); + SystemSearchViewPart searchPart = searchUI.activateSearchResultView(); + searchPart.addSearchResult((IAdaptable)resultSet); + } + + + + /** + * @see org.eclipse.search.ui.ISearchPage#setContainer(org.eclipse.search.ui.ISearchPageContainer) + */ + public void setContainer(ISearchPageContainer container) { + this.container = container; + } + + /** + * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean) + */ + public void setVisible(boolean visible) { + + // if we are to become visible + if (visible) { + + // if it is the very first time, then set the items for the string combo and file name combo + // and initialize from selection + if (isFirstShow) { + isFirstShow = false; + + // read in the data + readData(); + + // we set items and text here, rather than during createControl() to prevent page from resizing + setPreviousSearchStrings(); + setPreviousFileNames(); + setPreviousFolderNames(); + initialize(); + } + + // set focus to the string combo every time we become visible + stringCombo.setFocus(); + + // indicate whether search is allowed + container.setPerformActionEnabled(isValid()); + } + + super.setVisible(visible); + } + + /** + * Obtains the search strings from previous search data and adds them to the search string combo. + */ + private void setPreviousSearchStrings() { + int size = previousSearchData.size(); + + // array to hold previous search strings + String[] searchStrings = new String[size]; + + for (int i = 0; i < size; i++) { + searchStrings[i] = ((RemoteSearchData)previousSearchData.get(size - 1 - i)).searchString; + } + + stringCombo.setItems(searchStrings); + } + + /** + * Obtains the file name strings from previous search data and adds them to the file name combo. + */ + private void setPreviousFileNames() { + int size = previousSearchData.size(); + + // list to hold type strings + List typesStringList = new ArrayList(size); + + // go through the search data starting from the end + for (int i = size - 1; i >= 0; i--) { + RemoteSearchData data = (RemoteSearchData)previousSearchData.get(i); + + // now get the types string representing the list of types in the data + String typeString = data.fileNames; + + // check if we already have this types string in the types string list + // if not, add it + if (!typesStringList.contains(typeString)) { + typesStringList.add(typeString); + } + } + + String[] typesStringArray = (String[])typesStringList.toArray(new String[typesStringList.size()]); + + fileNameCombo.setItems(typesStringArray); + } + + /** + * Obtains the folder name strings from previous search data and adds them to the folder name combo. + */ + private void setPreviousFolderNames() { + int size = previousSearchData.size(); + + // list to hold folder names + List folderNamesList = new ArrayList(size); + + int j = 0; + + // go through the search data starting from the end + for (int i = size - 1; i >= 0; i--) { + RemoteSearchData data = (RemoteSearchData)previousSearchData.get(i); + + // get the string from the folder name editor + String folderNameString = folderNameEditor.getFormattedText(data.profileName, data.connectionName, data.folderName); + + if (!folderNamesList.contains(folderNameString)) { + folderNamesList.add(folderNameString); + + // add combo data + // TODO: needs to go when we show profile name in the folder name combo + folderNameEditor.addData(j, data.profileName, data.connectionName, data.folderName); + j++; + } + } + + String[] folderNamesArray = (String[])folderNamesList.toArray(new String[folderNamesList.size()]); + + folderNameCombo.setItems(folderNamesArray); + } + + /** + * Initializes the dialog. + */ + private void initialize() { + + ISelection selection = container.getSelection(); + + String text = null; + String fileName = null; + String profileName = null; + String connectionName = null; + String folderName = null; + + // if selection is not empty, we handle structured selection or text selection + if (selection != null && !selection.isEmpty()) { + + // if it is a structured selection + if (selection instanceof IStructuredSelection) { + Object obj = ((IStructuredSelection)selection).getFirstElement(); + + // check if it is a remote file + if (obj instanceof IRemoteFile) { + + IRemoteFile remoteFile = (IRemoteFile)obj; + boolean supportsArchiveManagement = remoteFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + + // if it's a file, but not an archive, get the file name, connection info, and parent folder name + if (remoteFile.isFile() && (!remoteFile.isArchive() && !supportsArchiveManagement)) { + fileName = remoteFile.getName(); + IHost conn = remoteFile.getSystemConnection(); + profileName = conn.getSystemProfileName(); + connectionName = conn.getAliasName(); + folderName = remoteFile.getParentPath(); + } + // otherwise if it's a folder or an arvhive, get the connection info and the name + else if (remoteFile.isDirectory() || (remoteFile.isArchive() && supportsArchiveManagement)) { + IHost conn = remoteFile.getSystemConnection(); + profileName = conn.getSystemProfileName(); + connectionName = conn.getAliasName(); + folderName = remoteFile.getAbsolutePath(); + } + } + } + // otherwise, if it is a text selection + else if (selection instanceof ITextSelection) { + ITextSelection textSelection = (ITextSelection)selection; + text = textSelection.getText(); + } + } + + // if text is null, then make it "*" + if (text == null || text.equals("")) { + text = "*"; + } + // otherwise, make sure to escape the special characters so that we actually search for the + // string with the special characters + else { + text = insertEscapeChar(text); + } + + stringCombo.setText(text); + + // if the file name is still null, set it to "*" + if (fileName == null) { + fileName = "*"; + } + + // set the file name + fileNameEditor.setFileNamesText(fileName); + + // set the remote folder combo properties if profile name, connection name and folder path are + // not null + if (profileName != null && connectionName != null && folderName != null) { + folderNameEditor.setFolderText(profileName, connectionName, folderName); + } + } + + /** + * Inserts escape character '\' for literals '*', '?' and '\\'. + * @param text the text. + * @return the text with the escape character inserted as needed, or "" if the given text is null, + * or an error occurs. + */ + private String insertEscapeChar(String text) { + + if (text == null || text.equals("")) { + return ""; + } + + StringBuffer sbIn = new StringBuffer(text); + BufferedReader reader = new BufferedReader(new StringReader(text)); + int lengthOfFirstLine = 0; + + try { + lengthOfFirstLine = reader.readLine().length(); + } + catch (IOException ex) { + return ""; + } + + StringBuffer sbOut = new StringBuffer(lengthOfFirstLine + 5); + int i = 0; + + while (i < lengthOfFirstLine) { + char ch = sbIn.charAt(i); + + if (ch == '*' || ch == '?' || ch == '\\') { + sbOut.append("\\"); + } + + sbOut.append(ch); + + i = i + 1; + } + + return sbOut.toString(); + } + + /** + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(Composite parent) { + + // compute horizontal and vertical units + initializeDialogUnits(parent); + + // read configuration + readConfiguration(); + + // main composite + Composite main = new Composite(parent, SWT.NONE); + GridLayout mainLayout = new GridLayout(3, false); + mainLayout.horizontalSpacing = 10; + main.setLayout(mainLayout); + GridData gd = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); + gd.horizontalSpan = 3; + main.setLayoutData(gd); + + // create controls for search string + createSearchStringControls(main); + + // create controls for file name + createFileNameControls(main); + + // create controls for folder + createFolderControls(main); + + // create advanced options controls + createAdvancedControls(main); + + // set mnemonics + SystemWidgetHelpers.setMnemonics(parent); + + // set the top level control + setControl(main); + + // set help + SystemWidgetHelpers.setHelp(main, SystemPlugin.HELPPREFIX + "rsdi0000"); + } + + /** + * Creates controls for users to specify the search string. + * @param comp the parent composite. + */ + private void createSearchStringControls(Composite comp) { + + // label introducing string combo + stringLabel = new Label(comp, SWT.LEFT); + stringLabel.setText(FileResources.RESID_SEARCH_STRING_LABEL_LABEL); + stringLabel.setToolTipText(FileResources.RESID_SEARCH_STRING_LABEL_TOOLTIP); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 3; + stringLabel.setLayoutData(gd); + + // string combo + stringCombo = new Combo(comp, SWT.SINGLE | SWT.BORDER); + stringCombo.setToolTipText(FileResources.RESID_SEARCH_STRING_COMBO_TOOLTIP); + + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan = 2; + stringCombo.setLayoutData(gd); + + stringCombo.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + container.setPerformActionEnabled(isValid()); + } + }); + + stringCombo.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + handleStringComboSelected(); + } + }); + + // checkbox for case sensitive + caseButton = new Button(comp, SWT.CHECK); + caseButton.setText(FileResources.RESID_SEARCH_CASE_BUTTON_LABEL); + caseButton.setToolTipText(FileResources.RESID_SEARCH_CASE_BUTTON_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + caseButton.setLayoutData(gd); + caseButton.setSelection(initialCaseSensitive); + + // label explaining special characters + stringHintLabel = new Label(comp, SWT.LEFT); + stringHintLabel.setText(FileResources.RESID_SEARCH_STRING_HINT_LABEL); + stringHintLabel.setToolTipText(FileResources.RESID_SEARCH_STRING_HINT_TOOLTIP); + + gd = new GridData(GridData.BEGINNING); + gd.horizontalSpan = 2; + stringHintLabel.setLayoutData(gd); + + // checkbox for regex + stringRegexButton = new Button(comp, SWT.CHECK); + stringRegexButton.setText(FileResources.RESID_SEARCH_STRING_REGEX_LABEL); + stringRegexButton.setToolTipText(FileResources.RESID_SEARCH_STRING_REGEX_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + stringRegexButton.setLayoutData(gd); + stringRegexButton.setSelection(initialStringRegex); + stringHintLabel.setVisible(!stringRegexButton.getSelection()); + + stringRegexButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + stringHintLabel.setVisible(!stringRegexButton.getSelection()); + } + }); + } + + /** + * Handles selection of an item from the string combo. Sets the dialog state for the + * selection data corrsponding to the search string selection. + */ + private void handleStringComboSelected() { + + if (stringCombo.getSelectionIndex() < 0) { + return; + } + + int index = previousSearchData.size() - 1 - stringCombo.getSelectionIndex(); + + RemoteSearchData data = (RemoteSearchData)previousSearchData.get(index); + + if (data == null || !stringCombo.getText().equals(data.searchString)) { + return; + } + + // set search string properties + stringCombo.setText(data.searchString); + + // set case sensitive + caseButton.setSelection(data.caseSensitive); + + // set string regex + stringHintLabel.setVisible(!data.stringRegex); + stringRegexButton.setSelection(data.stringRegex); + + // set types list + fileNameEditor.setFileNamesText(data.fileNames); + + // set file name regex + fileNameHintLabel.setVisible(!data.fileNameRegex); + fileNameRegexButton.setSelection(data.fileNameRegex); + + // set the remote folder properties + folderNameEditor.setFolderText(data.profileName, data.connectionName, data.folderName); + + // set search archive + searchArchivesButton.setSelection(data.includeArchives); + + // set search subfolders + searchSubfoldersButton.setSelection(data.includeSubfolders); + } + + /** + * Gets the remote file subsystem for the given profile name and connection name. + * @return the remote file subsystem, or null if the profile or connection does not exist. + */ + private IRemoteFileSubSystem getRemoteFileSubSystem(String profName, String connName) { + + if (profName == null || connName == null) { + return null; + } + else { + ISystemRegistry reg = SystemPlugin.getTheSystemRegistry(); + ISystemProfile profile = reg.getSystemProfile(profName); + + if (profile == null) { + return null; + } + + IHost conn = reg.getHost(profile, connName); + + if (conn == null) { + return null; + } + + return RemoteFileUtility.getFileSubSystem(conn); + } + } + + /** + * Creates controls to specify file name. + * @param comp the parent composite. + */ + private void createFileNameControls(Composite comp) { + + // label introducing file name combo + fileNameLabel = new Label(comp, SWT.LEFT); + fileNameLabel.setText(FileResources.RESID_SEARCH_FILENAME_LABEL_LABEL); + fileNameLabel.setToolTipText(FileResources.RESID_SEARCH_FILENAME_LABEL_TOOLTIP); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 3; + fileNameLabel.setLayoutData(gd); + + // file name combo + fileNameCombo = new Combo(comp, SWT.SINGLE | SWT.BORDER); + fileNameCombo.setToolTipText(FileResources.RESID_SEARCH_FILENAME_COMBO_TOOLTIP); + + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan = 2; + fileNameCombo.setLayoutData(gd); + + fileNameCombo.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + container.setPerformActionEnabled(isValid()); + } + }); + + // browse types button + fileNameBrowseButton = new Button(comp, SWT.PUSH); + fileNameBrowseButton.setText(FileResources.RESID_SEARCH_FILENAME_BROWSE_LABEL); + fileNameBrowseButton.setToolTipText(FileResources.RESID_SEARCH_FILENAME_BROWSE_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + fileNameBrowseButton.setLayoutData(gd); + + // create the file name editor + fileNameEditor = new FileNameEditor(fileNameCombo, fileNameBrowseButton); + + // label explaining special characters + fileNameHintLabel = new Label(comp, SWT.LEFT); + fileNameHintLabel.setText(FileResources.RESID_SEARCH_FILENAME_HINT_LABEL); + fileNameHintLabel.setToolTipText(FileResources.RESID_SEARCH_FILENAME_HINT_TOOLTIP); + + gd = new GridData(GridData.BEGINNING); + gd.horizontalSpan = 2; + fileNameHintLabel.setLayoutData(gd); + + // checkbox for regex + fileNameRegexButton = new Button(comp, SWT.CHECK); + fileNameRegexButton.setText(FileResources.RESID_SEARCH_FILENAME_REGEX_LABEL); + fileNameRegexButton.setToolTipText(FileResources.RESID_SEARCH_FILENAME_REGEX_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + fileNameRegexButton.setLayoutData(gd); + fileNameRegexButton.setSelection(initialFileNameRegex); + fileNameHintLabel.setVisible(!fileNameRegexButton.getSelection()); + + fileNameRegexButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + fileNameHintLabel.setVisible(!fileNameRegexButton.getSelection()); + } + }); + } + + /** + * Creates controls to specify folder name. + */ + private void createFolderControls(Composite comp) { + + // label introducing folder name combo + folderNameLabel = new Label(comp, SWT.LEFT); + folderNameLabel.setText(FileResources.RESID_SEARCH_FOLDERNAME_LABEL_LABEL); + folderNameLabel.setToolTipText(FileResources.RESID_SEARCH_FOLDERNAME_LABEL_TOOLTIP); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 3; + folderNameLabel.setLayoutData(gd); + + // folder name combo + folderNameCombo = new Combo(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY); + folderNameCombo.setToolTipText(FileResources.RESID_SEARCH_FOLDERNAME_COMBO_TOOLTIP); + + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan = 2; + folderNameCombo.setLayoutData(gd); + + folderNameCombo.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + container.setPerformActionEnabled(isValid()); + } + }); + + // browse types button + folderNameBrowseButton = new Button(comp, SWT.PUSH); + folderNameBrowseButton.setText(FileResources.RESID_SEARCH_FOLDERNAME_BROWSE_LABEL); + folderNameBrowseButton.setToolTipText(FileResources.RESID_SEARCH_FOLDERNAME_BROWSE_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + folderNameBrowseButton.setLayoutData(gd); + + // create the folder name editor + folderNameEditor = new FolderNameEditor(folderNameCombo, folderNameBrowseButton); + } + + /** + * Creates controls for advanced options. + */ + private void createAdvancedControls(Composite comp) { + + // dummy label + Label dummyLabel = new Label(comp, SWT.LEFT); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 3; + dummyLabel.setLayoutData(gd); + + // checkbox for search in archive files + searchArchivesButton = new Button(comp, SWT.CHECK); + searchArchivesButton.setText(FileResources.RESID_SEARCH_INCLUDE_ARCHIVES_LABEL); + searchArchivesButton.setToolTipText(FileResources.RESID_SEARCH_INCLUDE_ARCHIVES_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 1; + searchArchivesButton.setLayoutData(gd); + + searchArchivesButton.setSelection(initialSearchArchives); + + // checkbox for search in subfolders + searchSubfoldersButton = new Button(comp, SWT.CHECK); + searchSubfoldersButton.setText(FileResources.RESID_SEARCH_INCLUDE_SUBFOLDERS_LABEL); + searchSubfoldersButton.setToolTipText(FileResources.RESID_SEARCH_INCLUDE_SUBFOLDERS_TOOLTIP); + + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalSpan = 2; + gd.horizontalIndent = 20; + searchSubfoldersButton.setLayoutData(gd); + + searchSubfoldersButton.setSelection(initialSearchSubfolders); + } + + /** + * Returns whether the search string, file name and folder name are all valid. + * @return true if all are valid, false otherwise. + */ + private boolean isValid() { + + // note that we check folder name first for performance reasons (it is most likely to be + // invalid since we do not allow empty folder name) + return isFolderNameValid() && isSearchStringValid() && isFileNameValid(); + + // TODO: error messages!! But are they even visible in the search dialog? + } + + /** + * Returns whether search string is valid. Note that search string is valid if empty (we assume empty + * search string is the same as "*"); + * @return true if search string is not null, false otherwise. + */ + private boolean isSearchStringValid() { + + String searchString = stringCombo.getText(); + + if (searchString == null) { + return false; + } + else { + return true; + } + } + + /** + * Returns whether file name is valid. Note that file name is valid if empty (we assume empty file + * name is the same as "*"); + * @return true if file name is not null, false otherwise. + */ + private boolean isFileNameValid() { + + String fileNameString = fileNameCombo.getText(); + + if (fileNameString == null) { + return false; + } + else { + return true; + } + } + + /** + * Returns whether folder name is valid. + * @return true if folder name is not null or empty, false otherwise. + */ + private boolean isFolderNameValid() { + + String folderName = folderNameCombo.getText(); + + if (folderName == null || folderName.trim().length() == 0) { + return false; + } + else { + return true; + } + } + + /** + * Get plugin dialog settings. + * @return the dialog settings of the plugin. + */ + private IDialogSettings getPluginDialogSettings() { + return SystemPlugin.getDefault().getDialogSettings(); + } + + /** + * Returns the dialog settings for the remote search page. + * @return the dialog settings used to store search page configuration. + */ + private IDialogSettings getConfigDialogSettings() { + IDialogSettings settings = getPluginDialogSettings(); + IDialogSettings dialogSettings = settings.getSection(REMOTE_SEARCH_PAGE_NAME); + + if (dialogSettings == null) { + dialogSettings = settings.addNewSection(REMOTE_SEARCH_PAGE_NAME); + } + + return dialogSettings; + } + + /** + * Retrieves the configuration from the dialog settings. + */ + private void readConfiguration() { + IDialogSettings s = getConfigDialogSettings(); + initialCaseSensitive = s.getBoolean(STORE_CONFIG_CASE_SENSITIVE); + initialStringRegex = s.getBoolean(STORE_CONFIG_STRING_REGEX); + initialFileNameRegex = s.getBoolean(STORE_CONFIG_FILENAME_REGEX); + initialSearchArchives = s.getBoolean(STORE_CONFIG_INCLUDE_ARCHIVES); + initialSearchSubfolders = s.getBoolean(STORE_CONFIG_INCLUDE_SUBFOLDERS); + } + + /** + * Stores the current configuration to the dialog settings. + */ + private void writeConfiguration() { + IDialogSettings s = getConfigDialogSettings(); + s.put(STORE_CONFIG_CASE_SENSITIVE, caseButton.getSelection()); + s.put(STORE_CONFIG_STRING_REGEX, stringRegexButton.getSelection()); + s.put(STORE_CONFIG_FILENAME_REGEX, fileNameRegexButton.getSelection()); + s.put(STORE_CONFIG_INCLUDE_ARCHIVES, searchArchivesButton.getSelection()); + s.put(STORE_CONFIG_INCLUDE_SUBFOLDERS, searchSubfoldersButton.getSelection()); + } + + /** + * Reads the data. + */ + private void readData() { + + // store the size + int size = 0; + + try { + size = getConfigDialogSettings().getInt(STORE_CONFIG_DATA_SIZE); + } + catch (NumberFormatException e) { + // if a number format exception occurs, it doesn't mean there is an error + // it simply means this is the first time the dialog is opened + size = 0; + } + + if (size > 0) { + // take the minimum of stored size and the maximum size allowable + // this is unnecessary, since the stored size should never be + // more than the maximum size, but we check just in case + size = Math.min(size, MAX_DATA_SIZE); + previousSearchData = new ArrayList(size); + } + + for (int i = 0; i < size; i++) { + IDialogSettings dataSection = getPluginDialogSettings().getSection(STORE_DATA_PREFIX + i); + String searchString = dataSection.get(STORE_DATA_SEARCH_STRING); + boolean caseSensitive = dataSection.getBoolean(STORE_DATA_CASE_SENSITIVE); + boolean stringRegex = dataSection.getBoolean(STORE_DATA_STRING_REGEX); + + String fileNamesString = dataSection.get(STORE_DATA_FILE_NAMES); + boolean fileNameRegex = dataSection.getBoolean(STORE_DATA_FILE_NAME_REGEX); + + String profileName = dataSection.get(STORE_DATA_PROFILE_NAME); + String connectionName = dataSection.get(STORE_DATA_CONNECTION_NAME); + String folderName = dataSection.get(STORE_DATA_FOLDER_NAME); + + boolean searchArchives = dataSection.getBoolean(STORE_DATA_INCLUDE_ARCHIVES); + boolean searchSubfolders = dataSection.getBoolean(STORE_DATA_INCLUDE_SUBFOLDERS); + + RemoteSearchData data = new RemoteSearchData(searchString, caseSensitive, stringRegex, fileNamesString, fileNameRegex, profileName, connectionName, folderName, searchArchives, searchSubfolders); + previousSearchData.add(data); + } + } + + /** + * Writes the data. + */ + private void writeData() { + + // get the size of data + int size = previousSearchData.size(); + + // take the minimum of the data size and the maximum size allowable + // this is unnecessary, since the data size should never be + // more than the maximum size allowable, but we check just in case + size = Math.min(size, MAX_DATA_SIZE); + + // store the size + getConfigDialogSettings().put(STORE_CONFIG_DATA_SIZE, size); + + IDialogSettings pluginSettings = getPluginDialogSettings(); + + for (int i = 0; i < size; i++) { + IDialogSettings dataSection = pluginSettings.getSection(STORE_DATA_PREFIX + i); + + if (dataSection == null) { + dataSection = pluginSettings.addNewSection(STORE_DATA_PREFIX + i); + } + + RemoteSearchData data = (RemoteSearchData)previousSearchData.get(i); + + dataSection.put(STORE_DATA_SEARCH_STRING, data.searchString); + dataSection.put(STORE_DATA_CASE_SENSITIVE, data.caseSensitive); + dataSection.put(STORE_DATA_STRING_REGEX, data.stringRegex); + + dataSection.put(STORE_DATA_FILE_NAMES, data.fileNames); + dataSection.put(STORE_DATA_FILE_NAME_REGEX, data.fileNameRegex); + + dataSection.put(STORE_DATA_PROFILE_NAME, data.profileName); + dataSection.put(STORE_DATA_CONNECTION_NAME, data.connectionName); + dataSection.put(STORE_DATA_FOLDER_NAME, data.folderName); + + dataSection.put(STORE_DATA_INCLUDE_ARCHIVES, data.includeArchives); + dataSection.put(STORE_DATA_INCLUDE_SUBFOLDERS, data.includeSubfolders); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesAction.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesAction.java new file mode 100644 index 00000000000..ab0bcd46e18 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesAction.java @@ -0,0 +1,47 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + + +package org.eclipse.rse.files.ui.search; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.rse.files.ui.actions.SystemSelectFileTypesAction; +import org.eclipse.swt.widgets.Shell; + + +/** + * Action to select file types for the search dialog. + */ +public class SystemSearchSelectFileTypesAction + extends SystemSelectFileTypesAction { + + /** + * Creates the action. + * @param shell + */ + public SystemSearchSelectFileTypesAction(Shell shell) { + super(shell); + } + + + /** + * @see org.eclipse.rse.ui.actions.SystemBaseDialogAction#createDialog(org.eclipse.swt.widgets.Shell) + */ + public Dialog createDialog(Shell parent) { + SystemSearchSelectFileTypesDialog dialog = new SystemSearchSelectFileTypesDialog(getShell(), types); + return dialog; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesDialog.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesDialog.java new file mode 100644 index 00000000000..1283a364af6 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/search/SystemSearchSelectFileTypesDialog.java @@ -0,0 +1,132 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.search; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; + +import org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IFileEditorMapping; +import org.eclipse.ui.PlatformUI; + + +/** + * File types selection dialog for the search page. + */ +public class SystemSearchSelectFileTypesDialog extends SystemSelectFileTypesDialog { + + /** + * Creates the dialog. + * @param shell the shell. + * @param currentTypes types to preselect. + */ + public SystemSearchSelectFileTypesDialog(Shell shell, Collection currentTypes) { + super(shell, currentTypes); + } + + /** + * @see org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog#checkInitialSelections() + */ + protected void checkInitialSelections() { + + IFileEditorMapping editorMappings[] = PlatformUI.getWorkbench().getEditorRegistry().getFileEditorMappings(); + ArrayList selectedMappings = new ArrayList(); + + // go through all editor mappings, and check of those that are in the initial selections + for (int i = 0; i < editorMappings.length; i++) { + IFileEditorMapping mapping = editorMappings[i]; + + if (initialSelections.contains(mapping.getExtension())) { + listViewer.setChecked(mapping, true); + selectedMappings.add(mapping.getExtension()); + } + } + + // now find those entries in the initial selections that are not in editor mappings + // add these entries to the user defined list + Iterator initialIterator = initialSelections.iterator(); + StringBuffer entries = new StringBuffer(); + boolean first = true; + + while(initialIterator.hasNext()) { + String nextExtension = (String)initialIterator.next(); + + if(!selectedMappings.contains(nextExtension)) { + + if (!first) { + // if not the first entry, add a comma and a space + entries.append(TYPE_DELIMITER); + entries.append(" "); + } + else { + first = false; + } + + entries.append(nextExtension); + } + } + + userDefinedText.setText(entries.toString()); + } + + /** + * @see org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog#addUserDefinedEntries(java.util.List) + */ + protected void addUserDefinedEntries(List result) { + StringTokenizer tokenizer = new StringTokenizer(userDefinedText.getText(), TYPE_DELIMITER); + + while (tokenizer.hasMoreTokens()) { + String currentExtension = tokenizer.nextToken().trim(); + + if (!currentExtension.equals("")) { + result.add(currentExtension); + } + } + } + + /** + * @see org.eclipse.rse.ui.dialogs.SystemPromptDialog#processOK() + */ + protected boolean processOK() { + + IFileEditorMapping[] children = getInput(); + List list = new ArrayList(); + + // build a list of selected children + for (int i = 0; i < children.length; ++i) { + IFileEditorMapping element = children[i]; + + if (listViewer.getChecked(element)) { + list.add(element.getLabel()); + } + } + + addUserDefinedEntries(list); + setResult(list); + return true; + } + + /** + * @see org.eclipse.rse.ui.dialogs.SystemSelectFileTypesDialog#validateFileType(java.lang.String) + */ + protected boolean validateFileType(String filename) { + return true; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubSystemFactoryAdapter.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubSystemFactoryAdapter.java new file mode 100644 index 00000000000..668cf7d4268 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubSystemFactoryAdapter.java @@ -0,0 +1,200 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; + +import java.util.Vector; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystemConfiguration; +import org.eclipse.rse.files.ui.actions.SystemFileUpdateFilterAction; +import org.eclipse.rse.files.ui.actions.SystemNewFileAction; +import org.eclipse.rse.files.ui.actions.SystemNewFileFilterAction; +import org.eclipse.rse.files.ui.actions.SystemNewFolderAction; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.files.ui.resources.SystemRemoteEditManager; +import org.eclipse.rse.files.ui.wizards.SystemFileNewConnectionWizardPage; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.ISystemFilterPool; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.ui.actions.SystemPasteFromClipboardAction; +import org.eclipse.rse.ui.view.SubsystemFactoryAdapter; +import org.eclipse.rse.ui.wizards.ISystemNewConnectionWizardPage; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.widgets.Shell; + + +public class RemoteFileSubSystemFactoryAdapter extends SubsystemFactoryAdapter +{ + + SystemNewFileFilterAction _newFileFilterAction; + SystemFileUpdateFilterAction _changeFilerAction; + + Vector _additionalActions; + + // ----------------------------------- + // WIZARD PAGE CONTRIBUTION METHODS... (defects 43194 and 42780) + // ----------------------------------- + /** + * Optionally return one or more wizard pages to append to the New Connection Wizard if + * the user selects a system type that this subsystem factory supports. + *

    + * Tip: consider extending AbstractSystemWizardPage for your wizard page class. + */ + public ISystemNewConnectionWizardPage[] getNewConnectionWizardPages(ISubSystemConfiguration factory, IWizard wizard) + { + ISystemNewConnectionWizardPage[] basepages = super.getNewConnectionWizardPages(factory, wizard); + + // DKM - for now reverting back to not showing port on wizard page + // in UCD sessions, users were too confused by that page + if (false /*isPortEditable()*/) + { + SystemFileNewConnectionWizardPage page = new SystemFileNewConnectionWizardPage(wizard, factory); + ISystemNewConnectionWizardPage[] newPages = new ISystemNewConnectionWizardPage[basepages.length + 1]; + newPages[0] = page; + for (int i = 0; i < basepages.length; i++) + { + newPages[i+1] = basepages[i]; + } + basepages = newPages; + } + return basepages; + } + + /** + * Overridable parent method to return the action for creating a new filter inside a filter pool + * Returns new SystemNewFileFilterAction. + */ + protected IAction getNewFilterPoolFilterAction(ISubSystemConfiguration factory, ISystemFilterPool selectedPool, Shell shell) + { + if (_newFileFilterAction == null) + { + _newFileFilterAction = new SystemNewFileFilterAction((IRemoteFileSubSystemConfiguration)factory, selectedPool, shell); + } + else + { + _newFileFilterAction.setParentFilterPool(selectedPool); + + + } + return _newFileFilterAction; + } + + /** + * Overridable method to return the action for changing an existing filter. + * Returns new SystemFileUpdateFilterAction. + */ + protected IAction getChangeFilterAction(ISubSystemConfiguration factory, ISystemFilter selectedFilter, Shell shell) + { + if (_changeFilerAction == null) + { + _changeFilerAction = new SystemFileUpdateFilterAction(shell); + } + return _changeFilerAction; + } + + /** + * @see org.eclipse.rse.core.subsystems.SubSystemConfiguration#getAdditionalFilterActions(ISystemFilter,Shell) + */ + protected Vector getAdditionalFilterActions(ISubSystemConfiguration factory, ISystemFilter selectedFilter, Shell shell) + { + if (_additionalActions == null) + { + _additionalActions = super.getAdditionalFilterActions(factory, selectedFilter, shell); + if (selectedFilter.isPromptable()) + return _additionalActions; + if (_additionalActions == null) + _additionalActions = new Vector(); + + // following added by Phil for release 2, Nov 10 2002 + _additionalActions.add(new SystemNewFileAction(shell)); + _additionalActions.add(new SystemNewFolderAction(shell)); + + // DKM + // FIXME - can't do this here anymore + //_additionalActions.add(new SystemCommandAction(shell, true)); + + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + Clipboard clipboard = registry.getSystemClipboard(); + _additionalActions.add(new SystemPasteFromClipboardAction(shell, clipboard)); + } + return _additionalActions; + } + + /** + * Called by SystemRegistry's renameSystemProfile method to ensure we update our + * subsystem names within each subsystem. + *

    + * Must be called AFTER changing the profile's name!! + */ + public void renameSubSystemProfile(ISubSystemConfiguration factory, String oldProfileName, String newProfileName) + { + super.renameSubSystemProfile(factory, oldProfileName, newProfileName); + + // change all IFile properties in remote systems temp files tree + IProject project = SystemBasePlugin.getWorkspaceRoot().getProject(SystemRemoteEditManager.REMOTE_EDIT_PROJECT_NAME); + if (project != null) + { + IFolder folder = project.getFolder(oldProfileName); + if (folder != null && folder.exists()) + { + // recursively change all subsystem ids for the temp files + recursivelyUpdateIFileProperties(newProfileName, folder); + } + } + } + + + protected void recursivelyUpdateIFileProperties(String newName, IFolder container) + { + try + { + IResource[] resources = container.members(); + for (int i = 0; i < resources.length; i++) + { + IResource resource = resources[i]; + if (resource instanceof IFile) + { + IFile file = (IFile)resource; + SystemIFileProperties properties = new SystemIFileProperties(file); + + String absoluteSubSystemName = properties.getRemoteFileSubSystem(); + if (absoluteSubSystemName != null) + { + int profileDelim = absoluteSubSystemName.indexOf("."); + String theRest = absoluteSubSystemName.substring(profileDelim, absoluteSubSystemName.length()); + properties.setRemoteFileSubSystem(newName + theRest); + } + } + else if (resource instanceof IFolder) + { + recursivelyUpdateIFileProperties(newName, (IFolder)resource); + } + } + } + catch (Exception e) + { + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubsystemFactoryAdapterFactory.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubsystemFactoryAdapterFactory.java new file mode 100644 index 00000000000..c3e45d71143 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/RemoteFileSubsystemFactoryAdapterFactory.java @@ -0,0 +1,59 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; + +import org.eclipse.core.runtime.IAdapterFactory; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.rse.core.subsystems.util.ISubsystemConfigurationAdapter; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; + + +public class RemoteFileSubsystemFactoryAdapterFactory implements IAdapterFactory +{ + + private ISubsystemConfigurationAdapter ssFactoryAdapter = new RemoteFileSubSystemFactoryAdapter(); + + /** + * @see IAdapterFactory#getAdapterList() + */ + public Class[] getAdapterList() + { + return new Class[] {ISubsystemConfigurationAdapter.class}; + } + /** + * Called by our plugin's startup method to register our adaptable object types + * with the platform. We prefer to do it here to isolate/encapsulate all factory + * logic in this one place. + */ + public void registerWithManager(IAdapterManager manager) + { + manager.registerAdapters(this, IRemoteFileSubSystemConfiguration.class); + } + /** + * @see IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) + */ + public Object getAdapter(Object adaptableObject, Class adapterType) + { + Object adapter = null; + if (adaptableObject instanceof IRemoteFileSubSystemConfiguration) + adapter = ssFactoryAdapter; + + return adapter; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewFileAdapterFactory.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewFileAdapterFactory.java new file mode 100644 index 00000000000..3d2295df975 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewFileAdapterFactory.java @@ -0,0 +1,65 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; +import org.eclipse.core.runtime.IAdapterFactory; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.view.AbstractSystemRemoteAdapterFactory; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.ui.views.properties.IPropertySource; + + +/** + * This factory maps requests for an adapter object from a given + * element object. This is for the universal file system. + */ +public class SystemViewFileAdapterFactory extends AbstractSystemRemoteAdapterFactory +{ + private SystemViewRemoteFileAdapter fileAdapter = new SystemViewRemoteFileAdapter(); + + /** + * Called by our plugin's startup method to register our adaptable object types + * with the platform. We prefer to do it here to isolate/encapsulate all factory + * logic in this one place. + */ + public void registerWithManager(IAdapterManager manager) + { + manager.registerAdapters(this, IRemoteFile.class); + } + /** + * @see IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) + */ + public Object getAdapter(Object adaptableObject, Class adapterType) + { + Object adapter = null; + if (adaptableObject instanceof IRemoteFile) + adapter = fileAdapter; + + if ((adapter != null) && (adapterType == IPropertySource.class)) + { + ((ISystemViewElementAdapter)adapter).setPropertySourceInput(adaptableObject); + } + else if (adapter == null) + { + SystemBasePlugin.logWarning("No adapter found for object of type: " + adaptableObject.getClass().getName()); + } + return adapter; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteFileAdapter.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteFileAdapter.java new file mode 100644 index 00000000000..489eb8e60c4 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteFileAdapter.java @@ -0,0 +1,3064 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; +import java.io.File; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.core.subsystems.RemoteChildrenContentsType; +import org.eclipse.rse.core.subsystems.SubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.actions.SystemAddToArchiveAction; +import org.eclipse.rse.files.ui.actions.SystemCompareFilesAction; +import org.eclipse.rse.files.ui.actions.SystemCompareWithEditionAction; +import org.eclipse.rse.files.ui.actions.SystemConvertAction; +import org.eclipse.rse.files.ui.actions.SystemEditFilesAction; +import org.eclipse.rse.files.ui.actions.SystemExtractAction; +import org.eclipse.rse.files.ui.actions.SystemExtractToAction; +import org.eclipse.rse.files.ui.actions.SystemMoveRemoteFileAction; +import org.eclipse.rse.files.ui.actions.SystemNewFileAction; +import org.eclipse.rse.files.ui.actions.SystemNewFileFilterFromFolderAction; +import org.eclipse.rse.files.ui.actions.SystemNewFolderAction; +import org.eclipse.rse.files.ui.actions.SystemRemoteFileOpenWithMenu; +import org.eclipse.rse.files.ui.actions.SystemReplaceWithEditionAction; +import org.eclipse.rse.files.ui.actions.SystemSearchAction; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.files.ui.resources.SystemIFileProperties; +import org.eclipse.rse.files.ui.resources.SystemRemoteEditManager; +import org.eclipse.rse.files.ui.resources.UniversalFileTransferUtility; +import org.eclipse.rse.filters.ISystemFilterReference; +import org.eclipse.rse.filters.SystemFilterReference; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemMessageObject; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemResourceChangeEvent; +import org.eclipse.rse.model.ISystemResourceSet; +import org.eclipse.rse.model.SystemMessageObject; +import org.eclipse.rse.model.SystemRemoteResourceSet; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.model.SystemWorkspaceResourceSet; +import org.eclipse.rse.services.clientserver.StringCompare; +import org.eclipse.rse.services.clientserver.SystemSearchString; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.services.search.HostSearchResultSet; +import org.eclipse.rse.services.search.IHostSearchConstants; +import org.eclipse.rse.services.search.IHostSearchResultConfiguration; +import org.eclipse.rse.services.search.IHostSearchResultConfigurationFactory; +import org.eclipse.rse.services.search.IHostSearchResultSet; +import org.eclipse.rse.subsystems.files.core.model.ISystemFileRemoteTypes; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.servicesubsystem.FileServiceSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.subsystems.files.core.subsystems.IVirtualRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileEmpty; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileRoot; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteSearchResultsContentsType; +import org.eclipse.rse.subsystems.files.core.util.ValidatorFileUniqueName; +import org.eclipse.rse.ui.ISystemContextMenuConstants; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.SystemMenuManager; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.actions.SystemCopyToClipboardAction; +import org.eclipse.rse.ui.actions.SystemPasteFromClipboardAction; +import org.eclipse.rse.ui.actions.SystemShowInMonitorAction; +import org.eclipse.rse.ui.actions.SystemShowInTableAction; +import org.eclipse.rse.ui.dialogs.SystemRenameSingleDialog; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.operations.SystemFetchOperation; +import org.eclipse.rse.ui.validators.ISystemValidator; +import org.eclipse.rse.ui.view.AbstractSystemViewAdapter; +import org.eclipse.rse.ui.view.ISystemDragDropAdapter; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemMementoConstants; +import org.eclipse.rse.ui.view.ISystemPropertyConstants; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewDropDestination; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.rse.ui.view.SystemDNDTransferRunnable; +import org.eclipse.rse.ui.view.SystemViewResources; +import org.eclipse.rse.ui.view.search.SystemSearchTableView; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.progress.IElementCollector; +import org.eclipse.ui.views.properties.IPropertyDescriptor; +import org.eclipse.ui.views.properties.PropertyDescriptor; + + +/** + * Adapter for displaying remote file system objects in tree views. + * These are children of RemoteFileSubSystem filter strings + */ +public class SystemViewRemoteFileAdapter + extends AbstractSystemViewAdapter + implements ISystemViewElementAdapter, ISystemRemoteElementAdapter, + ISystemMessages, ISystemPropertyConstants +{ + + private String xlatedSize = null; + private String xlatedCompressedSize = null; + private String xlatedExpandedSize = null; + + private static final Object[] EMPTY_LIST = new Object[0]; + private boolean filesOnly, foldersOnly; + private SystemNewFileAction addNewFile; + private SystemNewFolderAction addNewFolder; + private SystemNewFileFilterFromFolderAction addNewFilter; + + private SystemMoveRemoteFileAction moveAction; + + private SystemCopyToClipboardAction copyClipboardAction; + private SystemPasteFromClipboardAction pasteClipboardAction; + + private SystemCompareFilesAction compareFilesAction; + private SystemCompareWithEditionAction compareEditionAction; + private SystemReplaceWithEditionAction replaceEditionAction; + // FIXME shells now separate plugin + //private SystemCommandAction commandAction, shellAction; + + private SystemSearchAction searchAction; + private SystemShowInTableAction showInTableAction; + private SystemShowInMonitorAction showInMonitorAction; + private SystemExtractAction extractAction; + private SystemExtractToAction extractToAction; + private SystemConvertAction convertAction; + private SystemAddToArchiveAction addToArchiveAction; + private IEditorRegistry registry; + private SystemRemoteFileOpenWithMenu openWithMenu; + + private boolean debug = false; //true; + + // ------------------- + // property descriptors + // ------------------- + private static PropertyDescriptor[] propertyDescriptorArray = null; + private static PropertyDescriptor[] briefPropertyDescriptorArray = null; + + // DKM + private static PropertyDescriptor[] uniquePropertyDescriptorArray = null; + private static PropertyDescriptor[] uniqueArchiveDescriptorArray = null; + private static PropertyDescriptor[] uniqueVirtualDescriptorArray = null; + + // MJB + private static PropertyDescriptor[] archiveDescriptorArray = null; + private static PropertyDescriptor[] virtualDescriptorArray = null; + + static final SystemMessage _uploadMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_UPLOADING_PROGRESS); + static final SystemMessage _downloadMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_DOWNLOADING_PROGRESS); + + /** + * Constructor + */ + public SystemViewRemoteFileAdapter() + { + super(); + xlatedSize = SystemViewResources.RESID_PROPERTY_FILE_SIZE_VALUE; + xlatedCompressedSize = SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSEDSIZE_VALUE; + xlatedExpandedSize = SystemViewResources.RESID_PROPERTY_ARCHIVE_EXPANDEDSIZE_VALUE; + + IWorkbench workbench = SystemPlugin.getDefault().getWorkbench(); + if (workbench != null) + registry = workbench.getEditorRegistry(); + } + /** + * Constructor for folders or files only + */ + public SystemViewRemoteFileAdapter(boolean foldersOnly, boolean filesOnly) + { + this(); + this.foldersOnly = foldersOnly; + this.filesOnly = filesOnly; + } + /** + * Set a filter string to subset the list by. For example, "A*.java" or "java,class,". + * Only valid if filesOnly mode or foldersOnly mode. + */ + public void setFilterString(String filterString) + { + if (filesOnly && (filterString != null) && (filterString.indexOf("/ns") == -1)) + filterString = filterString + " /ns"; + else if (foldersOnly && (filterString != null) && (filterString.indexOf("/nf") == -1)) + filterString = filterString + " /nf"; + this.filterString = filterString; + } + + /** + * Get the current filter string being used to subset the list by. + * Will be null unless setFilterString has previously been called. + */ + public String getFilterString() + { + return filterString; + } + + /** + * Returns any actions that should be contributed to the popup menu + * for the given filter string object. + * @param menu The menu to contribute actions to + * @param selection The window's current selection. + * @param shell Shell of viewer + * @param menuGroup recommended menu group to add actions to. If added to another group, you must be sure to create that group first. + */ + public void addActions(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) + { + int elementType = 0; + boolean isArchive = false; + boolean allHaveContents = false; + + boolean canEdit = true; + boolean supportsSearch = true; + boolean supportsArchiveManagement = false; + + boolean isVirtual = false; + + // perf improvement... phil + Object firstSelection = selection.getFirstElement(); + IRemoteFile firstFile = null; + if ((firstSelection != null) && (firstSelection instanceof IRemoteFile)) + { + firstFile = (IRemoteFile) firstSelection; + elementType = firstFile.isDirectory() || firstFile.isRoot() ? 1 : 0; + isArchive = firstFile.isArchive(); + isVirtual = firstFile instanceof IVirtualRemoteFile; + canEdit = firstFile.canRead(); + + supportsSearch = firstFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsSearch(); + supportsArchiveManagement = firstFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + } + else + return; + + allHaveContents = isArchive; + + if (isArchive) + { + Iterator elements = selection.iterator(); + Object element = null; + + while (elements.hasNext()) + { + element = elements.next(); + IRemoteFile remoteObj = (IRemoteFile) element; + if (!remoteObj.isArchive()) + { + allHaveContents = false; + break; + } + } + } + + if ((elementType == 1 || (isArchive && supportsArchiveManagement))) + { + if (!foldersOnly && canEdit) + { + if (addNewFile == null) + { + addNewFile = new SystemNewFileAction(shell); + } + menu.add(ISystemContextMenuConstants.GROUP_NEW, addNewFile); + } + if (!filesOnly) + { + if (canEdit) + { + if (addNewFolder == null) + { + addNewFolder = new SystemNewFolderAction(shell); + } + menu.add(ISystemContextMenuConstants.GROUP_NEW, addNewFolder); + } + + if (addNewFilter == null) + { + addNewFilter = new SystemNewFileFilterFromFolderAction(shell); + } + + menu.appendToGroup(ISystemContextMenuConstants.GROUP_NEW, new Separator()); + menu.add(ISystemContextMenuConstants.GROUP_NEW, addNewFilter); + } + + } + else + { + if (canEdit) + { + // open + String label = SystemResources.ACTION_CASCADING_OPEN_LABEL; + String tooltip = SystemResources.ACTION_CASCADING_OPEN_TOOLTIP; + SystemEditFilesAction action = new SystemEditFilesAction(label, tooltip, shell); + menu.add(ISystemContextMenuConstants.GROUP_OPEN, action); + + // open with -> + + MenuManager submenu = + new MenuManager(FileResources.ResourceNavigator_openWith, + ISystemContextMenuConstants.GROUP_OPENWITH); + + if (openWithMenu == null) + { + openWithMenu = new SystemRemoteFileOpenWithMenu(); + } + openWithMenu.updateSelection(selection); + submenu.add(openWithMenu); + menu.getMenuManager().appendToGroup(ISystemContextMenuConstants.GROUP_OPENWITH, submenu); + } + } + + if (extractAction == null) + { + extractAction = new SystemExtractAction(shell); + } + if (extractToAction == null) + { + extractToAction = new SystemExtractToAction(shell); + } + if (convertAction == null) + { + convertAction = new SystemConvertAction(shell); + } + if (addToArchiveAction == null) + { + addToArchiveAction = new SystemAddToArchiveAction(shell); + } + + if (allHaveContents && canEdit && !isVirtual) + { + /* + menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, extractAction); + menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, extractToAction); + menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, convertAction); + */ + } + + // add import and export actions for single selection of folder +/* if ((elementType == 1 && selection.size() == 1) && canEdit) + { + + if (importAction == null) { + importAction = new SystemImportToProjectAction(shell); + } + + if (exportAction == null) { + exportAction = new SystemExportFromProjectAction(shell); + } + + menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, importAction); + menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, exportAction); + }*/ + + if (moveAction == null) + moveAction = new SystemMoveRemoteFileAction(shell); + + ISubSystem subsys = firstFile.getParentRemoteFileSubSystem(); + + // DKM - clipboard based copy actions + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + Clipboard clipboard = registry.getSystemClipboard(); + + if (pasteClipboardAction == null) + { + pasteClipboardAction = new SystemPasteFromClipboardAction(shell, clipboard); + } + if (copyClipboardAction == null) + { + copyClipboardAction = new SystemCopyToClipboardAction(shell, clipboard); + } + /** FIXME - these show now be contributed via plugin.xml from the shells plugin + if (commandAction == null) + { + commandAction = new SystemCommandAction(shell, false, null); + } + if (shellAction == null) + { + shellAction = new SystemCommandAction(shell, true, null); + } + **/ + if (searchAction == null) + { + searchAction = new SystemSearchAction(shell); + } + if (compareFilesAction == null) + { + compareFilesAction = new SystemCompareFilesAction(shell); + } + if (compareEditionAction == null) + { + compareEditionAction = new SystemCompareWithEditionAction(shell); + } + if (replaceEditionAction == null) + { + replaceEditionAction = new SystemReplaceWithEditionAction(shell); + } + if (showInTableAction == null) + { + showInTableAction = new SystemShowInTableAction(shell); + } + if (showInMonitorAction == null) + { + showInMonitorAction = new SystemShowInMonitorAction(shell); + } + + if (canEdit && supportsSearch) + { + //menu.add(ISystemContextMenuConstants.GROUP_IMPORTEXPORT, addToArchiveAction); + + // add search action + menu.add(ISystemContextMenuConstants.GROUP_SEARCH, searchAction); + } + + if (!firstFile.isRoot() && canEdit) + { + menu.add(menuGroup, copyClipboardAction); + if (elementType == 0) + { + menu.add(ISystemContextMenuConstants.GROUP_COMPAREWITH, compareFilesAction); + menu.add(ISystemContextMenuConstants.GROUP_COMPAREWITH, compareEditionAction); + menu.add(ISystemContextMenuConstants.GROUP_REPLACEWITH, replaceEditionAction); + } + } + + if (elementType == 1 || (isArchive && supportsArchiveManagement)) + { + if (canEdit) + { + menu.add(menuGroup, pasteClipboardAction); + } + menu.add(ISystemContextMenuConstants.GROUP_OPEN, showInTableAction); + + + menu.add(ISystemContextMenuConstants.GROUP_OPEN, showInMonitorAction); + + /** FIXME - shells now separate plugin + if (elementType == 1) + { + if (!isVirtual) + { + menu.add(menuGroup, shellAction); + } + } + */ + } + if (!firstFile.isRoot() && canEdit) + { + menu.add(menuGroup, moveAction); + } + } + + /** + * Returns an image descriptor for the image. More efficient than getting the image. + * @param element The element for which an image is desired + */ + public ImageDescriptor getImageDescriptor(Object element) + { + IRemoteFile file = (IRemoteFile) element; + if (file.isFile() || file.isArchive()) // hack to show zips without folder icons + { + return registry.getImageDescriptor(file.getName()); + } + else + { + boolean isOpen = false; + if (getViewer() instanceof AbstractTreeViewer) + { + AbstractTreeViewer atv = (AbstractTreeViewer) getViewer(); + isOpen = atv.getExpandedState(element); + } + if (file.isRoot()) + return SystemPlugin.getDefault().getImageDescriptor(isOpen ? ISystemIconConstants.ICON_SYSTEM_ROOTDRIVEOPEN_ID : ISystemIconConstants.ICON_SYSTEM_ROOTDRIVE_ID); + else if (isOpen) + return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); + else + return SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_FOLDER_ID); + } + } + + /** + * Return the label for this object. Uses getName() on the remote file object. + */ + public String getText(Object element) + { + return getName(element); + } + + /** + * Return the label for this object. Uses getName() on the remote file object. + */ + public String getAlternateText(Object element) + { + return ((IRemoteFile) element).getLabel(); + } + + /** + * Return the name of this object, which may be different than the display text ({#link #getText(Object)}. + *

    + * Called by common rename and delete actions. + */ + public String getName(Object element) + { + return ((IRemoteFile) element).getName(); + } + /** + * Return the type label for this object + */ + public String getType(Object element) + { + IRemoteFile file = (IRemoteFile) element; + + if (file.isRoot()) + return SystemViewResources.RESID_PROPERTY_FILE_TYPE_ROOT_VALUE; + else if (file.isDirectory()) + return SystemViewResources.RESID_PROPERTY_FILE_TYPE_FOLDER_VALUE; + else + return SystemViewResources.RESID_PROPERTY_FILE_TYPE_FILE_VALUE; + } + + /** + * Return the string to display in the status line when the given object is selected. + * We return: + * : + */ + public String getStatusLineText(Object element) + { + return getType(element) + ": " + getAbsoluteName(element); + } + + /** + * Return the parent of this object + */ + public Object getParent(Object element) + { + //System.out.println("Inside getParent for: "+element); + IRemoteFile file = (IRemoteFile) element; + IRemoteFile parent = file.getParentRemoteFile(); + if ((parent != null) && parent.getAbsolutePath().equals(file.getAbsolutePath())) + // should never happen but sometimes it does, leading to infinite loop. + parent = null; + return parent; + } + + /** + * Return the children of this object. + * If this is a folder or root, we list all child folders and files. + */ + public Object[] getChildren(IProgressMonitor monitor, Object element) + { + return internalGetChildren(monitor, element); + } + + /** + * Return the children of this object. + * If this is a folder or root, we list all child folders and files. + */ + public Object[] getChildren(Object element) + { + _lastResults = internalGetChildren(null, element); + return _lastResults; + // } + } + + private synchronized Object[] internalGetChildren(IProgressMonitor monitor, Object element) + { + //System.out.println("Inside getChildren for: "+element); + IRemoteFile file = (IRemoteFile) element; + if (file instanceof RemoteFileEmpty) // cut to the chase + { + //System.out.println("FileAdapter.getChildren(): empty list-request"); + return EMPTY_LIST; + } + else if (file instanceof RemoteFileRoot) + { + //System.out.println("FileAdapter.getChildren(): children of root list-request"); + return ((RemoteFileRoot) file).getRootFiles(); + } + IRemoteFileSubSystem ss = file.getParentRemoteFileSubSystem(); + RemoteFileFilterString orgRffs = file.getFilterString(); + + String filter = null; + if (orgRffs != null) + { + if (foldersOnly) + { + RemoteFileFilterString rffs = (RemoteFileFilterString) orgRffs.clone(); + rffs.setPath(null); + rffs.setShowFiles(false); + rffs.setShowSubDirs(true); + filter = rffs.toString(); + } + else if (filesOnly) + { + RemoteFileFilterString rffs = (RemoteFileFilterString) orgRffs.clone(); + rffs.setPath(null); + rffs.setShowSubDirs(false); + rffs.setShowFiles(true); + filter = rffs.toString(); + } + else + { + filter = null; // this is our clue to RemoteFileSubSystemImpl to use all filter strings associated with this folder + } + } + else if (foldersOnly) + { + if (filterString == null) + filter = "* /nf"; + else + filter = filterString; + } + else if (filesOnly) + { + if (filterString == null) + filter = "* /ns"; + else + filter = filterString; + } + else + { + if (filterString == null) + filter = "*"; + else + filter = filterString; + } + + Object[] children = null; + + Viewer v = getViewer(); + + if ((v != null) && (v instanceof SystemSearchTableView)) { + + SystemSearchTableView view = (SystemSearchTableView)v; + Iterator iter = view.getResultSet().getSearchConfigurations(); + boolean hasSearchResults = false; + while (iter.hasNext() && !hasSearchResults) + { + IHostSearchResultConfiguration config = (IHostSearchResultConfiguration)(iter.next()); + String searchString = config.getSearchString().getTextString(); + + hasSearchResults = file.hasContents(RemoteSearchResultsContentsType.getInstance(), searchString); + + if (hasSearchResults) + { + children = file.getContents(RemoteSearchResultsContentsType.getInstance(), searchString); + return children; + } + } + } + + boolean hasChildren = file.hasContents(RemoteChildrenContentsType.getInstance(), filter); + + if (hasChildren && !file.isStale()) + { + children = file.getContents(RemoteChildrenContentsType.getInstance(), filter); + } + else + { + try + { + if (monitor != null) + { + + children = ss.resolveFilterString(monitor, file, filter); + } + else + { + children = ss.resolveFilterString(file, filter, getShell()); + } + if ((children == null) || (children.length == 0)) + { + //children = new SystemMessageObject[1]; + //children[0] = new SystemMessageObject(SystemPlugin.getPluginMessage(MSG_EXPAND_EMPTY), + // ISystemMessageObject.MSGTYPE_EMPTY, element); + children = EMPTY_LIST; + } + + } + catch (InterruptedException exc) + { + children = new SystemMessageObject[1]; + children[0] = new SystemMessageObject(SystemPlugin.getPluginMessage(MSG_EXPAND_CANCELLED), ISystemMessageObject.MSGTYPE_CANCEL, element); + //System.out.println("Canceled."); + } + catch (Exception exc) + { + children = new SystemMessageObject[1]; + children[0] = new SystemMessageObject(SystemPlugin.getPluginMessage(MSG_EXPAND_FAILED), ISystemMessageObject.MSGTYPE_ERROR, element); + SystemBasePlugin.logError("Exception resolving file filter strings", exc); + } // message already issued + } + return children; + } + /** + * Return true if this object has children. + * Since we can't predict the outcome of resolving the filter string, we return true. + */ + public boolean hasChildren(Object element) + { + IRemoteFile file = (IRemoteFile) element; + boolean supportsArchiveManagement = file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + boolean hasChildren = false; + if (file instanceof IVirtualRemoteFile) + { + hasChildren = ((IVirtualRemoteFile)file).isVirtualFolder(); + } + else + { + hasChildren = !file.isFile() || (file.isArchive() && supportsArchiveManagement); + } + + if (!hasChildren) { + + Viewer v = getViewer(); + + if ((v != null) && (v instanceof SystemSearchTableView)) { + + SystemSearchTableView view = (SystemSearchTableView)v; + Iterator iter = view.getResultSet().getSearchConfigurations(); + while (iter.hasNext() && !hasChildren) + { + IHostSearchResultConfiguration config = (IHostSearchResultConfiguration)(iter.next()); + String searchString = config.getSearchString().getTextString(); + + hasChildren = file.hasContents(RemoteSearchResultsContentsType.getInstance(), searchString); + } + } + else { + hasChildren = file.hasContents(RemoteChildrenContentsType.getInstance()); + } + } + + return hasChildren; + } + + + + public IPropertyDescriptor[] getUniquePropertyDescriptors() + { + + IRemoteFile file = null; + if (propertySourceInput instanceof IRemoteFile) + { + file = (IRemoteFile) propertySourceInput; + + boolean supportsArchiveManagement = file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + + boolean isArchive = file != null && file.isArchive() && supportsArchiveManagement; + boolean isVirtual = file != null && file instanceof IVirtualRemoteFile && supportsArchiveManagement; + boolean isRegular = !isArchive && !isVirtual; + + if (isRegular && uniquePropertyDescriptorArray == null || + isArchive && uniqueArchiveDescriptorArray == null || + isVirtual && uniqueVirtualDescriptorArray == null) + { + + int nbrOfArchiveProperties = 2; + int nbrOfVirtualProperties = 4; + int nbrOfProperties = 4; + if (isVirtual) nbrOfProperties += nbrOfVirtualProperties; + else if (isArchive) nbrOfProperties += nbrOfArchiveProperties; + + if (isRegular) uniquePropertyDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + else if (isVirtual) uniqueVirtualDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + else if (isArchive) uniqueArchiveDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + //PropertyDescriptor[] defaultProperties = (PropertyDescriptor[]) getDefaultDescriptors(); + + int i = -1; + + // add our unique property descriptors... + SystemPlugin plugin = SystemPlugin.getDefault(); + + // classification + if (isRegular) uniquePropertyDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + else if (isVirtual) uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + else if (isArchive) uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + + // last modified + if (isRegular) uniquePropertyDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + else if (isVirtual) uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + else if (isArchive) uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + + // size + if (isRegular) uniquePropertyDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + else if (isVirtual) uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + else if (isArchive) uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + + // canonical path + if (isRegular) uniquePropertyDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + else if (isVirtual) uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + else if (isArchive) uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + + + if (isVirtual) + { + // add virtual property descriptors... + + // compressed size + uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSEDSIZE, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSEDSIZE_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSEDSIZE_DESCRIPTION); + + // compression ratio + uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSIONRATIO, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONRATIO_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONRATIO_DESCRIPTION); + + // compression method + uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSIONMETHOD, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONMETHOD_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONMETHOD_DESCRIPTION); + + // comment + uniqueVirtualDescriptorArray[++i] = createSimplePropertyDescriptor(P_VIRTUAL_COMMENT, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMMENT_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMMENT_DESCRIPTION); + } + else if (isArchive) + { + // add archive property descriptors... + + // expanded size + uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_ARCHIVE_EXPANDEDSIZE, SystemViewResources.RESID_PROPERTY_ARCHIVE_EXPANDEDSIZE_LABEL, SystemViewResources.RESID_PROPERTY_ARCHIVE_EXPANDEDSIZE_DESCRIPTION); + + // comment + uniqueArchiveDescriptorArray[++i] = createSimplePropertyDescriptor(P_ARCHIVE_COMMENT, SystemViewResources.RESID_PROPERTY_ARCHIVE_COMMENT_LABEL, SystemViewResources.RESID_PROPERTY_ARCHIVE_COMMENT_DESCRIPTION); + } + } + + // DKM - I commented this stuff out since it's screwing up table view + ///* + if (isRegular) return uniquePropertyDescriptorArray; + else if (isVirtual) return uniqueVirtualDescriptorArray; + else if (isArchive) return uniqueArchiveDescriptorArray; + else return uniquePropertyDescriptorArray; + //*/ + } + return uniquePropertyDescriptorArray; + } + + /** + * Return our unique property descriptors + */ + protected IPropertyDescriptor[] internalGetPropertyDescriptors() + { + //System.out.println("Inside beg getPropertyDescriptors: "+propertyDescriptorArray); + // IT TURNS OUT THAT FOR IFS FILES, THE QUERY OF THE FULL SET OF PROPERTIES CAN TAKE UP + // TO 5 SECONDS, CONSIDERABLY SLOWING DOWN RESPONSE TIME TO THE POINT OF PAIN. TO FIX THIS, + // WE HAVE MADE IT POSSIBLE FOR REMOTE FILE OBJECTS TO DECIDE TO SHOW ONLY A SUBSET OF THE + // PROPERTIES, WHICH IFS FILES EXPLOIT. PHIL. + + IRemoteFile file = null; + if (propertySourceInput instanceof IRemoteFile) file = (IRemoteFile) propertySourceInput; + boolean isArchive = false;//file != null && file.isArchive(); + + boolean isVirtual = file != null && file instanceof IVirtualRemoteFile; + boolean isRegular = !isArchive && !isVirtual; + + if (isRegular && propertyDescriptorArray == null ||//uniquePropertyDescriptorArray == null || + isArchive && archiveDescriptorArray == null || + isVirtual && virtualDescriptorArray == null) + { + int nbrOfArchiveProperties = 2; + int nbrOfVirtualProperties = 4; + int nbrOfProperties = 8; + int nbrOfBriefProperties = 2; + if (debug) + nbrOfProperties += 7; + + if (isVirtual) nbrOfProperties += nbrOfVirtualProperties; + else if (isArchive) nbrOfProperties += nbrOfArchiveProperties; + + if (isRegular) propertyDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + else if (isVirtual) virtualDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + else if (isArchive) archiveDescriptorArray = new PropertyDescriptor[nbrOfProperties]; + + briefPropertyDescriptorArray = new PropertyDescriptor[nbrOfBriefProperties]; + int idx = -1; + int briefIdx = idx; + + // path + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_PATH, SystemViewResources.RESID_PROPERTY_FILE_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_PATH_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_PATH, SystemViewResources.RESID_PROPERTY_FILE_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_PATH_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_PATH, SystemViewResources.RESID_PROPERTY_FILE_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_PATH_TOOLTIP); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor(P_FILE_PATH, SystemViewResources.RESID_PROPERTY_FILE_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_PATH_TOOLTIP); + + // filter string + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILTERSTRING, SystemViewResources.RESID_PROPERTY_FILTERSTRING_LABEL,SystemViewResources.RESID_PROPERTY_FILTERSTRING_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILTERSTRING, SystemViewResources.RESID_PROPERTY_FILTERSTRING_LABEL,SystemViewResources.RESID_PROPERTY_FILTERSTRING_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILTERSTRING, SystemViewResources.RESID_PROPERTY_FILTERSTRING_LABEL,SystemViewResources.RESID_PROPERTY_FILTERSTRING_TOOLTIP); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor(P_FILTERSTRING, SystemViewResources.RESID_PROPERTY_FILTERSTRING_LABEL,SystemViewResources.RESID_PROPERTY_FILTERSTRING_TOOLTIP); + + // canonical path + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL,SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL,SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CANONICAL_PATH, SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_LABEL,SystemViewResources.RESID_PROPERTY_FILE_CANONICAL_PATH_TOOLTIP); + + // last modified + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL,SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_LASTMODIFIED, SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_LABEL,SystemViewResources.RESID_PROPERTY_FILE_LASTMODIFIED_TOOLTIP); + + // size + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_SIZE, SystemViewResources.RESID_PROPERTY_FILE_SIZE_LABEL, SystemViewResources.RESID_PROPERTY_FILE_SIZE_TOOLTIP); + + // classification + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_CLASSIFICATION, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_LABEL, SystemViewResources.RESID_PROPERTY_FILE_CLASSIFICATION_TOOLTIP); + + // readonly + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_READONLY, SystemViewResources.RESID_PROPERTY_FILE_READONLY_LABEL, SystemViewResources.RESID_PROPERTY_FILE_READONLY_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_READONLY, SystemViewResources.RESID_PROPERTY_FILE_READONLY_LABEL, SystemViewResources.RESID_PROPERTY_FILE_READONLY_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_READONLY, SystemViewResources.RESID_PROPERTY_FILE_READONLY_LABEL, SystemViewResources.RESID_PROPERTY_FILE_READONLY_TOOLTIP); + + // hidden + if (isRegular) propertyDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_HIDDEN, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_LABEL, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_TOOLTIP); + else if (isVirtual) virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_HIDDEN, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_LABEL, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_TOOLTIP); + else if (isArchive) archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_FILE_HIDDEN, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_LABEL, SystemViewResources.RESID_PROPERTY_FILE_HIDDEN_TOOLTIP); + + if (debug) + { + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_PARENTREMOTEFILE"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_PARENTREMOTEFILE"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_PARENT"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_PARENT"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_PARENTNOROOT"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_PARENTNOROOT"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_PARENTNAME"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_PARENTNAME"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_ROOT"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_ROOT"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_ISROOT"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_ISROOT"); + propertyDescriptorArray[++idx] = createSimplePropertyDescriptor("DEBUG_EXISTS"); + briefPropertyDescriptorArray[++briefIdx] = createSimplePropertyDescriptor("DEBUG_EXISTS"); + } + + if (isVirtual) + { + // add virtual property descriptors... + + // compressed size + virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSEDSIZE, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSEDSIZE_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSEDSIZE_DESCRIPTION); + + // compression ratio + virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSIONRATIO, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONRATIO_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONRATIO_DESCRIPTION); + + // compression method + virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_VIRTUAL_COMPRESSIONMETHOD, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONMETHOD_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMPRESSIONMETHOD_DESCRIPTION); + + // comment + virtualDescriptorArray[++idx] = createSimplePropertyDescriptor(P_VIRTUAL_COMMENT, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMMENT_LABEL, SystemViewResources.RESID_PROPERTY_VIRTUALFILE_COMMENT_DESCRIPTION); + } + + else if (isArchive) + { + // add archive property descriptors... + + // expanded size + archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_ARCHIVE_EXPANDEDSIZE, SystemViewResources.RESID_PROPERTY_ARCHIVE_EXPANDEDSIZE_LABEL, SystemViewResources.RESID_PROPERTY_ARCHIVE_EXPANDEDSIZE_DESCRIPTION); + + // comment + archiveDescriptorArray[++idx] = createSimplePropertyDescriptor(P_ARCHIVE_COMMENT, SystemViewResources.RESID_PROPERTY_ARCHIVE_COMMENT_LABEL, SystemViewResources.RESID_PROPERTY_ARCHIVE_COMMENT_DESCRIPTION); + } + + } + +// return propertyDescriptorArray; + // DKM - I've commented this out because it's too expensive to query archive properties during a folder query + // we need to come back to this and change this do work in a more performance-sensitive way + + //System.out.println("Inside end getPropertyDescriptors: "+propertyDescriptorArray.length); + if ((propertySourceInput instanceof IRemoteFile) && ((IRemoteFile) propertySourceInput).showBriefPropertySet()) + return propertyDescriptorArray; + //return briefPropertyDescriptorArray; + + else + { + if (isRegular) return propertyDescriptorArray; + else if (isVirtual) return virtualDescriptorArray; + else if (isArchive) return archiveDescriptorArray; + else return propertyDescriptorArray; + } + + } + + /** + * Create and return a simple string readonly property descriptor. For debug purposes + */ + protected static PropertyDescriptor createSimplePropertyDescriptor(String keyAndLabel) + { + PropertyDescriptor pd = new PropertyDescriptor(keyAndLabel, keyAndLabel); + return pd; + } + + /** + * Returns the current value for the named property. + * @return the current value of the given property + */ + protected Object internalGetPropertyValue(Object key) + { + return getPropertyValue(key, true); + } + + /** + * Returns the current value for the named property. + * + * @param property the name or key of the property as named by its property descriptor + * @param formatted indication of whether to return the value in formatted or raw form + * @return the current value of the given property + */ + public Object getPropertyValue(Object property, boolean formatted) + { + String name = (String) property; + IRemoteFile file = (IRemoteFile) propertySourceInput; + IVirtualRemoteFile virtualFile = null; + boolean isVirtual = file instanceof IVirtualRemoteFile; + if (isVirtual) + { + virtualFile = (IVirtualRemoteFile) file; + } + if (debug) + { + if (name.equals("DEBUG_PARENTREMOTEFILE")) + { + IRemoteFile parent = file.getParentRemoteFile(); + if (parent == null) + return "null"; + else + return "absPath='" + parent.getAbsolutePath() + "'"; + } + else if (name.equals("DEBUG_PARENT")) + return file.getParentPath(); + else if (name.equals("DEBUG_PARENTNOROOT")) + return file.getParentNoRoot(); + else if (name.equals("DEBUG_PARENTNAME")) + return file.getParentName(); + else if (name.equals("DEBUG_ROOT")) + return file.getRoot(); + else if (name.equals("DEBUG_ISROOT")) + return file.isRoot() ? "true" : "false"; + else if (name.equals("DEBUG_EXISTS")) + return file.exists() ? "true" : "false"; + + } + // + if (name.equals(ISystemPropertyConstants.P_FILE_LASTMODIFIED)) + { + Date date = file.getLastModifiedDate(); + if (date != null) + { + if (formatted) + { + SimpleDateFormat datefmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM); + return datefmt.format(date); + } + else + { + return date; + } + } + return date; + } + else if (name.equals(ISystemPropertyConstants.P_FILE_SIZE)) + { + if (formatted) + { + return sub(xlatedSize, MSG_SUB1, Long.toString(file.getLength())); + } + else + { + return new Long(file.getLength()); + } + } + else if (name.equals(ISystemPropertyConstants.P_ARCHIVE_EXPANDEDSIZE)) + { + if (!isVirtual) return new Long(0); + if (formatted) + { + return sub(xlatedExpandedSize, MSG_SUB1, Long.toString(virtualFile.getExpandedSize())); + } + else + { + return new Long(virtualFile.getExpandedSize()); + } + } + else if (name.equals(ISystemPropertyConstants.P_VIRTUAL_COMPRESSEDSIZE)) + { + if (!isVirtual) return new Long(0); + if (formatted) + { + return sub(xlatedCompressedSize, MSG_SUB1, Long.toString(virtualFile.getCompressedSize())); + } + else + { + return new Long(virtualFile.getCompressedSize()); + } + } + else if (name.equals(ISystemPropertyConstants.P_FILE_PATH)) + { + return file.getParentPath(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_CANONICAL_PATH)) + { + return file.getCanonicalPath(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_CLASSIFICATION)) + { + return file.getClassification(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_READONLY)) + { + return file.canWrite() ? getTranslatedNo() : getTranslatedYes(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_READABLE)) + { + return file.canRead() ? getTranslatedYes() : getTranslatedNo(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_WRITABLE)) + { + return file.canWrite() ? getTranslatedYes() : getTranslatedNo(); + } + else if (name.equals(ISystemPropertyConstants.P_FILE_HIDDEN)) + { + return file.isHidden() ? getTranslatedYes() : getTranslatedNo(); + } + else if (name.equals(ISystemPropertyConstants.P_FILTERSTRING)) + { + return file.getFilterString(); + } + else if (name.equals(ISystemPropertyConstants.P_ARCHIVE_COMMENT) || name.equals(ISystemPropertyConstants.P_VIRTUAL_COMMENT)) + { + return file.getComment(); + } + else if (name.equals(ISystemPropertyConstants.P_VIRTUAL_COMPRESSIONMETHOD)) + { + if (!isVirtual) return ""; + return virtualFile.getCompressionMethod(); + } + else if (name.equals(ISystemPropertyConstants.P_VIRTUAL_COMPRESSIONRATIO)) + { + Double ratio = new Double(virtualFile.getCompressionRatio()); + if (formatted) + { + NumberFormat numfmt = NumberFormat.getPercentInstance(); + return numfmt.format(ratio); + } + else + { + return ratio; + } + } + else + return null; //super.getPropertyValue(name); + } + + // Drag and Drop Implementation + + /** + * Indicates whether the specified object can be copied or not. + * @param element the object we want to try to copy + * @return whether this object can be copied or not + */ + public boolean canDrag(Object element) + { + if (element instanceof IRemoteFile) + { + return ((IRemoteFile)element).canRead(); + } + return true; + } + + /** + * Indicates whether the specified object can have another object copied to it + * @param element the object we want to try to copy to + * @return whether this object can be copied to or not + */ + public boolean canDrop(Object element) + { + if (element instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) element; + boolean supportsArchiveManagement = file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + return file.canRead() && file.canWrite() && (file.isDirectory() || file.isRoot() || (file.isArchive() && supportsArchiveManagement)); + } + + return false; + } + + /** + * Return true if it is valid for the src object to be dropped in the target + * @param srcSet the objects to drop + * @param target the object which src is dropped in + * @param sameSystem whether this is the same system + * @return whether this is a valid operation + */ + public boolean validateDrop(ISystemResourceSet srcSet, Object target, boolean sameSystem) + { + if (target instanceof IRemoteFile) + { + IRemoteFile targetFile = (IRemoteFile) target; + boolean supportsArchiveManagement = targetFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + if (!targetFile.isFile() || (targetFile.isArchive() && supportsArchiveManagement)) + { + targetFile.canWrite(); + } + // all objects are of same type, so we only need to use first to validate + Object first = srcSet.get(0); + if (first instanceof IRemoteFile) + { + return true; + } + else if (first instanceof IResource) + { + return true; + } + else if (first instanceof ISystemFilterReference) + { + return true; + } + else // akh11: proposed modification -- 01/28/2005 + { // ask source adapter if it supports drop of its type on this target: + ISystemViewDropDestination adapter = (ISystemViewDropDestination)Platform.getAdapterManager().getAdapter(first,ISystemViewDropDestination.class); + if (adapter != null) + return adapter.supportDropDestination(target); + } + } + return false; + } + + /** + * Return true if it is valid for the src object to be dropped in the target + * @param src the object to drop + * @param target the object which src is dropped in + * @param sameSystem whether this is the same system + * @return whether this is a valid operation + */ + public boolean validateDrop(Object src, Object target, boolean sameSystem) + { + if (target instanceof IRemoteFile) + { + IRemoteFile targetFile = (IRemoteFile) target; + boolean supportsArchiveManagement = targetFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement(); + if (!targetFile.isFile() || (targetFile.isArchive() && supportsArchiveManagement)) + { + // get properties + // this is asynchronous so we call + // it here to prepare for subsequent operation + targetFile.canWrite(); + + if (src instanceof IRemoteFile) + { + return true; + } + else if (src instanceof IResource) + { + return true; + } + else if (src instanceof String) + { + // check if this is a file + java.io.File localFile = new java.io.File((String) src); + if (localFile.exists()) + { + return true; + } + else + { + return false; + } + } + else if (src instanceof ISystemFilterReference) + { + return true; + } + + else // akh11: proposed modification -- 01/28/2005 + { // ask source adapter if it supports drop of its type on this target: + ISystemViewDropDestination adapter = (ISystemViewDropDestination)Platform.getAdapterManager().getAdapter(src,ISystemViewDropDestination.class); + if (adapter != null) + return adapter.supportDropDestination(target); + } + } + } + + return false; + } + + + + /** + * Performs a drag copy operation. The source object is uploaded to a temporary location so that it can + * later be dropped on another remote system. + * @param element the object which is being copied + * @param sameSystem an indication whether a transfer is being made between the same types of systems. + * @param monitor a progress monitor + * @return the temporary object that was created after the upload + */ + public Object doDrag(Object element, boolean sameSystem, IProgressMonitor monitor) + { + + // copy all resources into temporary location + if (element instanceof IRemoteFile) + { + IRemoteFile srcFileOrFolder = (IRemoteFile) element; + return UniversalFileTransferUtility.copyRemoteResourceToWorkspace(srcFileOrFolder, monitor); + } + else if (element instanceof IResource) + { + // if the src is an IResource, then this is our temp object + return element; + } + + return null; + } + + /** + * Overridable by subclasses, and is iff drag and drop supported.
    + * Perform the drag on the given objects. This default implementation simply iterates through the + * set. For optimal performance, this should be overridden. + * + * @param set the set of objects to copy + * @param sameSystemType indication of whether the source and target reside on the same type of system + * @param monitor the progress monitor + * @return a temporary workspace copies of the object that was copied + * + */ + public ISystemResourceSet doDrag(SystemRemoteResourceSet set, IProgressMonitor monitor) + { + + boolean supportsSearch = ((IRemoteFileSubSystemConfiguration)set.getSubSystem().getSubSystemConfiguration()).supportsSearch(); + boolean doSuperTransferProperty = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + if (!doSuperTransferProperty && supportsSearch) + { + SystemRemoteResourceSet flatSet = new SystemRemoteResourceSet(set.getSubSystem(), set.getAdapter()); + long totalByteSize = getFlatRemoteResourceSet(set.getResourceSet(), flatSet, monitor); + flatSet.setByteSize(totalByteSize); + + if (monitor != null) + { + monitor.beginTask(_downloadMessage.getLevelOneText(), (int)totalByteSize); + //monitor.done(); + } + + try + { + SystemWorkspaceResourceSet flatResult = UniversalFileTransferUtility.copyRemoteResourcesToWorkspace(flatSet, monitor); + if (flatResult.hasMessage()) + { + return flatResult; + } + else + { + SystemWorkspaceResourceSet hierarchicalResult = new SystemWorkspaceResourceSet(); + for (int i = 0; i < set.size(); i++) + { + IRemoteFile remoteFile = (IRemoteFile)set.get(i); + hierarchicalResult.addResource(UniversalFileTransferUtility.getTempFileFor(remoteFile)); + } + return hierarchicalResult; + } + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } + } + else + { + return UniversalFileTransferUtility.copyRemoteResourcesToWorkspace(set, monitor); + } + } + + /** + * Helper method to get the local file subsystem. + * @return the local file subsystem + */ + private IRemoteFileSubSystem getLocalFileSubSystem() + { + ISystemRegistry registry = SystemPlugin.getTheSystemRegistry(); + IHost[] connections = registry.getHosts(); + for (int i = 0; i < connections.length; i++) + { + IHost connection = connections[i]; + IRemoteFileSubSystem anFS = RemoteFileUtility.getFileSubSystem(connection); + if (anFS.getHost().getSystemType().equals("Local")) + { + return anFS; + } + } + + return null; + } + + protected long getFlatRemoteResourceSet(List initialResources, SystemRemoteResourceSet flatSet, IProgressMonitor monitor) + { + long totalByteSize = 0; + List configList = new ArrayList(); + + // create a search result set to contain all the results + IHostSearchResultSet searchSet = new HostSearchResultSet(); + + IRemoteFileSubSystem subsys = (IRemoteFileSubSystem)flatSet.getSubSystem(); + if (subsys instanceof FileServiceSubSystem) + { + FileServiceSubSystem ss = (FileServiceSubSystem)subsys; + + SystemSearchString searchString = new SystemSearchString("*", false, false, "*", false, false, true); + + for (int i = 0; i < initialResources.size(); i++) + { + IRemoteFile remoteFile = (IRemoteFile)initialResources.get(i); + + // get all files within directory + if (remoteFile.isDirectory()) + { + // create the configuration for this folder + IHostSearchResultConfiguration config = ss.createSearchConfiguration(searchSet, remoteFile, searchString); + + // kick off search for all files in the folder + subsys.search(config); + configList.add(config); + } + else + { + flatSet.addResource(remoteFile); + } + } + } + + + + SubProgressMonitor submonitor = null; + if (monitor != null) + { + submonitor = new SubProgressMonitor(monitor, configList.size()); + submonitor.setTaskName(FileResources.RESID_SEARCH_MESSAGE_SEARCHING); + + } + // accumulate results + for (int n = 0; n < configList.size(); n++) + { + IHostSearchResultConfiguration config = (IHostSearchResultConfiguration)configList.get(n); + while (config.getStatus() != IHostSearchConstants.FINISHED) + { + if (monitor != null) + { + if (monitor.isCanceled()) + { + return totalByteSize; + } + Display display = Display.getCurrent(); + while (display.readAndDispatch()); + try + { + Thread.sleep(100); + } + catch (Exception e) + { + } + } + else + { + try + { + Thread.sleep(100); + } + catch (Exception e) + { + } + } + } + + if (config.getStatus() == IHostSearchConstants.FINISHED) + { + submonitor.worked(1); + Object[] results = config.getResults(); + for (int m = 0; m < results.length; m++) + { + Object result = results[m]; + if (result instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile)result; + flatSet.addResource(file); + totalByteSize += file.getLength(); + } + } + } + } + //submonitor.done(); + return totalByteSize; + } + + protected long getFlatWorkspaceResourceSet(List resources, SystemWorkspaceResourceSet flatSet, IProgressMonitor monitor) + { + long totalBytes = 0; + for (int i = 0; i < resources.size(); i++) + { + IResource resource = (IResource)resources.get(i); + if (resource instanceof IFile) + { + IFile file = (IFile)resource; + flatSet.addResource(file); + File osFile = file.getLocation().toFile(); + totalBytes += osFile.length(); + } + else if (resource instanceof IContainer) + { + IContainer container = (IContainer)resource; + try + { + IResource[] members = container.members(); + totalBytes += getFlatWorkspaceResourceSet(members, flatSet, monitor); + } + catch (Exception e) + { + } + } + } + return totalBytes; + } + + protected long getFlatWorkspaceResourceSet(IResource[] resources, SystemWorkspaceResourceSet flatSet, IProgressMonitor monitor) + { + long totalBytes = 0; + for (int i = 0; i < resources.length; i++) + { + IResource resource = resources[i]; + if (resource instanceof IFile) + { + IFile file = (IFile)resource; + flatSet.addResource(file); + File osFile = file.getLocation().toFile(); + totalBytes += osFile.length(); + } + else if (resource instanceof IContainer) + { + IContainer container = (IContainer)resource; + try + { + IResource[] members = container.members(); + totalBytes += getFlatWorkspaceResourceSet(members, flatSet, monitor); + } + catch (Exception e) + { + } + } + } + return totalBytes; + } + + + + + /** + * Perform drop from the "fromSet" of objects to the "to" object + * @param from the source objects for the drop + * @param to the target object for the drop + * @param sameSystemType indication of whether the source and target reside of the same type of system + * @param sameSystem indication of whether the source and target are on the same system + * @param srcType the type of objects to be dropped + * @param monitor the progress monitor + * + * @return the set of new objects created from the drop + * + */ + public ISystemResourceSet doDrop(ISystemResourceSet fromSet, Object target, boolean sameSystemType, boolean sameSystem, int srcType, IProgressMonitor monitor) + { + SystemRemoteResourceSet resultSet = new SystemRemoteResourceSet(getSubSystem(target), this); + + if (!sameSystem && sameSystemType) + { + fromSet = doDrag((SystemRemoteResourceSet)fromSet, monitor); + } + + if (target instanceof IRemoteFile) + { + IRemoteFile targetFolder = (IRemoteFile) target; + IRemoteFileSubSystem targetFS = targetFolder.getParentRemoteFileSubSystem(); + + // make sure properties are uptodate + try + { + //targetFolder.markStale(true); + targetFolder = targetFS.getRemoteFileObject(targetFolder.getAbsolutePath()); + } + catch (Exception e) + { + } + + if (!targetFolder.canWrite()) + { + SystemMessage errorMsg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_SECURITY_ERROR); + errorMsg.makeSubstitution(targetFS.getHostAliasName()); + resultSet.setMessage(errorMsg); + return resultSet; + } + + if (!targetFS.isConnected()) + { + return null; + } + + List set = fromSet.getResourceSet(); + if (set.size() > 0) + { + if (fromSet instanceof SystemWorkspaceResourceSet) + { + + boolean doSuperTransferProperty = SystemPlugin.getDefault().getPreferenceStore().getBoolean(ISystemPreferencesConstants.DOSUPERTRANSFER); + if (!doSuperTransferProperty) + { + SystemWorkspaceResourceSet flatFromSet = new SystemWorkspaceResourceSet(); + long totalByteSize = getFlatWorkspaceResourceSet(fromSet.getResourceSet(), flatFromSet, monitor); + + if (monitor != null) + { + int size = (int)totalByteSize; + monitor.beginTask(_uploadMessage.getLevelOneText(), size); + } + // back to hierarchy + return UniversalFileTransferUtility.copyWorkspaceResourcesToRemote((SystemWorkspaceResourceSet)fromSet, targetFolder, monitor, getShell(), true); + } + else + { + return UniversalFileTransferUtility.copyWorkspaceResourcesToRemote((SystemWorkspaceResourceSet)fromSet, targetFolder, monitor, getShell(), true); + } + } + else if (fromSet instanceof SystemRemoteResourceSet) + { + SystemRemoteResourceSet rmtSet = (SystemRemoteResourceSet)fromSet; + + ISystemDragDropAdapter srcAdapter = rmtSet.getAdapter(); + ISubSystem srcSubSystem = rmtSet.getSubSystem(); + + Object first = set.get(0); + if (first instanceof ISystemFilterReference) + { + SystemWorkspaceResourceSet downloadedFilterResults = new SystemWorkspaceResourceSet(); + for (int i = 0; i < set.size(); i++) + { + ISystemFilterReference ref = (ISystemFilterReference)set.get(i); + SystemFilterReference filterReference = (SystemFilterReference) ref; + + + Object[] children = null; + try + { + children = ((SubSystem)srcSubSystem).internalResolveFilterStrings(monitor, filterReference.getReferencedFilter().getFilterStrings()); + } + catch (Exception e) + { + } + + for (int c = 0; c < children.length; c++) + { + Object child = children[c]; + + if (child instanceof IAdaptable) + { + Object newSrc = child; + + if (srcSubSystem != targetFS) + { + ISystemDragDropAdapter cAdapter = (ISystemDragDropAdapter) ((IAdaptable) child).getAdapter(ISystemDragDropAdapter.class); + newSrc = cAdapter.doDrag(child, sameSystemType, monitor); + if (newSrc instanceof SystemMessage) + { + resultSet.setMessage((SystemMessage)newSrc); + return resultSet; + } + else + { + downloadedFilterResults.addResource(newSrc); + } + } + } + } + } + + return doDrop(downloadedFilterResults, target, sameSystemType, srcSubSystem == targetFS, SystemDNDTransferRunnable.SRC_TYPE_RSE_RESOURCE, monitor); + + } + else if (first instanceof IRemoteFile) + { + List toCopy = new ArrayList(); + List toCopyNames = new ArrayList(); + List toCopyBatch = new ArrayList(); + + for (int i = 0; i < set.size(); i++) + { + IRemoteFile srcFileOrFolder = (IRemoteFile)set.get(i); + if (!srcFileOrFolder.exists()) + { + SystemMessage errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_FILE_NOTFOUND); + errorMessage.makeSubstitution(srcFileOrFolder.getAbsolutePath(), srcFileOrFolder.getSystemConnection().getAliasName()); + resultSet.setMessage(errorMessage); + return resultSet; + } + if (!srcFileOrFolder.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) + { + SystemMessage errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_ARCHIVEMANAGEMENT_NOTSUPPORTED); + resultSet.setMessage(errorMessage); + return resultSet; + } + + + String name = srcFileOrFolder.getName(); + + // same systemfor + if (sameSystem) + { + try + { + if (!targetFolder.getAbsolutePath().equals(srcFileOrFolder.getAbsolutePath())) + { + + // should be better doing a query for all in the set + IRemoteFile existingFileOrFolder = ((IRemoteFileSubSystem)srcSubSystem).getRemoteFileObject(targetFolder, name); + if (existingFileOrFolder.exists()) + { + ValidatorFileUniqueName validator = null; + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(getShell(), true, existingFileOrFolder, validator); + dlg.open(); + if (!dlg.wasCancelled()) + name = dlg.getNewName(); + else + name = null; + if (name != null) + { + toCopy.add(srcFileOrFolder); + toCopyNames.add(name); + } + } + else if (name != null) + { + toCopyBatch.add(srcFileOrFolder); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + else // why not same system? should we even get here? + { + System.out.println("HOW DID I GET HERE?!!"); + } + } + + for (int x = 0; x < toCopy.size(); x++) + { + + IRemoteFile srcFileOrFolder = (IRemoteFile)toCopy.get(x); + String name = (String)toCopyNames.get(x); + + /* + SystemMessage copyMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COPY_PROGRESS); + copyMessage.makeSubstitution(srcFileOrFolder.getName(), targetFolder.getName()); + if (monitor != null) + { + monitor.beginTask(copyMessage.getLevelOneText(), 100); + } + */ + try + { + if (targetFS.copy(srcFileOrFolder, targetFolder, name, monitor)) + { + IRemoteFile copiedFile = targetFS.getRemoteFileObject(targetFolder, name); + resultSet.addResource(copiedFile); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + // deal with batch copies now + IRemoteFile[] srcFileOrFolders = new IRemoteFile[toCopyBatch.size()]; + for (int x = 0; x < toCopyBatch.size(); x++) + { + srcFileOrFolders[x] = (IRemoteFile)toCopyBatch.get(x); + } + if (toCopyBatch.size() > 0) + { + try + { + if (targetFS.copyBatch(srcFileOrFolders, targetFolder, monitor)) + { + for (int x = 0; x < toCopyBatch.size(); x++) + { + IRemoteFile copiedFile = targetFS.getRemoteFileObject(targetFolder, srcFileOrFolders[x].getName()); + resultSet.addResource(copiedFile); + } + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + } + } + } + } + return resultSet; + } + + /** + * Perform a copy via drag and drop. + * @param src the object to be copied. If the target and source are not on the same system, then this is a + * temporary object produced by the doDrag. + * @param target the object to be copied to. + * @param sameSystem an indication whether the target and source reside on the same type of system + * @param srcType type of source being transferred + * @param monitor the progress monitor + * @return an indication whether the operation was successful or not. + */ + public Object doDrop(Object src, Object target, boolean sameSystemType, boolean sameSystem, int sourceType, IProgressMonitor monitor) + { + Object result = null; + + // same system type but not necessarily same computer + if (sameSystemType && !sameSystem) + { + src = doDrag(src, sameSystem, monitor); + } + + + if (target instanceof IRemoteFile) + { + IRemoteFile targetFolder = (IRemoteFile) target; + IRemoteFileSubSystem targetFS = targetFolder.getParentRemoteFileSubSystem(); + + // make sure properties are uptodate + try + { + //targetFolder.markStale(true); + targetFolder = targetFS.getRemoteFileObject(targetFolder.getAbsolutePath()); + } + catch (Exception e) + { + } + + if (!targetFolder.canWrite()) + { + SystemMessage errorMsg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_SECURITY_ERROR); + errorMsg.makeSubstitution(targetFS.getHostAliasName()); + return errorMsg; + } + + if (!targetFS.isConnected()) + { + return null; + } + + // non-Eclipse file transfer + + if (sourceType == SystemDNDTransferRunnable.SRC_TYPE_OS_RESOURCE) + { + if (src instanceof String) + { + IRemoteFileSubSystem localFS = getLocalFileSubSystem(); + IRemoteFile srcFileOrFolder = null; + try + { + srcFileOrFolder = localFS.getRemoteFileObject((String) src); + } + catch (SystemMessageException e) + { + return e.getSystemMessage(); + } + + return doDrop(srcFileOrFolder, target, sameSystemType, sameSystem, SystemDNDTransferRunnable.SRC_TYPE_RSE_RESOURCE, monitor); + } + } + if (sourceType == SystemDNDTransferRunnable.SRC_TYPE_TEXT) + { + if (src instanceof String) + { + // noop for now + } + } + + + if (sourceType == SystemDNDTransferRunnable.SRC_TYPE_ECLIPSE_RESOURCE || sourceType == SystemDNDTransferRunnable.SRC_TYPE_RSE_RESOURCE) + { + // Eclipse resource transfer + if (src instanceof IResource) + { + IResource srcFileOrFolder = (IResource) src; + return UniversalFileTransferUtility.copyWorkspaceResourceToRemote(srcFileOrFolder, targetFolder, monitor, true); + } + } + + + // RSE remote file transfer on same system + if (sourceType == SystemDNDTransferRunnable.SRC_TYPE_RSE_RESOURCE) + { + if (src instanceof ISystemFilterReference) + { + SystemFilterReference filterReference = (SystemFilterReference) src; + Object adapter = filterReference.getAdapter(ISystemViewElementAdapter.class); + ISystemViewElementAdapter filterAdapter = (ISystemViewElementAdapter) adapter; + if (filterAdapter != null) + { + SubSystem filterSubSystem = (SubSystem) filterAdapter.getSubSystem(filterReference); + Object[] children = null; + try + { + children = filterSubSystem.internalResolveFilterStrings(monitor, filterReference.getReferencedFilter().getFilterStrings()); + } + catch (Exception e) + { + } + + for (int c = 0; c < children.length; c++) + { + Object child = children[c]; + + if (child instanceof IAdaptable) + { + Object newSrc = child; + + if (filterSubSystem != targetFS) + { + ISystemDragDropAdapter cAdapter = (ISystemDragDropAdapter) ((IAdaptable) child).getAdapter(ISystemDragDropAdapter.class); + newSrc = cAdapter.doDrag(child, sameSystemType, monitor); + if (newSrc instanceof SystemMessage) + { + return newSrc; + } + } + doDrop(newSrc, target, sameSystemType, filterSubSystem == targetFS, SystemDNDTransferRunnable.SRC_TYPE_RSE_RESOURCE, monitor); + } + } + return target; + } + } + else if (src instanceof IRemoteFile) + { + try + { + IRemoteFile srcFileOrFolder = (IRemoteFile) src; + if (!srcFileOrFolder.exists()) + { + SystemMessage errorMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_ERROR_FILE_NOTFOUND); + errorMessage.makeSubstitution(srcFileOrFolder.getAbsolutePath(), srcFileOrFolder.getSystemConnection().getAliasName()); + return errorMessage; + } + + SystemMessage copyMessage = SystemPlugin.getPluginMessage(ISystemMessages.MSG_COPY_PROGRESS); + copyMessage.makeSubstitution(srcFileOrFolder.getName(), targetFolder.getAbsolutePath()); + + IRemoteFileSubSystem localFS = srcFileOrFolder.getParentRemoteFileSubSystem(); + + String name = srcFileOrFolder.getName(); + + if (localFS == targetFS) + { + if (!targetFolder.getAbsolutePath().equals(srcFileOrFolder.getAbsolutePath())) + { + IRemoteFile existingFileOrFolder = localFS.getRemoteFileObject(targetFolder, name); + + if (existingFileOrFolder.exists()) + { + + ValidatorFileUniqueName validator = null; + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(getShell(), true, existingFileOrFolder, validator); + dlg.open(); + if (!dlg.wasCancelled()) + name = dlg.getNewName(); + else + name = null; + } + + if (name != null) + { + monitor.subTask(copyMessage.getLevelOneText()); + if (targetFS.copy(srcFileOrFolder, targetFolder, name, monitor)) + { + IRemoteFile copiedFile = targetFS.getRemoteFileObject(targetFolder, name); + return copiedFile; + + } + } + } + } + else + { + + System.out.println("how do we get here!??"); + + if (srcFileOrFolder.isFile()) + { + try + { + name = checkForCollision(getShell(), targetFolder, name); + if (name == null) + { + return null; + } + + boolean isTargetArchive = targetFolder.isArchive(); + StringBuffer newPathBuf = new StringBuffer(targetFolder.getAbsolutePath()); + if (isTargetArchive) + { + newPathBuf.append(ArchiveHandlerManager.VIRTUAL_SEPARATOR); + } + else + { + newPathBuf.append(targetFolder.getSeparatorChar()); + } + newPathBuf.append(name); + + String newPath = newPathBuf.toString(); + + monitor.subTask(copyMessage.getLevelOneText()); + targetFS.upload(srcFileOrFolder.getAbsolutePath(), newPath, monitor); + + result = targetFS.getRemoteFileObject(targetFolder, name); + return result; + + } + catch (RemoteFileIOException e) + { + return e.getSystemMessage(); + + } + catch (RemoteFileSecurityException e) + { + return e.getSystemMessage(); + } + catch (Exception e) + { + } + + return null; + } + else + { + // this is a directory + // recursively copy + boolean isTargetArchive = targetFolder.isArchive(); + StringBuffer newPathBuf = new StringBuffer(targetFolder.getAbsolutePath()); + if (isTargetArchive) + { + newPathBuf.append(ArchiveHandlerManager.VIRTUAL_SEPARATOR); + } + else + { + newPathBuf.append(targetFolder.getSeparatorChar()); + } + newPathBuf.append(name); + + String newPath = newPathBuf.toString(); + + IRemoteFile newTargetFolder = targetFS.getRemoteFileObject(newPath); + targetFS.createFolder(newTargetFolder); + + IRemoteFile[] children = localFS.listFoldersAndFiles(srcFileOrFolder); + if (children != null) + { + for (int i = 0; i < children.length; i++) + { + if (monitor.isCanceled()) + { + return null; + } + else + { + IRemoteFile child = children[i]; + if (doDrop(child, newTargetFolder, sameSystemType, sameSystem, sourceType, monitor) == null) + { + return null; + } + } + } + } + + return newTargetFolder; + } + } + } + catch (SystemMessageException e) + { + return e.getSystemMessage(); + } + } + } + } + else + { + result = null; + } + + return result; + } + + protected String checkForCollision(Shell shell, IRemoteFile targetFolder, String oldName) + { + String newName = oldName; + + try + { + + IRemoteFileSubSystem ss = targetFolder.getParentRemoteFileSubSystem(); + IRemoteFile targetFileOrFolder = ss.getRemoteFileObject(targetFolder, oldName); + + //SystemPlugin.logInfo("CHECKING FOR COLLISION ON '"+srcFileOrFolder.getAbsolutePath() + "' IN '" +targetFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...TARGET FILE: '"+tgtFileOrFolder.getAbsolutePath()+"'"); + //SystemPlugin.logInfo("...target.exists()? "+tgtFileOrFolder.exists()); + if (targetFileOrFolder.exists()) + { + //monitor.setVisible(false); wish we could! + + // we no longer have to set the validator here... the common rename dialog we all now use queries the input + // object's system view adaptor for its name validator. See getNameValidator in SystemViewRemoteFileAdapter. phil + ValidatorFileUniqueName validator = null; // new ValidatorFileUniqueName(shell, targetFolder, srcFileOrFolder.isDirectory()); + //SystemCollisionRenameDialog dlg = new SystemCollisionRenameDialog(shell, validator, oldName); + SystemRenameSingleDialog dlg = new SystemRenameSingleDialog(shell, true, targetFileOrFolder, validator); // true => copy-collision-mode + + dlg.open(); + if (!dlg.wasCancelled()) + newName = dlg.getNewName(); + else + newName = null; + } + } + catch (SystemMessageException e) + { + SystemBasePlugin.logError("SystemCopyRemoteFileAction.checkForCollision()", e); + } + + return newName; + } + + // FOR COMMON DELETE ACTIONS + /** + * Yes, remote file objects are deletable! + */ + public boolean canDelete(Object element) + { + IRemoteFile file = (IRemoteFile) element; + //System.out.println("INSIDE CANDELETE FOR ADAPTER: RETURNING " + !file.isRoot()); + return !file.isRoot() && file.canRead(); + } + /** + * Perform the delete action. Defers request to the remote file subsystem + * @deprecated use the one with monitor now + */ + public boolean doDelete(Shell shell, Object element) throws Exception + { + return doDelete(shell, element, null); + } + + /** + * Perform the delete action. Defers request to the remote file subsystem + */ + public boolean doDelete(Shell shell, Object element, IProgressMonitor monitor) throws Exception + { + boolean ok; + IRemoteFile file = (IRemoteFile) element; + IRemoteFile parentFile = file.getParentRemoteFile(); + + IRemoteFileSubSystem ss = file.getParentRemoteFileSubSystem(); + try + { + // DKM - propagate the deletion to temp files project + IResource tmp = UniversalFileTransferUtility.getTempFileFor(file); + if (tmp.exists()) + { + try + { + tmp.delete(false, null); + } + catch (Exception e) + { + } + } + + /* + + ISystemEditableRemoteObject editable = getEditableRemoteObject(file); + if (editable != null) + { + try + { + if (editable.checkOpenInEditor() == ISystemEditableRemoteObject.OPEN_IN_SAME_PERSPECTIVE) + { + // for now, leave this + } + else + { + IFile localfile = editable.getLocalResource(); + if (localfile != null) + { + // delete this too + localfile.delete(true, null); + } + } + } + catch (Exception e) + { + + } + } + */ + ok = ss.delete(file, monitor); + + file.markStale(true); + parentFile.markStale(true); + } + catch (Exception exc) + { + ok = false; + SystemMessageDialog.displayErrorMessage(shell, SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_DELETE_FILE_FAILED).makeSubstitution(file.toString())); + } + return ok; + } + + /** + * Perform the delete action. Defers request to the remote file subsystem + */ + public boolean doDeleteBatch(Shell shell, List resourceSet, IProgressMonitor monitor) throws Exception + { + boolean ok; + IRemoteFileSubSystem ss = null; + IRemoteFile[] files = new IRemoteFile[resourceSet.size()]; + for (int i = 0; i < resourceSet.size(); i++) + { + IRemoteFile file = (IRemoteFile) resourceSet.get(i); + files[i] = file; + IRemoteFile parentFile = file.getParentRemoteFile(); + if (ss == null) ss = file.getParentRemoteFileSubSystem(); + try + { + // DKM - propagate the deletion to temp files project + IResource tmp = UniversalFileTransferUtility.getTempFileFor(file); + if (tmp.exists()) + { + try + { + tmp.delete(false, null); + } + catch (Exception e) + { + } + } + file.markStale(true); + parentFile.markStale(true); + } + catch (Exception exc) + { + ok = false; + SystemMessageDialog.displayErrorMessage(shell, SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_DELETE_FILE_FAILED).makeSubstitution(file.toString())); + } + } + ok = ss.deleteBatch(files, monitor); + return ok; + } + // FOR COMMON RENAME ACTIONS + /** + * Yes, remote file objects are renamable! + */ + public boolean canRename(Object element) + { + IRemoteFile file = (IRemoteFile) element; + return !file.isRoot() && file.canRead(); + } + + private void moveTempResource(IResource localResource, IPath newLocalPath, IRemoteFileSubSystem ss, String newRemotePath) + { + if (localResource != null) + { + try + { + moveTempFileProperties(localResource, ss, newRemotePath); + localResource.move(newLocalPath, true, null); + + } + catch (Exception e) + { + } + + } + } + + private void moveTempFileProperties(IResource localResource, IRemoteFileSubSystem ss, String remotePath) + { + + if (localResource instanceof IContainer) + { + IContainer localContainer = (IContainer) localResource; + try + { + IResource[] members = localContainer.members(); + for (int i = 0; i < members.length; i++) + { + IResource member = members[i]; + moveTempFileProperties(member, ss, remotePath + "/" + member.getName()); + } + } + catch (Exception e) + { + } + } + else if (localResource instanceof IFile) + { + IFile localFile = (IFile)localResource; + try + { + SystemIFileProperties properties = new SystemIFileProperties(localFile); + properties.setRemoteFilePath(remotePath); + + Object editableObj = properties.getRemoteFileObject(); + if (editableObj != null) + { + SystemEditableRemoteFile editable = (SystemEditableRemoteFile)editableObj; + // there's an in-memory editable, so change the associated remote file + IRemoteFile newRemoteFile = ss.getRemoteFileObject(remotePath); + editable.setRemoteFile(newRemoteFile); + } + } + catch (Exception e) + { + } + + } + + } + + /** + * Perform the rename action. Defers request to the remote file subsystem + */ + public boolean doRename(Shell shell, Object element, String newName) throws Exception + { + boolean ok = true; + IRemoteFile file = (IRemoteFile) element; + IRemoteFileSubSystem ss = file.getParentRemoteFileSubSystem(); + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + try + { + + String newRemotePath = file.getParentPath() + "/" + newName; + IResource localResource = null; + if (SystemRemoteEditManager.getDefault().doesRemoteEditProjectExist()) + { + localResource = UniversalFileTransferUtility.getTempFileFor(file); + } + + ss.rename(file, newName); + if (localResource != null && localResource.exists()) + { + + IPath newLocalPath = localResource.getParent().getFullPath().append(newName); + moveTempResource(localResource, newLocalPath, ss, newRemotePath); + } + + if (file.isDirectory()) + { + // update all tree views showing this remote folder... + // Hmm, why do we do this, given SystemView sends a rename event? I think we needed to refresh all child cached references to parent folder name... + SystemResourceChangeEvent event = new SystemResourceChangeEvent(file.getParentRemoteFile(), ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, null); + sr.fireEvent(event); + //sr.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_RENAMED, file, file.getParentRemoteFile(), file.getParentRemoteFileSubSystem(), null, null); + } + file.markStale(true); + + } + catch (Exception exc) + { + ok = false; + SystemMessageDialog.displayErrorMessage(shell, SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_RENAME_FILE_FAILED).makeSubstitution(file.toString())); + } + return ok; + } + + /** + * Return a validator for verifying the new name is correct. + * Defers request to the subsystem factory, calling either getFileNameValidator or getFolderNameValidator. + */ + public ISystemValidator getNameValidator(Object element) + { + if (element instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) element; + if (file.isDirectory()) + return file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().getFolderNameValidator(); + else + return file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().getFileNameValidator(); + } + return null; + } + /** + * Parent override. + *

    + * Form and return a new canonical (unique) name for this object, given a candidate for the new + * name. This is called by the generic multi-rename dialog to test that all new names are unique. + * To do this right, sometimes more than the raw name itself is required to do uniqueness checking. + *

    + * Returns newName, but uppercased for Windows file systems + */ + public String getCanonicalNewName(Object element, String newName) + { + if (element instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) element; + if (file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().isUnixStyle()) + return newName; + else + return newName.toUpperCase(); + } + else + return newName; + } + /** + * Parent override. + *

    + * Compare the name of the given element to the given new name to decide if they are equal. + * Allows adapters to consider case and quotes as appropriate. + *

    + * For Unix/Linux, returns the result of getName(element).equals(newName), which is to say, + * it is a case sensitive compare. For windows, it is case insensitive (equalsIgnoreCase). + */ + public boolean namesAreEqual(Object element, String newName) + { + if (element instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) element; + if (file.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().isUnixStyle()) + return getName(element).equals(newName); + else + return getName(element).equalsIgnoreCase(newName); + } + else + return super.namesAreEqual(element, newName); + } + // ------------------------------------------------------------ + // METHODS FOR SAVING AND RESTORING EXPANSION STATE OF VIEWER... + // ------------------------------------------------------------ + /** + * Return a short string to uniquely identify the type of resource. Eg "conn" for connection. + * This just defaults to getType, but if that is not sufficient override it here, since that is + * a translated string. + */ + public String getMementoHandleKey(Object element) + { + return ISystemMementoConstants.MEMENTO_KEY_REMOTE; + } + + // -------------------------------------------------------------------- + // METHODS PRESCRIBED BY THE ISYSTEMREMOTEELEMENT ADAPTER INTERFACE... + // -------------------------------------------------------------------- + /** + * Return fully qualified name that uniquely identifies this object within its subsystem + */ + public String getAbsoluteName(Object element) + { + IRemoteFile file = (IRemoteFile) element; + return file.getAbsolutePath(); + } + /** + * Return fully qualified name that uniquely identifies this remote object's remote parent within its subsystem + */ + public String getAbsoluteParentName(Object element) + { + IRemoteFile file = (IRemoteFile) element; + return file.getParentPath(); + } + + /** + * Return subsystem + */ + public ISubSystem getSubSystem(Object element) + { + if (element instanceof IRemoteFile) + { + IRemoteFile file = (IRemoteFile) element; + return file.getParentRemoteFileSubSystem(); + } + return null; + } + /** + * Return the subsystem factory id that owns this remote object + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getSubSystemFactoryId(Object element) + { + IRemoteFile file = (IRemoteFile) element; + return file.getParentRemoteFileSubSystem().getSubSystemConfiguration().getId(); + } + + /** + * Return a value for the type category property for this object + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getRemoteTypeCategory(Object element) + { + return ISystemFileRemoteTypes.TYPECATEGORY; + } + /** + * Return the untranslated type for this object. + * For files, returns the "file" + * For folders or roots, returns "folder" + */ + public String getRemoteType(Object element) + { + IRemoteFile file = (IRemoteFile) element; + if (!file.isRoot() && !file.isDirectory()) + return ISystemFileRemoteTypes.TYPE_FILE; + else + return ISystemFileRemoteTypes.TYPE_FOLDER; + } + /** + * Return the untranslated subtype for this object. + * For files, returns the file extension. Eg, for abc.java this returns "java". + * For folders, returns "root" or "subfolder" + */ + public String getRemoteSubType(Object element) + { + IRemoteFile file = (IRemoteFile) element; + if (file.isFile()) + return file.getExtension(); + else if (file.isRoot()) + return ISystemFileRemoteTypes.SUBTYPE_ROOT; + else + return ISystemFileRemoteTypes.SUBTYPE_SUBFOLDER; + } + /** + * Return the untranslated sub-subtype for this object. + * Returns null for now. + */ + public String getRemoteSubSubType(Object element) + { + return null; + } + /** + * Return the source type of the selected object. Typically, this only makes sense for compilable + * source members. For non-compilable remote objects, this typically just returns null. + *

    + * For files, this returns the extension. For folders, it returns null. + */ + public String getRemoteSourceType(Object element) + { + IRemoteFile file = (IRemoteFile) element; + String srcType = null; + if (file.isFile()) + { + srcType = file.getExtension(); + if (srcType == null) + srcType = "blank"; + else if (srcType.length() == 0) + srcType = "null"; + } + return srcType; + } + /** + * Some view has updated the name or properties of this remote object. As a result, the + * remote object's contents need to be refreshed. You are given the old remote object that has + * old data, and you are given the new remote object that has the new data. For example, on a + * rename the old object still has the old name attribute while the new object has the new + * new attribute. + *

    + * This is called by viewers like SystemView in response to rename and property change events. + *

    + * @param oldElement the element that was found in the tree + * @param newElement the updated element that was passed in the REFRESH_REMOTE event + * @return true if you want the viewer that called this to refresh the children of this object, + * such as is needed on a rename of a folder, say. + */ + public boolean refreshRemoteObject(Object oldElement, Object newElement) + { + //System.out.println("INSIDE REFRESHREMOTEOBJECT"); + if (oldElement instanceof RemoteFile) + { + /* FIXME do we still need this? + RemoteFile oldFile = (RemoteFile) oldElement; + RemoteFile newFile = (RemoteFile) newElement; + + oldFile.setName(newFile.getName()); + oldFile.setCanRead(newFile.canRead()); + oldFile.setCanWrite(newFile.canWrite()); + oldFile.setIsHidden(newFile.isHidden()); + oldFile.setLastModified(newFile.getLastModified()); + oldFile.setLength(newFile.getLength()); + // if (oldFile instanceof LocalFileImpl) + // { + // LocalFileImpl oldLocalFile = (LocalFileImpl)oldFile; + // LocalFileImpl newLocalFile = (LocalFileImpl)newFile; + oldFile.setFile(newFile.getFile()); + // } + return oldFile.isDirectory(); // refresh kids if this is a directory + */ + return true; + } + return false; + } + + /** + * Given a remote object, returns it remote parent object. Eg, given a file, return the folder + * it is contained in. + *

    + * The shell is required in order to set the cursor to a busy state if a remote trip is required. + * + * @return an IRemoteFile object for the parent + */ + public Object getRemoteParent(Shell shell, Object element) throws Exception + { + return ((IRemoteFile) element).getParentRemoteFile(); + } + /** + * Given a remote object, return the unqualified names of the objects contained in that parent. This is + * used for testing for uniqueness on a rename operation, for example. Sometimes, it is not + * enough to just enumerate all the objects in the parent for this purpose, because duplicate + * names are allowed if the types are different, such as on iSeries. In this case return only + * the names which should be used to do name-uniqueness validation on a rename operation. + * + * @return an array of all file and folder names in the parent of the given IRemoteFile object + */ + public String[] getRemoteParentNamesInUse(Shell shell, Object element) throws Exception + { + String[] names = EMPTY_STRING_LIST; + + IRemoteFile file = (IRemoteFile) element; + String parentName = file.getParentPath(); + if (parentName == null) // given a root? + return names; // not much we can do. Should never happen: you can't rename a root! + + // DKM - changed this so that we can take advantage of caching + Object[] children = getChildren(file.getParentRemoteFile()); + if ((children == null) || (children.length == 0)) + return names; + + names = new String[children.length]; + for (int idx = 0; idx < names.length; idx++) + names[idx] = ((IRemoteFile) children[idx]).getName(); + + return names; + } + + /** + * User has double clicked on an object. We want to open the object in the applicable editor. + * Return true to indicate that we are handling the double-click event. + */ + public boolean handleDoubleClick(Object element) + { + IRemoteFile remoteFile = (IRemoteFile) element; + if (!remoteFile.canRead()) + { + return false; + } + /** FIXME commands now separate from this + else if (testAttribute(remoteFile, "classification", "*executable*") || + testAttribute(remoteFile, "classification", "*script") || + testAttribute(remoteFile, "classification", "symbolic link(script)*") + ) + { + // instead of opening in editor + // attempt to execute it + return RemoteCommandHelpers.runUniversalCommand(getShell(), remoteFile.getName(), remoteFile.getParentPath(), + remoteFile.getParentRemoteFileSubSystem().getCommandSubSystem()); + } + */ + else if (!remoteFile.isArchive() || !remoteFile.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory().supportsArchiveManagement()) + { + // only handle double click if object is a file + ISystemEditableRemoteObject editable = getEditableRemoteObject(remoteFile); + if (editable != null) + { + try + { + if (editable.checkOpenInEditor() != ISystemEditableRemoteObject.OPEN_IN_SAME_PERSPECTIVE) + { + editable.open(getShell()); + } + else + { + editable.setLocalResourceProperties(); + editable.openEditor(); + } + } + catch (Exception e) + { + } + } + else if (remoteFile.isDirectory()) + { + return false; + } + + //SystemDoubleClickEditAction editAction = new SystemDoubleClickEditAction(element); + //editAction.run(); + return true; + } + else + { // if object is a folder, do not handle it + return false; + } + } + + public boolean canEdit(Object element) + { + IRemoteFile remoteFile = (IRemoteFile) element; + if (remoteFile.isFile()) + { + return remoteFile.canRead(); + } + return false; + } + + public ISystemEditableRemoteObject getEditableRemoteObject(Object element) + { + RemoteFile remoteFile = (RemoteFile) element; + if (remoteFile.isFile()) + { + try + { + IFile file = getCachedCopy(remoteFile); + if (file != null) + { + SystemIFileProperties properties = new SystemIFileProperties(file); + Object obj = properties.getRemoteFileObject(); + if (obj != null && obj instanceof ISystemEditableRemoteObject) + { + ISystemEditableRemoteObject rmtObj = (ISystemEditableRemoteObject) obj; + IAdaptable rmtFile = rmtObj.getRemoteObject(); + if (rmtFile instanceof IRemoteFile) + { + //((IRemoteFile)rmtFile).markStale(true); + } + return rmtObj; + } + } + + return new SystemEditableRemoteFile(remoteFile); + } + catch (Exception e) + { + } + } + return null; + } + + public IFile getCachedCopy(IRemoteFile remoteFile) throws SystemMessageException + { + if (SystemRemoteEditManager.getDefault().doesRemoteEditProjectExist()) + { + IResource replica = UniversalFileTransferUtility.getTempFileFor(remoteFile); + if (replica != null && replica.exists()) + { + return (IFile)replica; + } + } + return null; + } + + /** + * Return a filter string that corresponds to this object. + * @param object the object to obtain a filter string for + * @return the corresponding filter string if applicable + */ + public String getFilterStringFor(Object object) + { + if (object instanceof IRemoteFile) + { + IRemoteFile remoteFile = (IRemoteFile) object; + if (remoteFile.isDirectory()) + { + return remoteFile.getAbsolutePath() + remoteFile.getSeparator() + "*"; + } + else + { + return remoteFile.getAbsolutePath(); + } + } + return null; + } + + /** + * From IActionFilter, it exposes properties for decorator and popupMenus extension points. + *

    + *

      + *
    1. name="name". The given value must match the name exactly or if ends with an asterisk the beginning must match. + * (case sensitiveness depends on the subsystem)
    2. + *
    3. name="absolutePath". The given value must match the absolute path exactly or if ends with an asterisk the beginning must match. + * (case sensitiveness depends on the subsystem)
    4. + *
    5. name="extension". The given value must match the extension exactly or if ends with an asterisk the beginning must match. + * (case sensitiveness depends on the subsystem)
    6. + *
    7. name="isRoot". If the given value is true, then returns true if the target is a root file. + * If the given value is false, then returns true if the target is not root.
    8. + *
    9. name="isFile". If the given value is true, then returns true if the target is a file. + * If the given value is false, then returns true if the target is not a file.
    10. + *
    11. name="isDirectory". If the given value is true, then returns true if the target is a directory. + * If the given value is false, then returns true if the target is not a directory.
    12. + *
    13. name="isHidden". If the given value is true, then returns true if the target is a hidden file. + * If the given value is false, then returns true if the target is not a hidden file.
    14. + *
    15. name="canRead". If the given value is true, then returns true if the target is readable. + * If the given value is false, then returns true if the target is not readable.
    16. + *
    17. name="canWrite". If the given value is true, then returns true if the target is writable. + * If the given value is false, then returns true if the target is not writable.
    18. + *
    19. name="isBinary". If the given value is true, then returns true if the target is a binary file. + * If the given value is false, then returns true if the target is not a binary file.
    20. + *
    21. name="isText". If the given value is true, then returns true if the target is a text file. + * If the given value is false, then returns true if the target is not a text file.
    22. + *
    23. name="isArchive". If the given value is true, then returns true if the target is an archive file. + * If the given value is false, then returns true if the target is not an archive file.
    24. + *
    25. name="isVirtual". If the given value is true, then returns true if the target is a virtual file. + * If the given value is false, then returns true if the target is not a virtual file.
    26. + *
    + *

    + * @see org.eclipse.ui.IActionFilter#testAttribute(java.lang.Object, java.lang.String, java.lang.String) + */ + public boolean testAttribute(Object target, String name, String value) { + + if (target instanceof IRemoteFile) + { + IRemoteFile tgt = (IRemoteFile) target; + + String inName = name.toLowerCase(); + + + if (inName.equals("classification")) + { + String classification = tgt.getClassification(); + + if (classification != null) + { + return StringCompare.compare(value, classification, true); + } + } + else if (inName.equals("name")) + { + boolean caseSensitive = tgt.getParentRemoteFileSubSystem().isCaseSensitive(); + + String tgtName = getName(target); + String val = value; + + // if case does not matter, then lower case the compares + if (!caseSensitive) { + tgtName = tgtName.toLowerCase(); + val = val.toLowerCase(); + } + + // we have a wild card test, and * is the last character in the value + if (val.endsWith("*")) { + return tgtName.startsWith(val.substring(0, val.length()-1)); + } + else { + return val.equals(tgtName); + } + } + else if (inName.equals("absolutePath".toLowerCase())) { + + boolean caseSensitive = tgt.getParentRemoteFileSubSystem().isCaseSensitive(); + + String tgtPath = getAbsoluteName(target); + String val = value; + + // if case does not matter, then lower case the compares + if (!caseSensitive) { + tgtPath = tgtPath.toLowerCase(); + val = val.toLowerCase(); + } + + // we have a wild card test, and * is the last character in the value + if (val.endsWith("*")) { + return tgtPath.startsWith(val.substring(0, val.length()-1)); + } + else { + return val.equals(tgtPath); + } + } + else if (inName.equals("extension")) { + + boolean caseSensitive = tgt.getParentRemoteFileSubSystem().isCaseSensitive(); + + String tgtExtension = tgt.getExtension(); + + if (tgtExtension == null) { + return false; + } + + StringTokenizer st = new StringTokenizer(value, " \t\n\r\f,"); + + String val = null; + + while (st.hasMoreTokens()) { + + val = st.nextToken(); + + // if case does not matter, then lower case the compares + if (!caseSensitive) { + tgtExtension = tgtExtension.toLowerCase(); + val = val.toLowerCase(); + } + + boolean match = false; + + // we have a wild card test, and * is the last character in + // the value + if (val.endsWith("*")) { + match = tgtExtension.startsWith(val.substring(0, val.length() - 1)); + } + else { + match = val.equals(tgtExtension); + } + + // if there is a match, return true, otherwise check against next extension + if (match) { + return true; + } + } + + // return false if no match + return false; + } + else if (inName.equals("isroot")) + { + return tgt.isRoot() && value.equals("true") || + !tgt.isRoot() && value.equals("false"); + } + else if (inName.equals("isfile")) + { + return tgt.isFile() && value.equals("true") || + !tgt.isFile() && value.equals("false"); + } + else if (inName.equals("isdirectory")) + { + return tgt.isDirectory() && value.equals("true") || + !tgt.isDirectory() && value.equals("false"); + } + else if (inName.equals("ishidden")) + { + return tgt.isHidden() && value.equals("true") || + !tgt.isHidden() && value.equals("false"); + } + else if (inName.equals("canread")) + { + return tgt.canRead() && value.equals("true") || + !tgt.canRead() && value.equals("false"); + } + else if (inName.equals("canwrite")) + { + return tgt.canWrite() && value.equals("true") || + !tgt.canWrite() && value.equals("false"); + } + else if (inName.equals("isbinary")) + { + return tgt.isBinary() && value.equals("true") || + !tgt.isBinary() && value.equals("false"); + } + else if (inName.equals("istext")) + { + return tgt.isText() && value.equals("true") || + !tgt.isText() && value.equals("false"); + } + else if (inName.equals("isarchive")) { + return tgt.isArchive() && value.equals("true") || + !tgt.isArchive() && value.equals("false"); + } + else if (inName.equals("isvirtual")) + { + return tgt instanceof IVirtualRemoteFile && value.equals("true") || + !(tgt instanceof IVirtualRemoteFile) && value.equals("false"); + } + else if (inName.equals("isexecutable")) + { + return tgt.isExecutable() && value.equals("true") || + !tgt.isExecutable() && value.equals("false"); + } + else if (inName.equals("islink")) + { + return tgt.isLink() && value.equals("true") || + !tgt.isLink() && value.equals("false"); + } + } + + return super.testAttribute(target, name, value); + } + + /* + * Return whether deferred queries are supported. + */ + public boolean supportsDeferredQueries() + { + return true; + } + + + protected SystemFetchOperation getSystemFetchOperation(Object o, IElementCollector collector) + { + return new SystemFetchOperation(null, (IAdaptable)o, this, collector, true); + } + + /** + * Returns false if the file is a virtual file, otherwise defaults to asking the subsystem + * factory. + * @see org.eclipse.rse.ui.view.ISystemRemoteElementAdapter#supportsUserDefinedActions(java.lang.Object) + */ + public boolean supportsUserDefinedActions(Object object) { + + // if object is an instance of a remote file + if (object instanceof IRemoteFile) { + + IRemoteFile file = (IRemoteFile)object; + + // virtual files do not support user defined actions + if (file instanceof IVirtualRemoteFile) { + return false; + } + else { + return getSubSystem(object).getSubSystemConfiguration().supportsUserDefinedActions(); + } + } + else { + return getSubSystem(object).getSubSystemConfiguration().supportsUserDefinedActions(); + } + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultAdapter.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultAdapter.java new file mode 100644 index 00000000000..6de60fec05f --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultAdapter.java @@ -0,0 +1,729 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.files.ui.actions.SystemRemoteFileSearchOpenWithMenu; +import org.eclipse.rse.files.ui.resources.SystemEditableRemoteFile; +import org.eclipse.rse.services.search.IHostSearchResult; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.shells.core.model.ISystemOutputRemoteTypes; +import org.eclipse.rse.subsystems.shells.core.subsystems.IRemoteCommandShell; +import org.eclipse.rse.ui.ISystemContextMenuConstants; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.SystemMenuManager; +import org.eclipse.rse.ui.actions.SystemCopyToClipboardAction; +import org.eclipse.rse.ui.view.AbstractSystemViewAdapter; +import org.eclipse.rse.ui.view.ISystemDragDropAdapter; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemPropertyConstants; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.rse.ui.view.SystemViewResources; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.views.properties.IPropertyDescriptor; +import org.eclipse.ui.views.properties.PropertyDescriptor; + + +/** + * Adapter class to enable the output of a search to be "live" in that it has actions and properties. + */ +public class SystemViewRemoteSearchResultAdapter extends AbstractSystemViewAdapter implements ISystemRemoteElementAdapter, ISystemOutputRemoteTypes +{ + + protected IPropertyDescriptor[] _propertyDescriptors; + + + private SystemCopyToClipboardAction _copyOutputAction = null; + + public SystemViewRemoteSearchResultAdapter() { + } + + /** + * We should not add common actions such as compile and user actions for this adapter. + * @see org.eclipse.rse.ui.view.AbstractSystemViewAdapter#addCommonRemoteActions(org.eclipse.rse.ui.SystemMenuManager, org.eclipse.jface.viewers.IStructuredSelection, org.eclipse.swt.widgets.Shell, java.lang.String) + */ + public void addCommonRemoteActions(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) { + + if (selection != null && !selection.isEmpty()) { + + Iterator iter = selection.iterator(); + + boolean found = false; + + // go through selections and see if there is one IHostSearchResult + // if there is, we do not add any common remote actions + while (iter.hasNext()) { + Object obj = iter.next(); + + if (obj instanceof IHostSearchResult) { + found = true; + break; + } + } + + if (!found) { + super.addCommonRemoteActions(menu, selection, shell, menuGroup); + } + } + else { + super.addCommonRemoteActions(menu, selection, shell, menuGroup); + } + } + + /** + * Contributed context menu actions for a remote search result + */ + public void addActions(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) + { + Object firstSelection = selection.getFirstElement(); + + if (firstSelection != null) + { + if (_copyOutputAction == null) + { + _copyOutputAction = new SystemCopyToClipboardAction(shell, SystemPlugin.getTheSystemRegistry().getSystemClipboard()); + } + menu.add(menuGroup, _copyOutputAction); + + if (selection.size() == 1) + { + if (firstSelection instanceof IHostSearchResult) + { + // IHostSearchResult result = (IHostSearchResult) firstSelection; + //SystemSearchCreateEditLineActions createActions = new SystemSearchCreateEditLineActions(); + //createActions.create(menu, selection, shell, menuGroup); + MenuManager submenu = new MenuManager(FileResources.ResourceNavigator_openWith, ISystemContextMenuConstants.GROUP_OPENWITH); + + SystemRemoteFileSearchOpenWithMenu openWithMenu = new SystemRemoteFileSearchOpenWithMenu(); + openWithMenu.updateSelection(selection); + submenu.add(openWithMenu); + menu.getMenuManager().appendToGroup(ISystemContextMenuConstants.GROUP_OPENWITH, submenu); + } + } + } + else + { + return; + } + } + + /** + * Returns the parent of the search result (i.e. IHostSearchResults) + */ + public Object getParent(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) element; + return output.getParent(); + } + return null; + } + + /** + * Returns the display text for this search result + */ + public String getText(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) element; + return output.getText(); + } + + return null; + } + + /** + * Returns nothing + */ + public String getType(Object element) + { + return null; + } + + /** + * Returns nothing + */ + public Object[] getChildren(Object element) + { + return null; + } + + /** + * Returns false. + */ + public boolean hasChildren(Object element) + { + return false; + } + + /** + * Returns the associated remote file for a search result + * @param output the search result + * @return the associated remote file + */ + public static IRemoteFile outputToFile(IHostSearchResult output) + { + return (IRemoteFile)output.getParent(); + } + + + /** + * Opens the appropriate editor for a remote search result object + */ + public boolean handleDoubleClick(Object element) + { + boolean result = false; + if (element instanceof IHostSearchResult) + { + + IHostSearchResult searchResult = (IHostSearchResult) element; + IRemoteFile file = outputToFile(searchResult); + if (file != null && file.isFile()) + { + ISystemViewElementAdapter adapter = (ISystemViewElementAdapter)((IAdaptable)file).getAdapter(ISystemViewElementAdapter.class); + result = adapter.handleDoubleClick(file); + int line = searchResult.getLine(); + + if (result) + { + if (line > 0) + { + SystemRemoteFileSearchOpenWithMenu.handleGotoLine(file, searchResult); + } + return true; + } + } + } + + return result; + } + + /** + * Returns the associated subsystem for this search result + */ + public ISubSystem getSubSystem(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) element; + Object parent = output.getParent(); + + if (parent instanceof IRemoteFile) { + return ((IRemoteFile)parent).getParentRemoteFileSubSystem(); + } + } + + return null; + } + + /** + * Return the fully qualified name of this remote object. + */ + public String getAbsoluteName(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult searchResult = (IHostSearchResult)element; + + StringBuffer buf = new StringBuffer(); + + String str = getAbsoluteParentName(element); + + if (str == null) { + return null; + } + + // create the absolute name with this format + // remoteFilePath:SEARCH + buf.append(str); + buf.append(IHostSearchResult.SEARCH_RESULT_DELIMITER); + buf.append(IHostSearchResult.SEARCH_RESULT_OPEN_DELIMITER); + buf.append(searchResult.getMatchingSearchString().toString()); + buf.append(IHostSearchResult.SEARCH_RESULT_INDEX_DELIMITER); + buf.append(searchResult.getIndex()); + buf.append(IHostSearchResult.SEARCH_RESULT_CLOSE_DELIMITER); + + return buf.toString(); + } + + return null; + } + + /** + * Return fully qualified name that uniquely identifies this remote object's remote parent within its subsystem + */ + public String getAbsoluteParentName(Object element) + { + Object parent = getParent(element); + + if ((parent != null) && (parent instanceof IRemoteFile)) { + ISystemRemoteElementAdapter parentAdapter = SystemAdapterHelpers.getRemoteAdapter(parent); + + if (parentAdapter != null) { + return parentAdapter.getAbsoluteName(parent); + } + } + + return null; + } + + /** + * Return the subsystem factory id that owns this remote object + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getSubSystemFactoryId(Object element) + { + return null; + } + + /** + * Return a value for the type category property for this object + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getRemoteTypeCategory(Object element) + { + return null; + } + + /** + * Return a value for the type property for this object + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getRemoteType(Object element) + { + return null; + } + + /** + * Return a value for the subtype property for this object. + * Not all object types support a subtype, so returning null is ok. + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getRemoteSubType(Object element) + { + return null; + } + + /** + * Return a value for the sub-subtype property for this object. + * Not all object types support a sub-subtype, so returning null is ok. + * The value must not be translated, so that property pages registered via xml can subset by it. + */ + public String getRemoteSubSubType(Object element) + { + return null; + } + /** + * Return the source type of the selected object. Typically, this only makes sense for compilable + * source members. For non-compilable remote objects, this typically just returns null. + */ + public String getRemoteSourceType(Object element) + { + return null; + } + + /** + * Some view has updated the name or properties of this remote object. As a result, the + * remote object's contents need to be refreshed. You are given the old remote object that has + * old data, and you are given the new remote object that has the new data. For example, on a + * rename the old object still has the old name attribute while the new object has the new + * new attribute. + *

    + * This is called by viewers like SystemView in response to rename and property change events. + *

    + * @param oldElement the element that was found in the tree + * @param newElement the updated element that was passed in the REFRESH_REMOTE event + * @return true if you want the viewer that called this to refresh the children of this object, + * such as is needed on a rename of a folder, say. + */ + public boolean refreshRemoteObject(Object oldElement, Object newElement) + { + return false; + } + + /** + * Given a remote object, returns it remote parent object. Eg, given a file, return the folder + * it is contained in. + */ + public Object getRemoteParent(Shell shell, Object element) throws Exception + { + if (element instanceof IHostSearchResult) + { + return ((IHostSearchResult) element).getParent(); + } + return null; + } + + /** + * Given a remote object, return the unqualified names of the objects contained in that parent. This is + * used for testing for uniqueness on a rename operation, for example. Sometimes, it is not + * enough to just enumerate all the objects in the parent for this purpose, because duplicate + * names are allowed if the types are different, such as on iSeries. In this case return only + * the names which should be used to do name-uniqueness validation on a rename operation. + */ + public String[] getRemoteParentNamesInUse(Shell shell, Object element) throws Exception + { + return null; + } + + public IPropertyDescriptor[] getUniquePropertyDescriptors() + { + return new IPropertyDescriptor[0]; + } + + /** + * Returns the unique property descriptors for a search result + */ + protected org.eclipse.ui.views.properties.IPropertyDescriptor[] internalGetPropertyDescriptors() + { + if (_propertyDescriptors == null) + { + _propertyDescriptors = new PropertyDescriptor[2]; + int idx = -1; + + // path + _propertyDescriptors[++idx] = createSimplePropertyDescriptor(P_FILE_PATH, SystemViewResources.RESID_PROPERTY_FILE_PATH_LABEL, SystemViewResources.RESID_PROPERTY_FILE_PATH_TOOLTIP); + + // char start + _propertyDescriptors[++idx] = createSimplePropertyDescriptor(P_SEARCH_LINE, SystemViewResources.RESID_PROPERTY_SEARCH_LINE_LABEL, SystemViewResources.RESID_PROPERTY_SEARCH_LINE_TOOLTIP); + //_propertyDescriptors[++idx] = createSimplePropertyDescriptor(P_SEARCH_CHAR_END, SystemViewResources.RESID_PROPERTY_SEARCH_CHAR_END_ROOT); + } + return _propertyDescriptors; + } + + /** + * Returns the current collection of property descriptors. + * By default returns descriptors for name and type only. + * Override if desired. + * @return an array containing all descriptors. + */ + protected Object internalGetPropertyValue(Object key) + { + String name = (String) key; + if (propertySourceInput instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) propertySourceInput; + + if (name.equals(P_FILE_PATH)) + { + return output.getAbsolutePath(); + } + else if (name.equals(P_SEARCH_LINE)) + { + return new Integer(output.getLine()); + } + /* + else if (name.equals(P_SEARCH_CHAR_END)) + { + return new Integer(output.getCharEnd()); + } + */ + } + + return null; + } + + + /** + * Returns the associated image descriptor for a search result + */ + public ImageDescriptor getImageDescriptor(Object element) + { + if (element instanceof IHostSearchResult) + { + ImageDescriptor imageDescriptor = null; + imageDescriptor = SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_SEARCH_RESULT_ID); + + return imageDescriptor; + } + else + { // return some default + ImageDescriptor imageDescriptor = SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_BLANK_ID); + return imageDescriptor; + } + } + + /** + * Return true if we should show the delete action in the popup for the given element. + * If true, then canDelete will be called to decide whether to enable delete or not. + */ + public boolean showDelete(Object element) + { + return false; + } + /** + * Return true if this object is deletable by the user. If so, when selected, + * the Edit->Delete menu item will be enabled. + * By default, returns false. Override if your object is deletable. + */ + public boolean canDelete(Object element) + { + return false; + } + + // ------------------------------------------ + // METHODS TO SUPPORT COMMON REFRESH ACTION... + // ------------------------------------------ + /** + * Return true if we should show the refresh action in the popup for the given element. + */ + public boolean showRefresh(Object element) + { + return false; + } + + // ------------------------------------------------------------ + // METHODS TO SUPPORT COMMON OPEN-IN-NEW-PERSPECTIVE ACTIONS... + // ------------------------------------------------------------ + /** + * Return true if we should show the refresh action in the popup for the given element. + */ + public boolean showOpenViewActions(Object element) + { + return false; + } + + // ------------------------------------------ + // METHODS TO SUPPORT COMMON RENAME ACTION... + // ------------------------------------------ + + /** + * Return true if we should show the rename action in the popup for the given element. + * If true, then canRename will be called to decide whether to enable rename or not. + */ + public boolean showRename(Object element) + { + return false; + } + /** + * Return true if this object is renamable by the user. If so, when selected, + * the Rename popup menu item will be enabled. + * By default, returns false. Override if your object is renamable. + */ + public boolean canRename(Object element) + { + return false; + } + + /** + * Perform the rename action. By default does nothing. Override if your object is renamable. + * Return true if this was successful. Return false if it failed and you issued a msg. + * Throw an exception if it failed and you want to use the generic msg. + */ + public boolean doRename(Shell shell, Object element, String name) throws Exception + { + return false; + } + + // Drag and drop + + /** + * Indicates whether the specified object can have another object copied to it + * @param element the object to copy to + * @return whether this object can be copied to or not + */ + public boolean canDrop(Object element) + { + + return false; + } + + /** + * Indicates whether the specified object can be copied + * @param element the object to copy + */ + public boolean canDrag(Object element) + { + if (element instanceof IHostSearchResult) + { + return true; + } + + return false; + } + + /** + * Copy the specified remote output object. This method returns a string representing + * the text of the remote output; + * + * @param element the output to copy + * @param sameSystemType not applicable for remote output + * @param monitor the progress monitor + */ + public Object doDrag(Object element, boolean sameSystemType, IProgressMonitor monitor) + { + if (element instanceof List) + { + List resultSet = new ArrayList(); + List set = (List)element; + for (int i = 0; i < set.size(); i++) + { + resultSet.add(getText(set.get(i))); + } + return resultSet; + } + else + { + return getText(element); + } + } + + /** + * Return true if it is valid for the src object to be dropped in the target + * @param src the object to drop + * @param target the object which src is dropped in + * @param sameSystem whether this is the same system + * @return whether this is a valid operation + */ + public boolean validateDrop(Object src, Object target, boolean sameSystem) + { + return false; + } + + /** + * Perform a copy via drag and drop. + * @param src the object to be copied. If the target and source are not on the same system, then this is a + * temporary object produced by the doDrag. + * @param target the object to be copied to. + * @param sameSystem an indication whether the target and source reside on the same type of system + * @param indicates the type of source + * @param monitor the progress monitor + * @return an indication whether the operation was successful or not. + */ + public Object doDrop(Object src, Object target, boolean sameSystemType, boolean sameSystem, int srcType, IProgressMonitor monitor) + { + IRemoteFile folder = outputToFile((IHostSearchResult) target); + if (folder != null) + { + ISystemDragDropAdapter adapter = (ISystemDragDropAdapter) ((IAdaptable) folder).getAdapter(ISystemDragDropAdapter.class); + return adapter.doDrop(src, folder, sameSystemType, sameSystem, srcType, monitor); + } + return null; + } + + /** + * Indicates whether the search result can be opened in an editor + */ + public boolean canEdit(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) element; + IRemoteFile file = outputToFile(output); + if (file != null && file.isFile()) + { + return true; + } + } + return false; + } + + /** + * Returns the associated remote editable object for this search result + */ + public ISystemEditableRemoteObject getEditableRemoteObject(Object element) + { + if (element instanceof IHostSearchResult) + { + IHostSearchResult output = (IHostSearchResult) element; + IRemoteFile file = outputToFile(output); + if (file != null && file.isFile()) + { + return new SystemEditableRemoteFile(file); + } + } + return null; + } + + /** + * Return a filter string that corresponds to this object. + * @param object the object to obtain a filter string for + * @return the corresponding filter string if applicable + */ + public String getFilterStringFor(Object object) + { + return null; + } + + /** + * Returns false. + * @see org.eclipse.rse.ui.view.ISystemRemoteElementAdapter#supportsUserDefinedActions(java.lang.Object) + */ + public boolean supportsUserDefinedActions(Object object) { + return false; + } + + + + /** + * Returns the current value for the named property. + * + * @param property the name or key of the property as named by its property descriptor + * @param formatted indication of whether to return the value in formatted or raw form + * @return the current value of the given property + */ + public Object getPropertyValue(Object property, boolean formatted) + { + String name = (String) property; + if (propertySourceInput instanceof IRemoteCommandShell) + { + IRemoteCommandShell cmdShell = (IRemoteCommandShell) propertySourceInput; + if (name.equals(ISystemPropertyConstants.P_SHELL_STATUS)) + { + if (cmdShell.isActive()) + { + return SystemViewResources.RESID_PROPERTY_SHELL_STATUS_ACTIVE_VALUE; + } + else + { + return SystemViewResources.RESID_PROPERTY_SHELL_STATUS_INACTIVE_VALUE; + } + } + else if (name.equals(ISystemPropertyConstants.P_SHELL_CONTEXT)) + { + Object context = cmdShell.getContext(); + if (context instanceof IRemoteFile) + { + IRemoteFile cwd = (IRemoteFile)context; + if (cwd != null) + { + return cwd.getAbsolutePath(); + } + } + else + { + return context; + } + } + } + return ""; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultSetAdapter.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultSetAdapter.java new file mode 100644 index 00000000000..2eac1ba71c0 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewRemoteSearchResultSetAdapter.java @@ -0,0 +1,355 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.search.IHostSearchResultSet; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteSearchResult; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteSearchResultsContentsType; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemMenuManager; +import org.eclipse.rse.ui.view.AbstractSystemViewAdapter; +import org.eclipse.rse.ui.view.ISystemEditableRemoteObject; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemRemoveElementAdapter; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.views.properties.IPropertyDescriptor; + + +/** + * Adapter for a search result set. + */ +public class SystemViewRemoteSearchResultSetAdapter extends AbstractSystemViewAdapter implements ISystemRemoteElementAdapter, ISystemRemoveElementAdapter +{ + + + public SystemViewRemoteSearchResultSetAdapter() + { + } + + /** + * No actions are provided on a search results container + */ + public void addActions(SystemMenuManager menu, IStructuredSelection selection, Shell shell, String menuGroup) + { + } + + /** + * Returns false + */ + public boolean canEdit(Object obj) + { + return false; + } + + /** + * Returns null since a search results container can't be edited + */ + public ISystemEditableRemoteObject getEditableRemoteObject(Object obj) + { + return null; + } + + /** + * Returns the associated icon for a search handle + */ + public ImageDescriptor getImageDescriptor(Object element) + { + ImageDescriptor imageDescriptor= SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_SEARCH_RESULT_ID); + return imageDescriptor; + } + + /** + * Returns null since a search handle has no parent + */ + public Object getParent(Object element) + { + return null; + } + + /** + * Returns the display text for a search handle. The display text indicates the search string as well as + * whether the operation is in progress on not. + */ + public String getText(Object element) { + + if (element instanceof IHostSearchResultSet) { + + IHostSearchResultSet set = (IHostSearchResultSet)element; + String name = set.getName(); + SystemMessage msg = null; + + if (set.isRunning()) { + msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_OPERATION_RUNNING); + } + else if (set.isFinished()) { + msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_OPERATION_FINISHED); + } + else if (set.isCancelled()) { + msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_OPERTION_STOPPED); + } + else if (set.isDisconnected()) { + msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_OPERATION_DISCONNECTED); + } + + msg.makeSubstitution(name); + return msg.getLevelOneText(); + } + + return null; + } + + /** + * Returns the type property of a search. + */ + public String getType(Object element){ + return null; + } + + /** + * Returns the search results for the given search handle + */ + public Object[] getChildren(Object element) { + + if (element instanceof IHostSearchResultSet) { + IHostSearchResultSet output = (IHostSearchResultSet)element; + return output.getAllResults(); + } + + return null; + } + + /** + * Returns true if it has children, otherwise returns false. + */ + public boolean hasChildren(Object element) { + + if (element instanceof IHostSearchResultSet) { + int num = ((IHostSearchResultSet)element).getNumOfResults(); + return num > 0; + } + + return false; + } + + /** + * Returns false since a search handle can't be edited + */ + public boolean handleDoubleClick(Object element) { + return false; + } + + /** + * Returns the associated file subsystem for this search operation + */ + public ISubSystem getSubSystem(Object element) { + return null; + } + + + public String getAbsoluteName(Object element) + { + return null; + } + + public String getAbsoluteParentName(Object element) + { + return null; + } + + public String getSubSystemFactoryId(Object element) + { + return null; + } + + public String getRemoteTypeCategory(Object element) + { + return null; + } + + public String getRemoteType(Object element) + { + return null; + } + + public String getRemoteSubType(Object element) + { + return null; + } + + + public String getRemoteSubSubType(Object element) + { + return null; + } + + /** + * Return the source type of the selected object. Typically, this only makes sense for compilable + * source members. For non-compilable remote objects, this typically just returns null. + */ + public String getRemoteSourceType(Object element) + { + return null; + } + + public boolean refreshRemoteObject(Object oldElement, Object newElement) + { + return false; + } + + /** + * Given a remote object, returns it remote parent object. Eg, given a file, return the folder + * it is contained in. + * + */ + public Object getRemoteParent(Shell shell, Object element) throws Exception + { + return null; + } + + /** + * Given a remote object, return the unqualified names of the objects contained in that parent. This is + * used for testing for uniqueness on a rename operation, for example. Sometimes, it is not + * enough to just enumerate all the objects in the parent for this purpose, because duplicate + * names are allowed if the types are different, such as on iSeries. In this case return only + * the names which should be used to do name-uniqueness validation on a rename operation. + */ + public String[] getRemoteParentNamesInUse(Shell shell, Object element) throws Exception + { + return null; + } + + /** + * Return our unique property descriptors + */ + protected IPropertyDescriptor[] internalGetPropertyDescriptors() + { + return new IPropertyDescriptor[0]; + } + + /** + * Return our unique property values + */ + protected Object internalGetPropertyValue(Object key) + { + return null; + } + + /** + * Return a filter string that corresponds to this object. + * @param object the object to obtain a filter string for + * @return the corresponding filter string if applicable + */ + public String getFilterStringFor(Object object) + { + return null; + } + + /** + * @see org.eclipse.rse.ui.view.ISystemViewElementAdapter#canDelete(java.lang.Object) + */ + public boolean canDelete(Object element) { + return false; + } + + /** + * @see org.eclipse.rse.ui.view.ISystemViewElementAdapter#showDelete(java.lang.Object) + */ + public boolean showDelete(Object element) { + return false; + } + + /** + * @see org.eclipse.rse.ui.view.ISystemRemoveElementAdapter#remove(java.lang.Object, java.lang.Object) + */ + public boolean remove(Object element, Object child) { + + if (element instanceof IHostSearchResultSet) { + IHostSearchResultSet set = (IHostSearchResultSet)element; + + // if the child is an IRemoteFile + if (child instanceof IRemoteFile) { + set.removeResult(child); + return true; + } + // if child is a result leaf, remove it from its parent + else if (child instanceof IRemoteSearchResult) { + IRemoteSearchResult result = (IRemoteSearchResult)child; + IRemoteFile parent = (IRemoteFile)(result.getParent()); + + // get contents of parent + Object[] contents = parent.getContents(RemoteSearchResultsContentsType.getInstance(), result.getMatchingSearchString().toString()); + List contentsList = new ArrayList(); + + // go through array and add all entries to list that do not match the result + for (int i = 0; i < contents.length; i++) { + + if (contents[i] != result) { + contentsList.add(contents[i]); + } + } + + // now set the contents of the parent with the result removed + parent.setContents(RemoteSearchResultsContentsType.getInstance(), result.getMatchingSearchString().toString(), contentsList.toArray()); + + return true; + } + else { + return false; + } + } + else { + return false; + } + } + + /** + * @see org.eclipse.rse.ui.view.ISystemRemoveElementAdapter#removeAllChildren(java.lang.Object) + */ + public boolean removeAllChildren(Object element) { + + if (element == null) { + return false; + } + + if (element instanceof IHostSearchResultSet) { + IHostSearchResultSet set = (IHostSearchResultSet)element; + set.removeAllResults(); + return true; + } + else { + return false; + } + } + + + /** + * Returns false. + * @see org.eclipse.rse.ui.view.ISystemRemoteElementAdapter#supportsUserDefinedActions(java.lang.Object) + */ + public boolean supportsUserDefinedActions(Object object) { + return false; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultAdapterFactory.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultAdapterFactory.java new file mode 100644 index 00000000000..0f24d5070f0 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultAdapterFactory.java @@ -0,0 +1,79 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; + +import org.eclipse.core.runtime.IAdapterFactory; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.services.search.IHostSearchResult; +import org.eclipse.rse.ui.view.ISystemDragDropAdapter; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.ui.IActionFilter; +import org.eclipse.ui.model.IWorkbenchAdapter; +import org.eclipse.ui.views.properties.IPropertySource; + + + +/** + * This factory maps requests for an adapter object from a given + * element object. A search result adapter factory maps a search + * result object to a search result adapter. + */ +public class SystemViewSearchResultAdapterFactory implements IAdapterFactory +{ + private SystemViewRemoteSearchResultAdapter searchResultAdapter = new SystemViewRemoteSearchResultAdapter(); + + + /** + * @see IAdapterFactory#getAdapterList() + */ + public Class[] getAdapterList() + { + return new Class[] {ISystemViewElementAdapter.class, ISystemDragDropAdapter.class, ISystemRemoteElementAdapter.class, IPropertySource.class, IWorkbenchAdapter.class, IActionFilter.class}; + } + /** + * Called by our plugin's startup method to register our adaptable object types + * with the platform. We prefer to do it here to isolate/encapsulate all factory + * logic in this one place. + */ + public void registerWithManager(IAdapterManager manager) + { + manager.registerAdapters(this, IHostSearchResult.class); + } + /** + * @see IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) + */ + public Object getAdapter(Object adaptableObject, Class adapterType) + { + Object adapter = null; + if (adaptableObject instanceof IHostSearchResult) + adapter = searchResultAdapter; + + if ((adapter != null) && (adapterType == IPropertySource.class)) + { + ((ISystemViewElementAdapter)adapter).setPropertySourceInput(adaptableObject); + } + else if (adapter == null) + { + SystemBasePlugin.logWarning("No adapter found for object of type: " + adaptableObject.getClass().getName()); + } + return adapter; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultSetAdapterFactory.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultSetAdapterFactory.java new file mode 100644 index 00000000000..882388b4128 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/view/SystemViewSearchResultSetAdapterFactory.java @@ -0,0 +1,75 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.view; +import org.eclipse.core.runtime.IAdapterFactory; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.services.search.IHostSearchResultSet; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.ISystemViewElementAdapter; +import org.eclipse.ui.IActionFilter; +import org.eclipse.ui.model.IWorkbenchAdapter; +import org.eclipse.ui.views.properties.IPropertySource; + + +/** + * This factory maps requests for an adapter object from a given + * element object. A search results adapter factory maps a search + * results object to a search results adapter. + */ +public class SystemViewSearchResultSetAdapterFactory implements IAdapterFactory +{ + private SystemViewRemoteSearchResultSetAdapter outputAdapter = new SystemViewRemoteSearchResultSetAdapter(); + + /** + * @see IAdapterFactory#getAdapterList() + */ + public Class[] getAdapterList() + { + return new Class[] {ISystemViewElementAdapter.class, ISystemRemoteElementAdapter.class, IPropertySource.class, IWorkbenchAdapter.class, IActionFilter.class}; + } + /** + * Called by our plugin's startup method to register our adaptable object types + * with the platform. We prefer to do it here to isolate/encapsulate all factory + * logic in this one place. + */ + public void registerWithManager(IAdapterManager manager) + { + manager.registerAdapters(this, IHostSearchResultSet.class); + } + /** + * @see IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class) + */ + public Object getAdapter(Object adaptableObject, Class adapterType) + { + Object adapter = null; + + if (adaptableObject instanceof IHostSearchResultSet) { + adapter = outputAdapter; + } + + if ((adapter != null) && (adapterType == IPropertySource.class)) + { + ((ISystemViewElementAdapter)adapter).setPropertySourceInput(adaptableObject); + } + else if (adapter == null) + { + SystemBasePlugin.logWarning("No adapter found for object of type: " + adaptableObject.getClass().getName()); + } + return adapter; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/ISystemRemoteFolderBrowseCompleteListener.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/ISystemRemoteFolderBrowseCompleteListener.java new file mode 100644 index 00000000000..5170cf635b4 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/ISystemRemoteFolderBrowseCompleteListener.java @@ -0,0 +1,34 @@ +/******************************************************************************** + * Copyright (c) 2003, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; + + +/** + * Interface for listeners interested in being notified whenever + * the browse button in SystemRemoteFolderCombo is run. + */ +public interface ISystemRemoteFolderBrowseCompleteListener { + + /** + * Notifies that the given file was selected from the browse dialog. Note that the file will + * be null if the user cancelled from the browse dialog. + * @param remoteFile the remote file that was selected, or null if the user cancelled + * from the browse dialog. + */ + public void fileSelected(IRemoteFile remoteFile); +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemEnterOrSelectRemoteFileForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemEnterOrSelectRemoteFileForm.java new file mode 100644 index 00000000000..c3c555485e1 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemEnterOrSelectRemoteFileForm.java @@ -0,0 +1,226 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; + +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.validators.ValidatorFileName; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + +public class SystemEnterOrSelectRemoteFileForm extends SystemSelectRemoteFileOrFolderForm { + + // text field for file name + protected Text fileNameText; + + // initial file name + protected String fileName, initialFileName; + + // file name validator + protected ValidatorFileName validator; + + /** + * Constructor for form to enter or select a file. + * @param msgLine A GUI widget capable of writing error messages to. + * @param caller The wizardpage or dialog hosting this form. + * @param fileMode true if in select-file mode, false if in select-folder mode + */ + public SystemEnterOrSelectRemoteFileForm(ISystemMessageLine msgLine, Object caller, boolean fileMode) { + super(msgLine, caller, fileMode); + validator = new ValidatorFileName(); + initialFileName = ""; + fileName = initialFileName; + } + + /** + * Calls super method and creates the text field for file name. + * @see org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm#createContents(org.eclipse.swt.widgets.Shell, org.eclipse.swt.widgets.Composite) + */ + public Control createContents(Shell shell, Composite parent) { + Control control = super.createContents(shell, parent); + + Composite composite = SystemWidgetHelpers.createComposite(parent, 2); + + // file name text field + fileNameText = SystemWidgetHelpers.createLabeledTextField( + composite, null, FileResources.RESID_NEWFILE_NAME_LABEL, FileResources.RESID_NEWFILE_NAME_TOOLTIP); + + // listen for file name modifications + fileNameText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + fileName = fileNameText.getText(); + setPageComplete(); + } + }); + + // set file name + if (fileName != null) { + fileNameText.setText(fileName); + } + + return control; + } + + /** + * @see org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm#verify() + */ + public boolean verify() { + + boolean ok = super.verify(); + + if (ok) { + + IRemoteFile file = (IRemoteFile)getSelectedObject(); + IRemoteFile saveasFile = null; + + try { + saveasFile = file.getParentRemoteFileSubSystem().getRemoteFileObject(file, fileName); + } + catch (Exception e) { + } + + if (saveasFile != null && saveasFile.exists()) { + + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_UPLOAD_FILE_EXISTS); + msg.makeSubstitution(fileName); + SystemMessageDialog dlg = new SystemMessageDialog(getShell(), msg); + ok = dlg.openQuestionNoException(); + } + } + + return ok; + } + + /** + * @see org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm#isPageComplete() + */ + public boolean isPageComplete() { + + SystemMessage errMsg = null; + + if (fileName != null) { + errMsg = validator.validate(fileName); + } + + if (errMsg != null) { + setErrorMessage(errMsg); + return false; + } + else { + clearErrorMessage(); + } + + return fileNameText != null && fileNameText.getText().length() > 0 && super.isPageComplete(); + } + + /** + * @see org.eclipse.rse.files.ui.widgets.SystemSelectRemoteFileOrFolderForm#setPreSelection(org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile) + */ + public void setPreSelection(IRemoteFile selection) { + + // if preselect a directory, just call super + if (selection.isDirectory()) { + super.setPreSelection(selection); + } + // otherwise, if it's a file, select the parent and set the file name + else if (selection.isFile()) { + IRemoteFile parentFile = selection.getParentRemoteFile(); + + if (parentFile.isDirectory()) { + super.setPreSelection(parentFile); + } + + initialFileName = parentFile.getName(); + fileName = initialFileName; + } + } + + /** + * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent e) { + super.selectionChanged(e); + + Object selectedObject = getFirstSelection(e.getSelection()); + + if (selectedObject != null && selectedObject instanceof IRemoteFile) { + + IRemoteFile remoteFile = (IRemoteFile)selectedObject; + + ISystemRemoteElementAdapter remoteAdapter = getRemoteAdapter(selectedObject); + + if ((remoteAdapter != null)) { + + if (fileNameText != null) { + + // simulate the parent file being selected... + Object parentFile = tree.getSelectedParent(); + + if (remoteFile.isFile()) { + fileName = remoteAdapter.getName(selectedObject); + fileNameText.setText(fileName); + } + else { + fileName = initialFileName; + fileNameText.setText(fileName); + parentFile = remoteFile; + } + + remoteAdapter = getRemoteAdapter(parentFile); + + if (remoteAdapter != null) { + String fullPath = remoteAdapter.getAbsoluteName(parentFile); + setNameText(fullPath); + outputObjects = new Object[] { parentFile }; + setPageComplete(); + } + } + } + } + } + + /** + * Returns the remote element adapter. + * @param o the remote element. + * @return the remote element adapter. + */ + protected ISystemRemoteElementAdapter getRemoteAdapter(Object o) { + return SystemAdapterHelpers.getRemoteAdapter(o); + } + + /** + * Returns the file name. + * @return the file name. + */ + public String getFileName() { + return fileName; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemFileWidgetHelpers.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemFileWidgetHelpers.java new file mode 100644 index 00000000000..ba301d222bc --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemFileWidgetHelpers.java @@ -0,0 +1,121 @@ +/******************************************************************************** + * Copyright (c) 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; + +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; + +/** + * Static methods that can be used when writing SWT GUI code. + * They simply make it more productive. + */ +public class SystemFileWidgetHelpers extends SystemWidgetHelpers +{ + + + /** + * Creates a new remote system folder combobox instance and sets the default + * layout data, with tooltip text. + *

    + * Assign the listener to the passed in implementer of Listener. + *

    + * A remote system folder combobox is one that mimics the local folder selection combobox, but + * works with remote file systems instead. It has a label, a historical dropdown, and a browse button. + *

    + * @param parent composite to put the combo into. + * @param listener object to listen for selection events. Can be null. + * If you want to listen for modify events, call addListener(SWT.Modify,this) on your own. + * @param historyKey The key with which to remember/restore the history for this combo. Pass null to use the overall default. + * @param horizontalSpan number of columns this should span + * @param readOnly true if the combo is to be readonly + */ + public static SystemRemoteFolderCombo createFolderCombo(Composite parent, SelectionListener listener, int horizontalSpan, String historyKey, boolean readOnly) { + if (historyKey == null) + historyKey = ISystemPreferencesConstants.HISTORY_FOLDER; + SystemRemoteFolderCombo combo = new SystemRemoteFolderCombo(parent, SWT.NULL, historyKey, readOnly); + if (listener != null) + combo.addSelectionListener(listener); + boolean hasGridData = (combo.getLayoutData() != null) && (combo.getLayoutData() instanceof GridData); + //System.out.println("history directory griddata non-null? " + hasGridData); + int minwidth = 250; + if (!hasGridData) { + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + data.widthHint = minwidth; + data.verticalAlignment = GridData.CENTER; + data.grabExcessVerticalSpace = false; + data.horizontalSpan = horizontalSpan; + combo.setLayoutData(data); + } else { + ((GridData) combo.getLayoutData()).horizontalSpan = horizontalSpan; + ((GridData) combo.getLayoutData()).horizontalAlignment = GridData.FILL; + ((GridData) combo.getLayoutData()).grabExcessHorizontalSpace = true; + ((GridData) combo.getLayoutData()).widthHint = minwidth; + } + return combo; + } + + /** + * Creates a new remote system directory combobox instance and sets the default + * layout data, with tooltip text. Each remote directory is qualified by its connection name. + * These combos are always readonly. + *

    + * Assign the listener to the passed in implementer of Listener. + *

    + * A remote system qualified-directory combobox is one that mimics the local directory selection combobox, but + * works with remote file systems instead. It has a label, a historical dropdown, and a browse button. + *

    + * @param parent composite to put the combo into. + * @param listener object to listen for selection events. Can be null. + * If you want to listen for modify events, call addListener(SWT.Modify,this) on your own. + * @param historyKey The key with which to remember/restore the history for this combo. Pass null to use the overall default. + * @param horizontalSpan number of columns this should span + */ + public static SystemQualifiedRemoteFolderCombo createQualifiedDirectoryCombo(Composite parent, SelectionListener listener, int horizontalSpan, String historyKey) { + if (historyKey == null) + historyKey = ISystemPreferencesConstants.HISTORY_QUALIFIED_FOLDER; + SystemQualifiedRemoteFolderCombo combo = new SystemQualifiedRemoteFolderCombo(parent, SWT.NULL, historyKey); + if (listener != null) + combo.addSelectionListener(listener); + boolean hasGridData = (combo.getLayoutData() != null) && (combo.getLayoutData() instanceof GridData); + //System.out.println("history directory griddata non-null? " + hasGridData); + int minwidth = 250; + if (!hasGridData) { + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + data.widthHint = minwidth; + data.verticalAlignment = GridData.CENTER; + data.grabExcessVerticalSpace = false; + data.horizontalSpan = horizontalSpan; + combo.setLayoutData(data); + } else { + ((GridData) combo.getLayoutData()).horizontalSpan = horizontalSpan; + ((GridData) combo.getLayoutData()).horizontalAlignment = GridData.FILL; + ((GridData) combo.getLayoutData()).grabExcessHorizontalSpace = true; + ((GridData) combo.getLayoutData()).widthHint = minwidth; + } + return combo; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemQualifiedRemoteFolderCombo.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemQualifiedRemoteFolderCombo.java new file mode 100644 index 00000000000..cccc0dbc5be --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemQualifiedRemoteFolderCombo.java @@ -0,0 +1,773 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import java.util.Hashtable; +import java.util.ResourceBundle; + +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.SystemPreferencesManager; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.actions.SystemSelectRemoteFolderAction; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemProfile; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.widgets.ISystemCombo; +import org.eclipse.rse.ui.widgets.SystemHistoryCombo; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + + +/** + * This re-usable widget is for selecting a new or previously specified + * folder path within a given connection. + *

    + * The dropdown is historical and contains a folder path qualified by a connection name. + * It is readonly ... the user must use the browse button. + *

    + * The composite is layed as follows: + * + * Folder: conn\dir1_____v Browse... + * + *

    + * The browse button lists only connections that are of the specified subsystem factory. + * It also by default has a New Connection... prompting object for creating new connections, but this can be + * turned off. + *

    + * To get the current folder object selected, use getFolder(). + *

    + * To listen for changes, use addSelectionListener(). + */ +public class SystemQualifiedRemoteFolderCombo extends Composite + implements ISystemMessages, ISystemCombo +{ + public static final char CONNECTION_DELIMITER = IRemoteFile.CONNECTION_DELIMITER; + private Label folderLabel = null; + private SystemHistoryCombo folderCombo = null; + private Button browseButton = null; + //private RemoteFileSubSystem subsystem = null; + //private RemoteFileSubSystemFactory subsystemFactory = null; + //private String subsystemFactoryID = null; + //private IRemoteFile[] folders = null; + private Hashtable resolvedFolders = new Hashtable(); + //private String[] folderStrings = null; + private String[] systemTypes; + private boolean readOnly = true; + private boolean showNewPrompt = true; + private SystemSelectRemoteFolderAction browseAction = null; + //private static final int DEFAULT_COMBO_WIDTH = 300; + //private static final int DEFAULT_BUTTON_WIDTH = 80; + + /** + * Constructor. + * Requires a history key used to store/restore the dropdown history for this. Pass null to use + * the overall default (ISystemPreferencesConstants.HISTORY_FOLDER). + * By default, this allows users to select with any connection that has subsystems that implement + * RemoteFileSubSystem. To restrict it to connections of a particular system type, say, call + * setSystemType. + * @param parent Parent composite + * @param style SWT style flags for overall composite widget + * @param historyKey A string identifying the key into the user preferences where this combo's history will be stored. + * @see #setSystemType(String) + */ + public SystemQualifiedRemoteFolderCombo(Composite parent, int style, String historyKey) + { + super(parent, style); + prepareComposite(3); + folderLabel = SystemWidgetHelpers.createLabel(this,SystemFileResources.WIDGET_FOLDER_LABEL, SystemFileResources.WIDGET_FOLDER_TOOLTIP); + if (historyKey == null) + historyKey = ISystemPreferencesConstants.HISTORY_QUALIFIED_FOLDER; + folderCombo = SystemWidgetHelpers.createHistoryCombo(this,null,historyKey,readOnly,SystemFileResources.WIDGET_FOLDER_TOOLTIP); + Object folderData = folderCombo.getLayoutData(); + if (folderData instanceof GridData) + ((GridData)folderData).widthHint = 200; + browseButton = createPushButton(this,SystemFileResources.WIDGET_BROWSE_LABEL); + addOurButtonSelectionListener(); + //scrubHistory(); this is too intensive as it starts all kinds of servers and stuff unnecessarily. + } + + /** + * Set auto-uppercase. When enabled, all non-quoted values are uppercases when appropriate. + * This has no effect in readonly mode, which this combo is, so in fact this is ineffective! + * We include it in case we allow editing in the future, and because it is in the ISystemCombo + * interface we implement. + */ + public void setAutoUpperCase(boolean enable) + { + folderCombo.setAutoUpperCase(enable); + } + + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + this.systemTypes = systemTypes; + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + //System.out.println("SYSTEM TYPES SET TO "+systemType+" IN SYSQUALRMTFLDRCMBO"); + } + + /** + * Specify if the "New Connection..." object for creating connections should be shown when the user selects + * the Browse... button to select a remote folder. The default is true. + */ + public void setShowNewConnectionPrompt(boolean show) + { + this.showNewPrompt = show; + if (browseAction != null) + browseAction.setShowNewConnectionPrompt(show); + } + + /** + * Return the combo box history widget + */ + public SystemHistoryCombo getFolderCombo() + { + return folderCombo; + } + /** + * Return the combo box widget + */ + public SystemHistoryCombo getHistoryCombo() + { + return folderCombo; + } + /** + * Return the raw combo box widget + */ + public Combo getCombo() + { + return folderCombo.getCombo(); + } + + /** + * Set the width hint for this whole composite + * Default is computed from the child widgets + */ + public void setWidthHint(int widthHint) + { + // after much research it was decided that it was the wrong thing to do to + // explicitly set the widthHint of a child widget without our composite, as + // that could end up being a bigger number than the composites widthHint itself + // if the caller set its it directly. + // Rather, we just set the overall composite width and specify the combo child + // widget is to grab all the space within that which the little button does not use. + ((GridData)getLayoutData()).widthHint = widthHint; + } + + /** + * Return the browse button widget + */ + public Button getBrowseButton() + { + return browseButton; + } + + /** + * Set the folders in the combo field. + * History is updated. + * @param folders Array of IRemoteFile objects ... each is a remote folder + */ + public void setFolders(IRemoteFile[] folders) + { + if (folders == null) + { + //folderStrings = null; + folderCombo.setItems(null); + return; + } + String[] folderStrings = new String[folders.length]; + for (int idx=0; idx -1) + { + folderCombo.getCombo().remove(idx); + updateHistory(); + } + } + + /** + * Get the items in the combo field as an array of strings. + * @return Array of String objects + */ + public String[] getItems() + { + return folderCombo.getItems(); + } + + /** + * Get the index of a given folder in the current list for this combo. + * Returns -1 if it is not in the list. + */ + public int getFolderIndex(IRemoteFile folder) + { + int match = -1; + String[] folderStrings = folderCombo.getItems(); + if ( (folderStrings == null) || (folderStrings.length==0) ) + return match; + IHost conn = folder.getSystemConnection(); + String fulldir = folder.getAbsolutePathPlusConnection(); + for (int idx=0; (idx + * Since it is possible the selected item is no longer valid, this will throw an + * exception if the profile or connection does not exist or the user cancels the + * connecting action. The message in the exception is translated and displayable. + */ + public IRemoteFile getFolder() + throws Exception + { + String fileString = folderCombo.getText().trim(); + //System.out.println("selected idx = " + idx); + if (fileString.length() == 0) + return null; + else + { + IRemoteFile fileObj = (IRemoteFile)resolvedFolders.get(fileString); + if (fileObj == null) + { + fileObj = convertToRemoteFile(fileString); + if (fileObj != null) + resolvedFolders.put(fileString, fileObj); + } + return fileObj; + } + } + /** + * Query the folder combo field's current contents and return the connection part of + * it as a SystemConnection object. + *

    + * Will return null if either there is no contents currently or there is no such system! + */ + public IHost getSystemConnection() + { + String fileString = folderCombo.getText().trim(); + if (fileString.length() == 0) + return null; + String profileName = extractProfileName(fileString); + String connName = extractConnectionName(fileString); + if ((profileName == null) || (connName == null)) + return null; + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + ISystemProfile profile = sr.getSystemProfile(profileName); + if (profile == null) + return null; + IHost conn = SystemPlugin.getTheSystemRegistry().getHost(profile,connName); + return conn; + } + + /** + * Disable/Enable all the child controls. + */ + public void setEnabled(boolean enabled) + { + folderCombo.setEnabled(enabled); + browseButton.setEnabled(enabled); + } + /** + * Set the tooltip text for the folder combo field + */ + public void setToolTipText(String tip) + { + folderLabel.setToolTipText(tip); + folderCombo.setToolTipText(tip); + } + /** + * Set the tooltip text for the browse button + */ + public void setBrowseButtonToolTipText(String tip) + { + browseButton.setToolTipText(tip); + } + /** + * Same as {@link #setBrowseButtonToolTipText(String)} + */ + public void setButtonToolTipText(String tip) + { + setBrowseButtonToolTipText(tip); + } + + /** + * Set the folder combo field's text limit + */ + public void setTextLimit(int limit) + { + folderCombo.setTextLimit(limit); + } + /** + * Set the focus to the folder combo field + */ + public boolean setFocus() + { + return folderCombo.setFocus(); + } + /** + * Set the focus to the browse button + */ + public void setBrowseButtonFocus() + { + browseButton.setFocus(); + } + + /** + * Register a listener interested in an item is selected in the combo box + * @see #removeSelectionListener(SelectionListener) + */ + public void addSelectionListener(SelectionListener listener) + { + folderCombo.addSelectionListener(listener); + } + /** + * Remove a previously set combo box selection listener. + * @see #addSelectionListener(SelectionListener) + */ + public void removeSelectionListener(SelectionListener listener) + { + folderCombo.removeSelectionListener(listener); + } + /** + * Register a listener interested in when the browse button is selected + * @see #removeBrowseButtonSelectionListener(SelectionListener) + */ + public void addBrowseButtonSelectionListener(SelectionListener listener) + { + browseButton.addSelectionListener(listener); + } + /** + * Remove a previously set browse button selection listener. + * @see #addBrowseButtonSelectionListener(SelectionListener) + */ + public void removeBrowseButtonSelectionListener(SelectionListener listener) + { + browseButton.removeSelectionListener(listener); + } + + /** + * Register a listener interested in entry field modify events + * @see #removeModifyListener(ModifyListener) + */ + public void addModifyListener(ModifyListener listener) + { + folderCombo.addModifyListener(listener); + } + /** + * Remove a previously set entry field listener. + * @see #addModifyListener(ModifyListener) + */ + public void removeModifyListener(ModifyListener listener) + { + folderCombo.removeModifyListener(listener); + } + + /** + * Return the current history for the folder combo box + */ + public static String[] getHistory() + { + return SystemPreferencesManager.getPreferencesManager().getFolderHistory(); + } + + /** + * Update the history with current entry field setting. + *

    + * This is called automatically for you whenever this list is changed. + */ + public void updateHistory() + { + folderCombo.updateHistory(); + } + + // --------------------------------------------------------- + // METHODS TO CONVERT FROM STRINGS TO IREMOTEFILE OBJECTS... + // --------------------------------------------------------- + /** + * Given a qualified folder name, return an IRemoteFile object representing it. + * Will return null if there is no connection of the given name, or that connection + * does not have a subsystem that implements RemoteFileSubSystem. + *

    + * Note that if the connection contains multiple subsystems that implement RemoteFileSubSystem, + * or that come from a subsystem factory of the given subsystem factory ID, + * the first such subsystem is chosen. + */ + public IRemoteFile convertToRemoteFile(String qualifiedFolder) + throws Exception + { + SystemMessage msg = null; + // parse string in constituent profile, connection and folder parts... + String profileName = extractProfileName(qualifiedFolder); + String connName = extractConnectionName(qualifiedFolder); + String dirName = extractFolder(qualifiedFolder); + if ((profileName == null) || (connName == null) || (dirName == null)) + return null; + + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + + // turn profile name into profile object... + ISystemProfile profile = sr.getSystemProfile(profileName); + if (profile == null) + { + msg = SystemPlugin.getPluginMessage(MSG_ERROR_PROFILE_NOTFOUND); + msg.makeSubstitution(profileName); + throw new Exception(msg.getLevelOneText()); + } + + // turn connection name into connection object... + IHost conn = SystemPlugin.getTheSystemRegistry().getHost(profile,connName); + if (conn == null) + { + msg = SystemPlugin.getPluginMessage(MSG_ERROR_CONNECTION_NOTFOUND); + msg.makeSubstitution(connName); + throw new Exception(msg.getLevelOneText()); + } + + // turn folder name into folder object... + IRemoteFile remoteFolder = null; + ISubSystem[] filesubsystems = null; + //if (subsystemFactoryID == null) + filesubsystems = RemoteFileUtility.getFileSubSystems(conn); + //else + // filesubsystems = sr.getSubSystems(subsystemFactoryID, conn); + + if (filesubsystems.length == 0) + { + msg = SystemPlugin.getPluginMessage(MSG_ERROR_CONNECTION_NOTFOUND);// hmm, what else to say? + msg.makeSubstitution(connName); + throw new Exception(msg.getLevelOneText()); + } + IRemoteFileSubSystem ss = (IRemoteFileSubSystem)filesubsystems[0]; // what else to do? + if (!ss.isConnected()) + { + try + { + ss.connect(getShell()); // will throw exception if fails. + } catch (InterruptedException exc) + { + msg = SystemPlugin.getPluginMessage(MSG_CONNECT_CANCELLED); + msg.makeSubstitution(conn.getHostName()); + throw new Exception(msg.getLevelOneText()); + } catch (Exception exc) + { + msg = SystemPlugin.getPluginMessage(MSG_CONNECT_FAILED); + msg.makeSubstitution(conn.getHostName()); + throw new Exception(msg.getLevelOneText()); + } + } + if (ss.isConnected()) + remoteFolder = ss.getRemoteFileObject(dirName); + return remoteFolder; + } + + /** + * Get the profile.connection name part of a qualified folder string. + */ + public static String extractQualifiedConnectionName(String qualifiedFolder) + { + int idx = qualifiedFolder.indexOf(CONNECTION_DELIMITER); + if (idx == -1) + return null; + else + return qualifiedFolder.substring(0,idx); + } + /** + * Get the profile name part of a profile.connection string + */ + public static String extractProfileName(String qualifiedConnectionName) + { + int idx = qualifiedConnectionName.indexOf('.'); + if (idx == -1) + return null; + else + return qualifiedConnectionName.substring(0,idx); + } + /** + * Get the connection name part of a profile.connection string. + * Will work if given profile.connection or profile.connection\folder + */ + public static String extractConnectionName(String qualifiedConnectionName) + { + int idx = qualifiedConnectionName.indexOf('.'); + if (idx == -1) + return null; + else + { + String nonProfile = qualifiedConnectionName.substring(idx+1); + idx = nonProfile.indexOf(CONNECTION_DELIMITER); + if (idx == -1) + return nonProfile; + else + return nonProfile.substring(0,idx); + } + } + + /** + * Get the folder name part of a qualified folder string. + */ + public static String extractFolder(String qualifiedFolder) + { + int idx = qualifiedFolder.indexOf(CONNECTION_DELIMITER); + if (idx == -1) + return null; + else + return qualifiedFolder.substring(idx+1); + } + + // ----------------------- + // INTERNAL-USE METHODS... + // ----------------------- + + /** + * Prepares this composite control and sets the default layout data. + * @param Number of columns the new group will contain. + */ + protected Composite prepareComposite(int numColumns) + { + Composite composite = this; + //GridLayout + GridLayout layout = new GridLayout(); + layout.numColumns = numColumns; + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + //GridData + GridData data = new GridData(); + data.verticalAlignment = GridData.CENTER; + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = false; + //data.widthHint = 300; + composite.setLayoutData(data); + return composite; + } + + protected void addOurButtonSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + IHost defaultConnection = null; + IRemoteFile currFolder = null; + try + { + currFolder = getFolder(); + } catch (Exception exc) {} + if (currFolder != null) + defaultConnection = currFolder.getSystemConnection(); + + if (browseAction == null) + { + browseAction = getBrowseAction(getShell(), defaultConnection); + } + browseAction.setShowNewConnectionPrompt(showNewPrompt); + //if (defaultConnection != null) + browseAction.setHost(defaultConnection); + //if (systemTypes != null) + browseAction.setSystemTypes(systemTypes); + //if (systemTypes != null) + // System.out.println("browseAction systemsTypes set to "+systemTypes[0]); + + + browseAction.run(); + IRemoteFile folder = ((SystemSelectRemoteFolderAction)browseAction).getSelectedFolder(); + if (folder != null) + setFolder(folder); + }; + }; + browseButton.addSelectionListener(selectionListener); + } + /** + * Returns action to be called when Browse... pressed. + */ + protected SystemSelectRemoteFolderAction getBrowseAction(Shell shell, IHost defaultConnection) + { + SystemSelectRemoteFolderAction action = new SystemSelectRemoteFolderAction(shell); + return action; + } + + + public static Button createPushButton(Composite group, String label) + { + Button button = new Button(group, SWT.PUSH); + button.setText(label); + //button.setText("THIS IS A VERY LONG LABEL. I MEAN, IT IS JUST HUGE"); + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = false; + button.setLayoutData(data); + return button; + } + protected static Button createPushButton(Composite group, ResourceBundle bundle, String key) + { + String label = bundle.getString(key+"label"); + Button button = createPushButton(group,label); + button.setToolTipText(bundle.getString(key+"tooltip")); + return button; + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteConnectionCombo.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteConnectionCombo.java new file mode 100644 index 00000000000..ccaea016c84 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteConnectionCombo.java @@ -0,0 +1,66 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import org.eclipse.rse.core.ISystemTypes; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.ui.widgets.SystemHostCombo; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; + + +/** + * A connection combo widget for universal connections. Includes remote Linux, Windows and Unix connections, + * and Local connections. + */ +public class SystemRemoteConnectionCombo extends SystemHostCombo { + + private static final String[] SYSTEM_TYPES = { ISystemTypes.SYSTEMTYPE_LINUX, + ISystemTypes.SYSTEMTYPE_LOCAL, + ISystemTypes.SYSTEMTYPE_UNIX, + ISystemTypes.SYSTEMTYPE_WINDOWS }; + + /** + * Constructor when you want to set the style. + * @param parent Parent composite. + * @param style SWT style flags for overall composite widget. Typically just pass SWT.NULL. + * @param defaultConnection the system connection to preselect. Pass null to preselect first connection. + * @param showNewButton true if a New... button is to be included in this composite. + */ + public SystemRemoteConnectionCombo(Composite parent, int style, IHost defaultConnection, boolean showNewButton) { + super(parent, style, SYSTEM_TYPES, defaultConnection, showNewButton); + } + + /** + * Constructor when you don't care about the style. Defaults to SWT.NULL. + * @param parent Parent composite. + * @param style SWT style flags for overall composite widget. Typically just pass SWT.NULL. + * @param defaultConnection the system connection to preselect. Pass null to preselect first connection. + * @param showNewButton true if a New... button is to be included in this composite. + */ + public SystemRemoteConnectionCombo(Composite parent, IHost defaultConnection, boolean showNewButton) { + this(parent, SWT.NULL, defaultConnection, showNewButton); + } + + /** + * Constructor when you don't care about the style or default connection, and do want to show the New button. + * This is the most common case. + * @param parent Parent composite + */ + public SystemRemoteConnectionCombo(Composite parent) { + this(parent, null, true); + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteFolderCombo.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteFolderCombo.java new file mode 100644 index 00000000000..5ab6bf060fe --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemRemoteFolderCombo.java @@ -0,0 +1,568 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import java.util.Iterator; +import java.util.ResourceBundle; +import java.util.Vector; + +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPreferencesManager; +import org.eclipse.rse.files.ui.actions.SystemSelectRemoteFolderAction; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemPreferencesConstants; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.widgets.ISystemCombo; +import org.eclipse.rse.ui.widgets.SystemHistoryCombo; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + + +/** + * This re-usable widget is for selecting a new or previously specified + * folder path within a given connection. + *

    + * Unlike SystemQualifiedRemoteFolderCombo, this widget does not combine the + * connection name with the folder name. That means if you want to restrict + * this to a particular connection, you must call setSystemConnection. If + * you want to restrict to any connections of a particular system type, call + * setSystemType. + *

    + * Because this combo only deals with strings, versus IRemoteFile, it is + * left to the caller to interpret that string as desired. + *

    + * The composite is layed as follows: + *

    
    + *   Folder: ______________v  Browse...
    + * 
    + */ +public class SystemRemoteFolderCombo extends Composite implements ISystemCombo +{ + private Label folderLabel = null; + private SystemHistoryCombo folderCombo = null; + private Button browseButton = null; + //private RemoteFileSubSystem subsystem = null; + //private RemoteFileSubSystemFactory subsystemFactory = null; + private String[] systemTypes = null; + private IHost connection = null; + private boolean showNewConnectionPrompt = true; + //private static final int DEFAULT_COMBO_WIDTH = 300; + //private static final int DEFAULT_BUTTON_WIDTH = 80; + private SystemSelectRemoteFolderAction browseAction = null; + private IRemoteFileSubSystem fileSubSystem = null; + + // list of listeners that are notified when the browse action is run and completed + // note that the listener + private Vector listeners; + + /** + * Constructor for SystemFileFolderCombo. Requires a history key used to store/restore the + * dropdown history for this. Pass null to use the overall default (ISystemPreferencesConstants.HISTORY_FOLDER) + * @param parent Parent composite + * @param style SWT style flags for overall composite widget + * @param historyKey A string identifying the key into the user preferences where this combo's history will be stored. + * @param readOnly True if the combo box is not to allow user editing. + * @see #setSystemConnection(IHost) + */ + public SystemRemoteFolderCombo(Composite parent, int style, String historyKey, boolean readOnly) + { + super(parent, style); + prepareComposite(3); + folderLabel = SystemWidgetHelpers.createLabel(this,SystemFileResources.WIDGET_FOLDER_LABEL, SystemFileResources.WIDGET_FOLDER_TOOLTIP); + if (historyKey == null) + historyKey = ISystemPreferencesConstants.HISTORY_FOLDER; + folderCombo = SystemWidgetHelpers.createHistoryCombo(this,null,historyKey,readOnly,SystemFileResources.WIDGET_FOLDER_TOOLTIP); + Object folderData = folderCombo.getLayoutData(); + if (folderData instanceof GridData) + ((GridData)folderData).widthHint = 160; + browseButton = createPushButton(this,SystemFileResources.WIDGET_BROWSE_LABEL); + addOurButtonSelectionListener(); + + listeners = new Vector(); + } + + /** + * Set auto-uppercase. When enabled, all non-quoted values are uppercases when appropriate. + * This has no effect in readonly mode! + */ + public void setAutoUpperCase(boolean enable) + { + folderCombo.setAutoUpperCase(enable); + } + + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + this.systemTypes = systemTypes; + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + } + + /** + * Set the input system connection to restrict the browse button to this connection only. + * Either call this or setSubSystemFactoryId. + */ + public void setSystemConnection(IHost connection) + { + this.connection = connection; + } + /** + * Get the system connection as specified in setSystemConnection. + */ + public IHost getSystemConnection() + { + return connection; + } + + /** + * Set the input remote file subsystem. If set, this will allow the browse button to better + * pre-fill the selection dialog when browse is pressed. + */ + public void setSubSystem(IRemoteFileSubSystem subsystem) + { + this.fileSubSystem = subsystem; + } + + /** + * Set whether to allow users to create new connections when Browse is pressed + */ + public void setShowNewConnectionPrompt(boolean show) + { + this.showNewConnectionPrompt = show; + } + + /** + * Return the combo box widget as a System + * Same as {@link #getCombo()} + */ + public Combo getFolderCombo() + { + return folderCombo.getCombo(); + } + + /** + * Get folder label. + * @return the folder label. + */ + public Label getFolderLabel() { + return folderLabel; + } + + /** + * Return the combo box historical widget + * Same as {@link #getCombo()} but returns the combo reference as a SystemHistoryCombo reference + */ + public SystemHistoryCombo getHistoryCombo() + { + return folderCombo; + } + /** + * Return the embedded combo box widget + * Same as {@link #getFolderCombo()} + */ + public Combo getCombo() + { + return folderCombo.getCombo(); + } + + /** + * Set the width hint for this whole composite + * Default is computed from children. + */ + public void setWidthHint(int widthHint) + { + // after much research it was decided that it was the wrong thing to do to + // explicitly set the widthHint of a child widget without our composite, as + // that could end up being a bigger number than the composites widthHint itself + // if the caller set its it directly. + // Rather, we just set the overall composite width and specify the combo child + // widget is to grab all the space within that which the little button does not use. + ((GridData)getLayoutData()).widthHint = widthHint; + } + + /** + * Return the browse button widget + */ + public Button getBrowseButton() + { + return browseButton; + } + + /** + * Set the items in the combo field + */ + public void setItems(String[] items) + { + folderCombo.setItems(items); + } + /** + * Get the items in the combo field + */ + public String[] getItems() + { + return folderCombo.getItems(); + } + + + /** + * Set the folder combo field's current contents + */ + public void setText(String text) + { + folderCombo.setText(text); + } + + /** + * Query the folder combo field's current contents + */ + public String getText() + { + return folderCombo.getText(); + } + + /** + * Disable/Enable all the child controls. + */ + public void setEnabled(boolean enabled) + { + folderCombo.setEnabled(enabled); + browseButton.setEnabled(enabled); + } + /** + * Set the tooltip text for the folder combo field + */ + public void setToolTipText(String tip) + { + folderLabel.setToolTipText(tip); + folderCombo.setToolTipText(tip); + } + /** + * Set the tooltip text for the browse button + */ + public void setBrowseButtonToolTipText(String tip) + { + browseButton.setToolTipText(tip); + } + /** + * Set the tooltip text for the browse button. + * Same as {@link #setBrowseButtonToolTipText(String)} + */ + public void setButtonToolTipText(String tip) + { + browseButton.setToolTipText(tip); + } + + /** + * Set the folder combo field's text limit + */ + public void setTextLimit(int limit) + { + folderCombo.setTextLimit(limit); + } + /** + * Set the focus to the folder combo field + */ + public boolean setFocus() + { + return folderCombo.setFocus(); + } + /** + * Set the focus to the browse button + */ + public void setBrowseButtonFocus() + { + browseButton.setFocus(); + } + /** + * Select the combo dropdown list entry at the given index + */ + public void select(int selIdx) + { + folderCombo.select(selIdx); + } + /** + * Same as {@link #select(int)} + */ + public void setSelectionIndex(int selIdx) + { + select(selIdx); + } + /** + * Get the index number of the currently selected item. + */ + public int getSelectionIndex() + { + return folderCombo.getSelectionIndex(); + } + + /** + * Clear the selection of the text in the entry field part of the combo + */ + public void clearSelection() + { + folderCombo.clearSelection(); + } + /** + * Clear the entered/selected contents of the combo box. Clears only the text selection, not the list selection + */ + public void clearTextSelection() + { + folderCombo.clearTextSelection(); + } + /** + * Register a listener interested in an item is selected in the combo box + * @see #removeSelectionListener(SelectionListener) + */ + public void addSelectionListener(SelectionListener listener) + { + folderCombo.addSelectionListener(listener); + } + /** + * Remove a previously set combo box selection listener. + * @see #addSelectionListener(SelectionListener) + */ + public void removeSelectionListener(SelectionListener listener) + { + folderCombo.removeSelectionListener(listener); + } + /** + * Register a listener interested in when the browse button is selected + * @see #removeBrowseButtonSelectionListener(SelectionListener) + */ + public void addBrowseButtonSelectionListener(SelectionListener listener) + { + browseButton.addSelectionListener(listener); + } + /** + * Remove a previously set browse button selection listener. + * @see #addBrowseButtonSelectionListener(SelectionListener) + */ + public void removeBrowseButtonSelectionListener(SelectionListener listener) + { + browseButton.removeSelectionListener(listener); + } + + /** + * Register a listener interested in entry field modify events + * @see #removeModifyListener(ModifyListener) + */ + public void addModifyListener(ModifyListener listener) + { + folderCombo.addModifyListener(listener); + } + /** + * Remove a previously set entry field listener. + * @see #addModifyListener(ModifyListener) + */ + public void removeModifyListener(ModifyListener listener) + { + folderCombo.removeModifyListener(listener); + } + + /** + * Adds a listener which will be notified each time after the browse action is run. + * @param listener the listener to be notified. + */ + public void addBrowseActionCompleteListener(ISystemRemoteFolderBrowseCompleteListener listener) { + + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } + + /** + * Removes the given listener. Has no effect if the listener was not added before. + * @param listener the listener to be removed. + */ + public void removeBrowseActionCompleteListener(ISystemRemoteFolderBrowseCompleteListener listener) { + listeners.remove(listener); + } + + /** + * Notifies all registered listeners. + * @param remoteFile the remote file to use for the notification. + */ + protected void notifyBrowseActionCompleteListeners(IRemoteFile remoteFile) { + + Iterator iter = listeners.iterator(); + + if (iter.hasNext()) { + ISystemRemoteFolderBrowseCompleteListener listener = (ISystemRemoteFolderBrowseCompleteListener)(iter.next()); + listener.fileSelected(remoteFile); + } + } + + /** + * Return the current history for the folder combo box + */ + public static String[] getHistory() + { + return SystemPreferencesManager.getPreferencesManager().getFolderHistory(); + } + + /** + * Update the history with current entry field setting. + *

    + * This is called automatically for you when setText is called. However, for non-readonly + * versions, you should still call this yourself when OK is successfully pressed on the + * dialog box. + */ + public void updateHistory() + { + folderCombo.updateHistory(); + } + + /** + * Update the history with current entry field setting, and optionally refresh the list from the new history. + */ + public void updateHistory(boolean refresh) { + folderCombo.updateHistory(refresh); + } + + // ----------------------- + // INTERNAL-USE METHODS... + // ----------------------- + /** + * Prepares this composite control and sets the default layout data. + * @param Number of columns the new group will contain. + */ + protected Composite prepareComposite(int numColumns) + { + Composite composite = this; + //GridLayout + GridLayout layout = new GridLayout(); + layout.numColumns = numColumns; + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + //GridData + GridData data = new GridData(); + data.verticalAlignment = GridData.CENTER; + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = false; + //data.widthHint = 180; //CAUSES TRUNCATION IF TRANSLATED BUTTON TEXT IS LONG + composite.setLayoutData(data); + return composite; + } + + protected void addOurButtonSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + if (browseAction == null) + { + browseAction = getBrowseAction(getShell()); + } + //if (connection != null) + browseAction.setHost(connection); + //if (systemTypes != null) + browseAction.setSystemTypes(systemTypes); + browseAction.setShowNewConnectionPrompt(showNewConnectionPrompt); + browseAction.setShowPropertySheet(true, false); + String currentFolder = getText().trim(); + if ((currentFolder.length() > 0) && (fileSubSystem!=null)) + { + IRemoteFile currentFolderObject = null; + try { + currentFolderObject = fileSubSystem.getRemoteFileObject(currentFolder); + } catch(SystemMessageException e) { + SystemBasePlugin.logError("SystemRemoteFolderCombo.wdigetSelected", e); + } + if (currentFolderObject != null) + browseAction.setPreSelection(currentFolderObject); + } + + browseAction.run(); + IRemoteFile folder = ((SystemSelectRemoteFolderAction)browseAction).getSelectedFolder(); + if (folder != null) + setText(folder.getAbsolutePath()); + + // notify listeners with the selected folder + // we notify even if the suer cancelled and the folder is null so listeners + // know that the brose dialog was cancelled + notifyBrowseActionCompleteListeners(folder); + }; + }; + browseButton.addSelectionListener(selectionListener); + } + /** + * Returns action to be called when Browse... pressed. + * Either connection or subsystemFactoryId better be set! + */ + protected SystemSelectRemoteFolderAction getBrowseAction(Shell shell) + { + SystemSelectRemoteFolderAction action = new SystemSelectRemoteFolderAction(shell); + return action; + } + + + public static Button createPushButton(Composite group, String label) + { + Button button = new Button(group, SWT.PUSH); + button.setText(label); + //button.setText("THIS IS A VERY LONG LABEL. I MEAN IT IS JUST HUGE."); //to test mri + GridData data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = false; + button.setLayoutData(data); + return button; + } + protected static Button createPushButton(Composite group, ResourceBundle bundle, String key) + { + String label = bundle.getString(key+"label"); + Button button = createPushButton(group,label); + button.setToolTipText(bundle.getString(key+"tooltip")); + return button; + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFileOrFolderForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFileOrFolderForm.java new file mode 100644 index 00000000000..cf88d8ea5ec --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFileOrFolderForm.java @@ -0,0 +1,1057 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.rse.core.SystemAdapterHelpers; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.SystemRemoteObjectMatcher; +import org.eclipse.rse.files.ui.ISystemAddFileListener; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.SystemFilterSimple; +import org.eclipse.rse.model.IHost; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.SystemFileResources; +import org.eclipse.rse.subsystems.files.core.model.ISystemFileRemoteTypes; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileUtility; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.subsystems.files.core.util.SystemRemoteFileMatcher; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.dialogs.SystemPromptDialog; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.validators.IValidatorRemoteSelection; +import org.eclipse.rse.ui.view.ISystemRemoteElementAdapter; +import org.eclipse.rse.ui.view.SystemPropertySheetForm; +import org.eclipse.rse.ui.view.SystemSelectRemoteObjectAPIProviderImpl; +import org.eclipse.rse.ui.view.SystemViewForm; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + + + +/** + * A reusable form for prompting for a remote file system folder or file. + *

    + * This form may be used to populate a dialog or a wizard page. + *

    + * To configure the functionality, call these methods: + *

      + *
    • {@link #setShowNewConnectionPrompt(boolean)} + *
    • {@link #setSystemConnection(IHost) or #setDefaultConnection(SystemConnection)} + *
    • {@link #setSystemTypes(String[])} + *
    • {@link #setRootFolder(IHost, String)} or {@link #setRootFolder(IRemoteFile)} + *
    • {@link #setPreSelection(IRemoteFile)} + *
    • {@link #setFileTypes(String[])} or {@link #setFileTypes(String)} + *
    • {@link #setAutoExpandDepth(int)} + *
    • {@link #setShowPropertySheet(boolean)} + *
    • {@link #enableAddMode(org.eclipse.rse.files.ui.ISystemAddFileListener)} + *
    • {@link #setMultipleSelectionMode(boolean)} + *
    • {@link #setSelectionValidator(org.eclipse.rse.ui.IValidatorRemoteSelection)} + *
    + *

    + * To configure the text on the dialog, call these methods: + *

      + *
    • {@link #setMessage(String)} + *
    • {@link #setSelectionTreeToolTipText(String)} + *
    + *

    + * After running, call these methods to get the output: + *

      + *
    • {@link #getSelectedObject()} + *
    • {@link #getSelectedConnection()} + *
    + */ +public class SystemSelectRemoteFileOrFolderForm + implements ISelectionChangedListener, ISystemIconConstants, ISystemMessages +{ + protected static final int PROMPT_WIDTH = 400; // The maximum width of the dialog's prompt, in pixels. + + // GUI widgets + protected Label verbageLabel, spacer1, spacer2; + protected Text nameEntryValue; + protected SystemViewForm tree; + protected SystemPropertySheetForm ps; + protected ISystemMessageLine msgLine; + protected Composite outerParent, ps_composite; + // inputs + protected ISystemRegistry sr = null; + protected String verbage = null; + protected String treeTip = null; + protected String locationPrompt = ""; + protected String fileTypes; + protected boolean fileMode; + protected boolean valid = true; + protected boolean filesOnlyMode; + protected boolean showRootFilter = true; + protected boolean alwaysEnableOK = false; + protected boolean multipleSelectionMode; + protected boolean allowForMultipleParents = false; + protected boolean showPropertySheet = false; + protected boolean showLocationPrompt = false; + protected boolean allowFolderSelection = true; + protected SystemRemoteObjectMatcher objectMatcher = null; + protected ISystemAddFileListener addButtonCallback = null; + protected Vector listeners = new Vector(); + protected IValidatorRemoteSelection selectionValidator; + // outputs + protected Object[] outputObjects = null; + protected IHost outputConnection = null; + // state + //protected ResourceBundle rb; + protected SystemSelectRemoteObjectAPIProviderImpl inputProvider = null; + protected ISystemFilter preSelectFilter; + protected String preSelectFilterChild; + protected boolean preSelectRoot; + protected boolean initDone; + protected boolean contentsCreated; + + //protected String errorMessage; + protected Object caller; + protected boolean callerInstanceOfWizardPage, callerInstanceOfSystemPromptDialog; + protected int autoExpandDepth = 0; + + protected Object previousSelection = null; + protected List viewerFilters = new ArrayList(); + + /** + * Constructor + * @param msgLine A GUI widget capable of writing error messages to. + * @param caller The wizardpage or dialog hosting this form. + * @param fileMode true if in select-file mode, false if in select-folder mode + + * @see #setSystemConnection(IHost) + * @see #setShowNewConnectionPrompt(boolean) + * @see #setSystemTypes(String[]) + * @see #setSelectionTreeToolTipText(String) + */ + public SystemSelectRemoteFileOrFolderForm(ISystemMessageLine msgLine, Object caller, boolean fileMode) + { + this.msgLine = msgLine; + this.caller = caller; + this.fileMode = fileMode; + callerInstanceOfWizardPage = (caller instanceof WizardPage); + callerInstanceOfSystemPromptDialog = (caller instanceof SystemPromptDialog); + //rb = SystemPlugin.getResourceBundle(); + sr = SystemPlugin.getTheSystemRegistry(); + + // set default GUI + verbage = fileMode ? SystemFileResources.RESID_SELECTFILE_VERBAGE: SystemFileResources.RESID_SELECTDIRECTORY_VERBAGE; + treeTip = fileMode ? SystemFileResources.RESID_SELECTFILE_SELECT_TOOLTIP : SystemFileResources.RESID_SELECTDIRECTORY_SELECT_TOOLTIP; + + // create the input provider that drives the contents of the tree + inputProvider = getInputProvider(); + + String initialFilterString = "*"; // change to "*" for defect 43492 + inputProvider.setFilterString(fileMode ? initialFilterString : initialFilterString+" /nf"); + + // create object matcher + if (fileMode) + objectMatcher = SystemRemoteFileMatcher.getFileOnlyMatcher(); + else + objectMatcher = SystemRemoteFileMatcher.getFolderOnlyMatcher(); + } + + // --------------------------------- + // INPUT OR CONFIGURATION METHODS... + // --------------------------------- + /** + * Returns the input provider that drives the contents of the tree + * Subclasses can override to provide custom tree contents + */ + protected SystemSelectRemoteObjectAPIProviderImpl getInputProvider() + { + if (inputProvider == null) + { + // create the input provider that drives the contents of the tree + inputProvider = new SystemSelectRemoteObjectAPIProviderImpl(null, ISystemFileRemoteTypes.TYPECATEGORY, + true, null); // show new connection prompt, no system type restrictions + + } + return inputProvider; + } + + /** + * Indicate whether the form should allow selection of objects from different parents + */ + public void setAllowForMultipleParents(boolean flag) + { + allowForMultipleParents = flag; + } + + /** + * Set the connection to restrict the user to seeing + */ + public void setSystemConnection(IHost conn) + { + // Dave, you can't just change true to false. This causes the side effect of all selection dialogs + // allowing users to see more then just their current connection, which makes no sense. It needs + // to be selective based on the particular action. So, I added setDefaultConnection for those cases + // where we want to see other connections. Phil + //inputProvider.setSystemConnection(conn, /* DKM - now we support cross system copy true */ false); // true means only this connection + inputProvider.setSystemConnection(conn,true); // true means only this connection + } + /** + * Set the connection to default the selection to + */ + public void setDefaultConnection(IHost conn) + { + inputProvider.setSystemConnection(conn, /* DKM - now we support cross system copy true */ false); // true means only this connection + } + + /** + * Set to true if a "New Connection..." special connection is to be shown for creating new connections + */ + public void setShowNewConnectionPrompt(boolean show) + { + inputProvider.setShowNewConnectionPrompt(show); + } + /** + * Restrict to certain system types + * @param systemTypes the system types to restrict what connections are shown and what types of connections + * the user can create + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + inputProvider.setSystemTypes(systemTypes); + } + /** + * Set the message shown as the text at the top of the form. Eg, "Select a file" + */ + public void setMessage(String message) + { + this.verbage = message; + if (verbageLabel != null) + verbageLabel.setText(message); + } + /** + * Set the tooltip text for the remote systems tree from which an item is selected. + */ + public void setSelectionTreeToolTipText(String tip) + { + this.treeTip = tip; + if (tree != null) + tree.setToolTipText(tip); + } + + /** + * Set the root folder from which to start listing folders or files. + * This version identifies the folder via a connection object and absolute path. + * There is another overload that identifies the folder via a single IRemoteFile object. + * + * @param connection The connection to the remote system containing the root folder + * @param folderAbsolutePath The fully qualified folder to start listing from (eg: "\folder1\folder2") + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IHost connection, String folderAbsolutePath) + { + setSystemConnection(connection); + setShowNewConnectionPrompt(false); + setAutoExpandDepth(1); + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + IRemoteFileSubSystem ss = RemoteFileUtility.getFileSubSystem(connection); + IRemoteFileSubSystemConfiguration ssf = ss.getParentRemoteFileSubSystemFactory(); + RemoteFileFilterString rffs = new RemoteFileFilterString(ssf); + rffs.setShowFiles(fileMode); // no files if in folders mode + rffs.setShowSubDirs(!fileMode || !filesOnlyMode); // yes folders, always, for now + if (fileTypes != null) + rffs.setFile(fileTypes); + + // set the default filters we will show when the user expands a connection... + String filterName = null; + SystemFilterSimple filter = null; + int filterCount = showRootFilter ? 2 : 1; + if (preSelectRoot) + filterCount = 1; + ISystemFilter[] filters = new ISystemFilter[filterCount]; + int idx = 0; + + // filter one: "Root files"/"Root folders" or "Drives" + if (showRootFilter) + { + if (ssf.isUnixStyle()) + { + if (!preSelectRoot) + { + // "Root files" or "Folders" + filterName = fileMode ? SystemFileResources.RESID_FILTER_ROOTFILES : SystemFileResources.RESID_FILTER_ROOTFOLDERS; + //rffs.setPath(ssf.getSeparator()); // defect 43492. Show the root not the contents of the root + } + else + { + filterName = SystemFileResources.RESID_FILTER_ROOTS; // "Roots" + } + } + else + filterName = fileMode ? SystemFileResources.RESID_FILTER_DRIVES : SystemFileResources.RESID_FILTER_DRIVES; + filter = new SystemFilterSimple(filterName); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx++] = filter; + //System.out.println("FILTER 1: " + filter.getFilterString()); + if (preSelectRoot) + { + preSelectFilter = filter; + preSelectFilterChild = folderAbsolutePath; + //SystemPlugin.logInfo("in setRootFolder. Given: " + folderAbsolutePath); + } + } + + if (!preSelectRoot) + { + + // filter two: "\folder1\folder2" + rffs.setPath(folderAbsolutePath); + + filter = new SystemFilterSimple(rffs.toStringNoSwitches()); + filter.setParent(ss); + filter.setFilterString(rffs.toString()); + filters[idx] = filter; + + preSelectFilter = filter; + //SystemPlugin.logInfo("FILTER 2: " + filter.getFilterString()); + } + inputProvider.setFilterString(null); // undo what ctor did + inputProvider.setQuickFilters(filters); + } + /** + * Set the root folder from which to start listing folders. + * This version identifies the folder via an IRemoteFile object. + * There is another overload that identifies the folder via a connection and folder path. + * + * @param rootFolder The IRemoteFile object representing the remote folder to start the list from + * + * @see org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString + */ + public void setRootFolder(IRemoteFile rootFolder) + { + setRootFolder(rootFolder.getSystemConnection(),rootFolder.getAbsolutePath()); + } + /** + * Set a file or folder to preselect. This will: + *
      + *
    • Set the parent folder as the root folder + *
    • Pre-expand the parent folder + *
    • Pre-select the given file or folder after expansion + *
    + * If there is no parent, then we were given a root. In which case we will + *
      + *
    • Force setRestrictFolders to false + *
    • Pre-expand the root drives (Windows) or root files (Unix) + *
    • Pre-select the given root drive (Windows only) + *
    + */ + public void setPreSelection(IRemoteFile selection) + { + SystemBasePlugin.logInfo("given: '" + selection.getAbsolutePath()+"'"); + IRemoteFile parentFolder = selection.getParentRemoteFile(); + /**/ + if (parentFolder != null) + SystemBasePlugin.logInfo("parent of given: '" + parentFolder.getAbsolutePath() + "'"); + else + SystemBasePlugin.logInfo("parent of given is null"); + /**/ + // it might be a bug, bug when asking for the parent of '/', I get back '/'!!! + if ((parentFolder != null) && + (selection.getAbsolutePath().equals("/") && + (parentFolder.getAbsolutePath()!=null) && + parentFolder.getAbsolutePath().equals("/"))) + parentFolder = null; + if (parentFolder != null) + { + IRemoteFileSubSystemConfiguration ssf = selection.getParentRemoteFileSubSystem().getParentRemoteFileSubSystemFactory(); + boolean isUnix = ssf.isUnixStyle(); + if (isUnix) + setRestrictFolders(parentFolder.isRoot()); + setRootFolder(parentFolder); + preSelectFilterChild = selection.getName(); + //SystemPlugin.logInfo("Setting preSelectFilterChild to '"+preSelectFilterChild+"'"); + } + else + { + SystemBasePlugin.logInfo("preSelectRoot is true"); + preSelectRoot = true; + setRestrictFolders(false); + setRootFolder(selection); + } + inputProvider.setPreSelectFilterChild(preSelectFilterChild); + } + + /** + * For files mode, restrict the files list by an array of file types + *

    + * This must be called BEFORE setRootFolder! + */ + public void setFileTypes(String[] fileTypes) + { + String fts = null; + if (fileTypes != null) + fts = RemoteFileFilterString.getTypesString(fileTypes); + setFileTypes(fts); + } + /** + * For files mode, restrict the files list by a comman-delimited array of file types. + * The last type must also end in a comma. Eg "java, class," or "class,". + *

    + * This must be called BEFORE setRootFolder! + */ + public void setFileTypes(String fileTypes) + { + this.fileTypes = fileTypes; + inputProvider.setFilterString("/"+ fileTypes); + } + /** + * Specify the zero-based auto-expand level for the tree. The default is zero, meaning + * only show the connections. + */ + public void setAutoExpandDepth(int depth) + { + this.autoExpandDepth = depth+1; + } + /** + * Specify whether setRootFolder should prevent the user from being able to see or select + * any other folder. This causes two effects: + *

      + *
    1. The special filter for root/drives is not shown + *
    2. No subfolders are listed in the target folder, if we are listing files. Of course, they are shown + * if we are listing folders, else it would be an empty list! + *
    + */ + public void setRestrictFolders(boolean restrict) + { + //this.filesOnlyMode = restrict; + this.showRootFilter = !restrict; + } + /** + * Enable Add mode. This means the OK button is replaced with an Add button, and + * the Cancel with a Close button. When Add is pressed, the caller is called back. + * The dialog is not exited until Close is pressed. + *

    + * When a library is selected, the caller is called back to decide to enable the Add + * button or not. + */ + public void enableAddMode(ISystemAddFileListener caller) + { + this.addButtonCallback = caller; + } + /** + * Show the property sheet on the right hand side, to show the properties of the + * selected object. + *

    + * Default is false + */ + public void setShowPropertySheet(boolean show) + { + this.showPropertySheet = show; + } + + /** + * Set multiple selection mode. Default is single selection mode + *

    + * If you turn on multiple selection mode, you must use the getSelectedObjects() + * method to retrieve the list of selected objects. + *

    + * Further, if you turn this on, it has the side effect of allowing the user + * to select any remote object. The assumption being if you are prompting for + * files, you also want to allow the user to select a folder, with the meaning + * being that all files within the folder are implicitly selected. + * + * @see #getSelectedObjects() + */ + public void setMultipleSelectionMode(boolean multiple) + { + this.multipleSelectionMode = multiple; + if (multiple) + objectMatcher = null; + } + + /** + * Add a listener to selection change events in the tree + */ + public void addSelectionChangedListener(ISelectionChangedListener l) + { + if (tree != null) + tree.addSelectionChangedListener(l); + else + listeners.addElement(l); + } + /** + * Remove a listener for selection change events + */ + public void removeSelectionChangedListener(ISelectionChangedListener l) + { + if (tree != null) + tree.removeSelectionChangedListener(l); + else + listeners.removeElement(l); + } + + /** + * Specify a validator to use when the user selects a remote file or folder. + * This allows you to decide if OK should be enabled or not for that remote file or folder. + */ + public void setSelectionValidator(IValidatorRemoteSelection selectionValidator) + { + this.selectionValidator = selectionValidator; + } + + + // --------------------------------- + // OUTPUT METHODS... + // --------------------------------- + /** + * Return first selected object + */ + public Object getSelectedObject() + { + if ((outputObjects != null) && (outputObjects.length>=1)) + return outputObjects[0]; + else + return null; + } + /** + * Return all selected objects. + * @see #setMultipleSelectionMode(boolean) + */ + public Object[] getSelectedObjects() + { + return outputObjects; + } + /** + * Return selected connection + */ + public IHost getSelectedConnection() + { + return outputConnection; + } + + /** + * Return the embedded System Tree object. + * Will be null until createContents is called. + */ + public SystemViewForm getSystemViewForm() + { + return tree; + } + + /** + * Return the multiple selection mode current setting + */ + public boolean getMultipleSelectionMode() + { + return multipleSelectionMode; + } + + // ----------------------------------------------------- + // SEMI-PRIVATE METHODS USED BY CALLING DIALOG/WIZARD... + // ----------------------------------------------------- + /** + * Often the message line is null at the time of instantiation, so we have to call this after + * it is created. + */ + public void setMessageLine(ISystemMessageLine msgLine) + { + this.msgLine = msgLine; + } + + /** + * Return control to recieve initial focus + */ + public Control getInitialFocusControl() + { + return tree.getTreeControl(); + } + + /** + * Show or hide the property sheet. This is called after the contents are created when the user + * toggles the Details button. + * @param shell Use getShell() in your dialog or wizard page + * @param contents Use getContents() in your dialog or wizard page + * @return new state -> true if showing, false if hiding + */ + public boolean toggleShowPropertySheet(Shell shell, Control contents) + { + Point windowSize = shell.getSize(); + Point oldSize = contents.computeSize(SWT.DEFAULT, SWT.DEFAULT); + + if (showPropertySheet) // hiding? + { + ps.dispose(); + spacer1.dispose(); + spacer2.dispose(); + ps_composite.dispose(); + ps = null; spacer1 = spacer2 = null; ps_composite = null; + ((GridLayout)outerParent.getLayout()).numColumns = 1; + } + else // showing? + { + //createPropertySheet((Composite)contents, shell); + ((GridLayout)outerParent.getLayout()).numColumns = 2; + createPropertySheet(outerParent, shell); + } + + Point newSize = contents.computeSize(SWT.DEFAULT, SWT.DEFAULT); + shell.setSize(new Point(windowSize.x + (newSize.x - oldSize.x), windowSize.y)); + + if (ps != null) + { + ISelection s = tree.getSelection(); + if (s != null) + ps.selectionChanged(s); + } + + showPropertySheet = !showPropertySheet; + return showPropertySheet; + } + + /** + * Create the property sheet viewer + */ + private void createPropertySheet(Composite outerParent, Shell shell) + { + ps_composite = SystemWidgetHelpers.createFlushComposite(outerParent, 1); + ((GridData)ps_composite.getLayoutData()).grabExcessVerticalSpace = true; + ((GridData)ps_composite.getLayoutData()).verticalAlignment = GridData.FILL; + + // SPACER LINES + spacer1 = SystemWidgetHelpers.createLabel(ps_composite, "", 1); + spacer2 = SystemWidgetHelpers.createLabel(ps_composite, "", 1); + // PROPERTY SHEET VIEWER + ps = new SystemPropertySheetForm(shell, ps_composite, SWT.BORDER, msgLine); + } + + public void dispose() + { + if (tree != null) + { + tree.removeSelectionChangedListener(this); + for (int i = 0; i < listeners.size(); i++) + { + tree.removeSelectionChangedListener((ISelectionChangedListener)listeners.get(i)); + } + } + } + /** + * In this method, we populate the given SWT container with widgets and return the container + * to the caller. + * @param parent The parent composite + */ + public Control createContents(Shell shell, Composite parent) + { + contentsCreated = true; + + outerParent = parent; + // OUTER COMPOSITE + //if (showPropertySheet) + { + outerParent = SystemWidgetHelpers.createComposite(parent, showPropertySheet ? 2 : 1); + } + + // INNER COMPOSITE + int gridColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createFlushComposite(outerParent, gridColumns); + + // PROPERTY SHEET COMPOSITE + if (showPropertySheet) + { + createPropertySheet(outerParent, shell); + } + else + { + //((GridLayout)composite_prompts.getLayout()).margin... + } + + // MESSAGE/VERBAGE TEXT AT TOP + verbageLabel = (Label) SystemWidgetHelpers.createVerbage(composite_prompts, verbage, gridColumns, false, PROMPT_WIDTH); + //verbageLabel = SystemWidgetHelpers.createLabel(composite_prompts, verbage, gridColumns); + + // SPACER LINE + SystemWidgetHelpers.createLabel(composite_prompts, "", gridColumns); + + // LOCATION PROMPT + if (showLocationPrompt) + { + SystemWidgetHelpers.createLabel(composite_prompts, locationPrompt, gridColumns); + } + + // SELECT OBJECT READONLY TEXT FIELD + Composite nameComposite = composite_prompts; + int nameSpan = gridColumns; + nameEntryValue = SystemWidgetHelpers.createReadonlyTextField(nameComposite); + ((GridData)nameEntryValue.getLayoutData()).horizontalSpan = nameSpan; + + // create an array of viewer filters from our list of viewer filters + ViewerFilter[] initViewerFilters = null; + + // if we don't have a viewer filter list, then create an empty array + if (viewerFilters == null) { + initViewerFilters = new ViewerFilter[0]; + } + // otherwise copy from list to array + else { + initViewerFilters = new ViewerFilter[viewerFilters.size()]; + + Iterator iter = viewerFilters.iterator(); + + int idx = 0; + + // copy from list to array + while (iter.hasNext()) { + ViewerFilter filter = (ViewerFilter)(iter.next()); + initViewerFilters[idx] = filter; + idx++; + } + } + + // TREE + tree = new SystemViewForm(shell, composite_prompts, SWT.NULL, inputProvider, !multipleSelectionMode, msgLine, gridColumns, 1, initViewerFilters); + + if (treeTip != null) + //tree.setToolTipText(treeTip); //EXTREMELY ANNOYING! + if (autoExpandDepth != 0) + { + tree.getSystemView().setAutoExpandLevel(autoExpandDepth); + tree.reset(inputProvider); + } + + // initialize fields + if (!initDone) + doInitializeFields(); + + // add selection listeners + tree.addSelectionChangedListener(this); + if (listeners.size() > 0) + for (int idx=0; idx 1) && !tree.sameParent() && !allowForMultipleParents) + { + clearErrorMessage(); + setNameText(""); + setPageComplete(); + return; // don't enable OK/Add if selections from different parents + } + + Object errMsg = null; + Object selectedObject = getFirstSelection(selection); + if (selectedObject == previousSelection && selectionSize == 1) + { + // DKM we null set this before, so we need to reset it + outputObjects = getSelections(selection); + return; + } + clearErrorMessage(); + setNameText(""); + setPageComplete(); + previousSelection = selectedObject; + if (selectedObject != null) + { + + ISystemRemoteElementAdapter remoteAdapter = getRemoteAdapter(selectedObject); + if (remoteAdapter != null) + { + setNameTextFromSelection(selection, selectedObject, remoteAdapter); + + outputConnection = internalGetConnection(); + if ((addButtonCallback != null) && (selectedObject instanceof IRemoteFile)) + { + errMsg = addButtonCallback.okToEnableAddButton(outputConnection, (IRemoteFile[])getSelections(selection)); + + if (errMsg != null) + { + if (errMsg instanceof String) + setErrorMessage((String)errMsg); + else + setErrorMessage((SystemMessage)errMsg); + } + } + else if ((objectMatcher == null) || objectMatcher.appliesTo(remoteAdapter, selectedObject)) + { + SystemMessage selectionMsg = null; + if (selectionValidator != null) + selectionMsg = selectionValidator.isValid(outputConnection, getSelections(selection), getRemoteAdapters(selection)); + + if (selectionMsg != null) + { + valid = false; + setErrorMessage(selectionMsg); + setPageComplete(); + } + } + // if we're in file mode and folder selection is not allowed, then mark as invlaid selection + else if (fileMode && !allowFolderSelection) { + + if (remoteAdapter.getRemoteType(selectedObject).equals(ISystemFileRemoteTypes.TYPE_FOLDER)) { + valid = false; + setPageComplete(); + } + } + } + } + } + + protected ISystemRemoteElementAdapter[] getRemoteAdapters(ISelection selection) + { + Object[] selectedObjects = getSelections(selection); + ISystemRemoteElementAdapter[] adapters = new ISystemRemoteElementAdapter[selectedObjects.length]; + for (int idx=0; idx 0) ) && valid; + } + + /** + * Inform caller of page-complete status of this form + */ + public void setPageComplete() + { + if (callerInstanceOfWizardPage) + { + ((WizardPage)caller).setPageComplete(isPageComplete()); + } + else if (callerInstanceOfSystemPromptDialog) + { + ((SystemPromptDialog)caller).setPageComplete(isPageComplete()); + } + } + + + protected void clearErrorMessage() + { + if (msgLine != null) + msgLine.clearErrorMessage(); + } + protected void setErrorMessage(String msg) + { + if (msgLine != null) + if (msg != null) + msgLine.setErrorMessage(msg); + else + msgLine.clearErrorMessage(); + } + protected void setErrorMessage(SystemMessage msg) + { + if (msgLine != null) + if (msg != null) + msgLine.setErrorMessage(msg); + else + msgLine.clearErrorMessage(); + } + + /** + * Return shell of parent dialog or wizard + */ + protected Shell getShell() + { + if (callerInstanceOfWizardPage) + return ((WizardPage)caller).getShell(); + else if (callerInstanceOfSystemPromptDialog) + return ((SystemPromptDialog)caller).getShell(); + else + return null; + } + + public void setShowLocationPrompt(boolean show) + { + showLocationPrompt = show; + } + + public void setLocationPrompt(String prompt) + { + locationPrompt = prompt; + } + + /** + * Add viewer filter. + * @param filter a viewer filter. + * @see SystemActionViewerFilter. + */ + public void addViewerFilter(ViewerFilter filter) { + viewerFilters.add(filter); + } + + /** + * Sets whether to allow folder selection. The default selection validator will use this to + * determine whether the OK button will be enabled when a folder is selected. The default + * is true. This call only makes sense if the form is in file selection mode. + * @param allow true to allow folder selection, false otherwise. + */ + public void setAllowFolderSelection(boolean allow) { + allowFolderSelection = allow; + } +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFilesForm.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFilesForm.java new file mode 100644 index 00000000000..27a3675127b --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/widgets/SystemSelectRemoteFilesForm.java @@ -0,0 +1,612 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.widgets; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; + +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.SystemFileTreeAndListGroup; +import org.eclipse.rse.files.ui.actions.SystemSelectFileTypesAction; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileRoot; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.SystemViewLabelAndContentProvider; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; + + +/** + * This re-usable composite widget is for prompting the user to select + * multiple files from a remote system. + *

    + * The composite is layed as follows: + * + * Folder: ______________V Browse... + * + * .________________. ____________. + * | + folder | | file1 | + * | + subfolder | | file2 | + * | + subfolder | | file3 | + * .---------------. .-----------. + * + * The tree and list boxes are checkbox widgets, standard in Eclipse. + *

    + * You can also optionally decide to show the standard buttons at the + * button of the checkbox boxes: + * + * .-----------------. .------------. .--------------. + * | Select Types... | | Select All | | Deselect All | + * .-----------------. .------------. .--------------. + * + * + *

    + * To allow error messages to be issued on a message line versus in message dialogs, + * pass in an ISystemMessageLine reference. This usually represents the message line + * of a dialog or wizard. If supplied, messages are written to it. + * To specify it, call {@link #setMessageLine(ISystemMessageLine)}. + */ +public class SystemSelectRemoteFilesForm extends Composite +{ + // widgets + private SystemQualifiedRemoteFolderCombo dirCombo = null; + private SystemFileTreeAndListGroup fileSelector = null; + //private RemoteFileEmptyImpl emptyFileSelectorRoot = null; + private RemoteFileRoot rootElement = null; + private Button selectTypesButton, selectAllButton, deselectAllButton; + // state + private String historyKey = null; + private boolean showSelectTypesButton, showSelectAllButtons = false; + private ISystemMessageLine msgLine = null; + private java.util.List selectedTypes = new ArrayList(); + private String filterString = null; + private SystemSelectFileTypesAction typesAction = null; + private SystemViewLabelAndContentProvider folderProvider, fileProvider; + // constants + private final static int SIZING_SELECTION_WIDGET_WIDTH = 400; + private final static int SIZING_SELECTION_WIDGET_HEIGHT = 150; + /** + * Constructor when you want to specify your own history key for the qualified folder + * nested widget. + * + * @param parent The owning composite + * @param style The swt style to apply to the overall composite. Typically it is just SWT.NULL + * @param showSelectTypesButton Specify if you want to have Select Types button + * @param showSelectAllButtons Specify if you want to have Select All and Deselect All buttons + * @param key The unique string used as a preferences key to persist the qualified-folder history + */ + public SystemSelectRemoteFilesForm(Composite parent, int style, + boolean showSelectTypesButton, boolean showSelectAllButtons, + String key) + { + super(parent, style); + this.showSelectTypesButton = showSelectTypesButton; + this.showSelectAllButtons = showSelectAllButtons; + historyKey = key; + prepareComposite(1); + createFolderPrompt(this); + createFilesSelectorGroup(this); + if (showSelectTypesButton || showSelectAllButtons) + createButtons(this, showSelectTypesButton, showSelectAllButtons); + addOurQualifiedFolderSelectionListener(); + } + /** + * Constructor when you want to use the default history key, meaning you share the + * qualified-folder history with other dialogs/wizards that use the same widget. + * + * @param parent The owning composite + * @param style The swt style to apply to the overall composite. Typically it is just SWT.NULL + * @param showSelectTypesButton Specify if you want to have Select Types button + * @param showSelectAllButtons Specify if you want to have Select All and Deselect All buttons + */ + public SystemSelectRemoteFilesForm(Composite parent, int style, + boolean showSelectTypesButton, boolean showSelectAllButtons) + { + this(parent, style, showSelectTypesButton, showSelectAllButtons, null); + } + /** + * Constructor when you want to use the default history key and want to show the standard buttons. + * + * @param parent The owning composite + * @param style The swt style to apply to the overall composite. Typically it is just SWT.NULL + */ + public SystemSelectRemoteFilesForm(Composite parent, int style) + { + this(parent, style, true, true, null); + } + + /** + * Specify a message line so error messages are written to it versus in message dialogs. + * @param msgLine An object implementing ISystemMessageLine. Typically pass "this" for + * your dialog or wizard page, and implement the interface there. + */ + public void setMessageLine(ISystemMessageLine msgLine) + { + this.msgLine = msgLine; + } + /** + * Get the message line specified in setMessageLine. + */ + public ISystemMessageLine getMessageLine() + { + return msgLine; + } + + /** + * Set the system types to restrict what connections the user sees, and what types of + * connections they can create. + * @param systemTypes An array of system type names + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemTypes(String[] systemTypes) + { + dirCombo.setSystemTypes(systemTypes); + } + /** + * Convenience method to restrict to a single system type. + * Same as setSystemTypes(new String[] {systemType}) + * + * @param systemType The name of the system type to restrict to + * + * @see org.eclipse.rse.core.ISystemTypes + */ + public void setSystemType(String systemType) + { + if (systemType == null) + setSystemTypes(null); + else + setSystemTypes(new String[] {systemType}); + } + + /** + * Set a filter string to subset the list by. For example, "A*.java" or "java,class," + */ + public void setFilterString(String filterString) + { + fileProvider.setFilterString(filterString); + folderProvider.setFilterString(filterString); + refresh(); + } + /** + * Get the current filter string being used to subset the list by. + * Will be null unless setFilterString has previously been called. + */ + public String getFilterString() + { + return filterString; + } + + /** + * Return the nested qualified-folder combo widget + */ + public SystemQualifiedRemoteFolderCombo getFolderCombo() + { + return dirCombo; + } + + /** + * Disable/Enable all the child controls. + */ + public void setEnabled(boolean enabled) + { + dirCombo.setEnabled(enabled); + fileSelector.getListTable().setEnabled(enabled); + } + /** + * Set the focus to the combo field + */ + public boolean setFocus() + { + return dirCombo.setFocus(); + } + + /** + * Clear the contents of the file selector widgets + */ + public void clearAll() + { + fileSelector.clearAll(); + enableButtonGroup(false); + } + /** + * Set the root folder from which to populate the widgets + * @param rootFolder The root folder from which to start the tree + */ + public void setRootFolder(IRemoteFile rootFolder) + { + rootElement.setRootFile(rootFolder); + fileSelector.setRoot(rootElement); + enableButtonGroup(true); + } + + /** + * Refesh the contents of the folder and file-selection checkbox viewers + */ + public void refresh() + { + folderProvider.flushCache(); + fileProvider.flushCache(); + fileSelector.refresh(); + } + + /** + * Add a checkstate listener to be called whenever the checked state of + * a remote file is changed. + */ + public void addCheckStateListener(ICheckStateListener l) + { + fileSelector.addCheckStateListener(l); + } + /** + * Remove a checkstate listener + */ + public void removeCheckStateListener(ICheckStateListener l) + { + fileSelector.removeCheckStateListener(l); + } + + /** + * Get the list of selected IRemoteFile objects. + * Will be length 0 if nothing selected + */ + public IRemoteFile[] getSelectedFiles() + { + java.util.List list = fileSelector.getAllCheckedListItems(); + IRemoteFile[] files = new IRemoteFile[list.size()]; + Iterator i = list.iterator(); + int idx = 0; + while (i.hasNext()) + { + files[idx++] = (IRemoteFile)i.next(); + } + return files; + } + + // ----------------------- + // INTERNAL-USE METHODS... + // ----------------------- + /** + * Prepares this composite control and sets the default layout data. + * @param numColumns Number of columns the new group will contain. + */ + protected Composite prepareComposite(int numColumns) + { + Composite composite = this; + //GridLayout + GridLayout layout = new GridLayout(); + layout.numColumns = numColumns; + layout.marginWidth = 0; + layout.marginHeight = 0; + layout.horizontalSpacing = 0; + composite.setLayout(layout); + //GridData + GridData data = new GridData(); + data.verticalAlignment = GridData.FILL; + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; + data.grabExcessVerticalSpace = false; + //data.widthHint = SIZING_SELECTION_WIDGET_WIDTH + 20; + composite.setLayoutData(data); + return composite; + } + + /** + * Create qualified-folder prompt + */ + protected void createFolderPrompt(Composite parent) + { + // connection\folder prompt + dirCombo = new SystemQualifiedRemoteFolderCombo(parent, SWT.NULL, historyKey); + } + + /** + * Create folder and files selection checkbox viewers + */ + protected void createFilesSelectorGroup(Composite parent) + { + // file selector prompt (checkbox tree and checkbox list) + folderProvider = new SystemViewLabelAndContentProvider(true,false); + fileProvider = new SystemViewLabelAndContentProvider(false,true); + rootElement = new RemoteFileRoot(); + fileSelector = new SystemFileTreeAndListGroup(parent, + folderProvider, folderProvider, // tree content and label providers + fileProvider, fileProvider, // list content and label providers + SWT.NULL, SIZING_SELECTION_WIDGET_WIDTH, + SIZING_SELECTION_WIDGET_HEIGHT); + } + /** + * Create three buttons under checkbox viewers + */ + protected void createButtons(Composite parent, boolean showSelectTypes, boolean showSelectAll) + { + Composite buttonComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + if (showSelectTypes && showSelectAll) + layout.numColumns = 3; + else if (showSelectTypes) + layout.numColumns = 1; + else + layout.numColumns = 2; + layout.makeColumnsEqualWidth = true; + buttonComposite.setLayout(layout); + buttonComposite.setLayoutData( + new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL)); + + if (showSelectTypes) + { + selectTypesButton = createPushButton(buttonComposite, SystemResources.RESID_SELECTFILES_SELECTTYPES_BUTTON_ROOT_LABEL, SystemResources.RESID_SELECTFILES_SELECTTYPES_BUTTON_ROOT_TOOLTIP); + addSelectTypesButtonSelectionListener(); + } + if (showSelectAll) + { + selectAllButton = createPushButton(buttonComposite, SystemResources.RESID_SELECTFILES_SELECTALL_BUTTON_ROOT_LABEL); + deselectAllButton = createPushButton(buttonComposite, SystemResources.RESID_SELECTFILES_DESELECTALL_BUTTON_ROOT_TOOLTIP); + addSelectAllButtonSelectionListener(); + addDeselectAllButtonSelectionListener(); + } + + enableButtonGroup(false); + } + protected static Button createPushButton(Composite group, String label, String tooltip) + { + Button button = createPushButton(group,label); + button.setToolTipText(tooltip); + return button; + } + public static Button createPushButton(Composite group, String label) + { + Button button = new Button(group, SWT.PUSH); + button.setText(label); + //button.setText("THIS IS A LONG LABEL. I MEAN, IT IS JUST HUGE!"); + GridData data = new GridData(GridData.FILL_HORIZONTAL); + button.setLayoutData(data); + return button; + } + + + protected void addOurQualifiedFolderSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + clearErrorMessage(); + //clearMessage(); + IRemoteFile selectedFolder = null; + try + { + selectedFolder = dirCombo.getFolder(); + if (selectedFolder == null) + { + //displayErrorMessage("Nothing selected?"); + clearAll(); + } + else + { + //displayMessage("Selected folder exist? " + selectedFolder.exists()); + setRootFolder(selectedFolder); + } + } + catch (Exception exc) + { + String msg = exc.getMessage(); + if ((msg == null) || (msg.length()==0)) + { + msg = "Exception: " + exc.getClass().getName(); + displayExceptionMessage(exc); + } + else + displayErrorMessage(msg); + clearAll(); + } + }; + }; + dirCombo.addSelectionListener(selectionListener); + } + + protected void addSelectTypesButtonSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + handleTypesEditButtonPressed(); + }; + }; + selectTypesButton.addSelectionListener(selectionListener); + } + protected void addSelectAllButtonSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + fileSelector.setAllSelections(true); + }; + }; + selectAllButton.addSelectionListener(selectionListener); + } + protected void addDeselectAllButtonSelectionListener() + { + // Add the button listener + SelectionListener selectionListener = new SelectionAdapter() + { + public void widgetSelected(SelectionEvent event) + { + fileSelector.setAllSelections(false); + }; + }; + deselectAllButton.addSelectionListener(selectionListener); + } + + /** + * Open a registered type selection dialog and note the selections + * in the receivers types-to-export field + */ + protected void handleTypesEditButtonPressed() + { + SystemSelectFileTypesAction typesAction = getSelectTypesAction(); + typesAction.setTypes(selectedTypes); + typesAction.run(); + if (!typesAction.wasCancelled()) + { + selectedTypes = typesAction.getTypes(); + setupSelectionsBasedOnSelectedTypes(); + } + /* + TypeFilteringDialog dialog = + new TypeFilteringDialog(getShell(), selectedTypes); + dialog.open(); + Object[] newSelectedTypes = dialog.getResult(); + if (newSelectedTypes != null) // ie.- did not press Cancel + { + this.selectedTypes = new ArrayList(newSelectedTypes.length); + for (int i = 0; i < newSelectedTypes.length; i++) + { + //System.out.println(newSelectedTypes[i]); + this.selectedTypes.add(newSelectedTypes[i]); + } + setupSelectionsBasedOnSelectedTypes(); + } + */ + } + /** + * Get the action to run when "Select Types..." is pressed by the user + */ + protected SystemSelectFileTypesAction getSelectTypesAction() + { + if (typesAction == null) + typesAction = new SystemSelectFileTypesAction(getShell()); + return typesAction; + } + /** + * Update the tree to only select those elements that match the selected types + */ + protected void setupSelectionsBasedOnSelectedTypes() + { + //BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() + //{ + //public void run() + //{ + Map selectionMap = new Hashtable(); + IRemoteFile[] filesList = getSelectedFiles(); + for (int idx=0;idxtrue if the resource name is suitable for export based + * upon its extension + */ + protected boolean isExportableExtension(String extension) + { + if (selectedTypes == null) // ie.- all extensions are acceptable + return true; + Iterator enumer = selectedTypes.iterator(); + while (enumer.hasNext()) + { + if (extension.equalsIgnoreCase((String)enumer.next())) + return true; + } + return false; + } + + + /** + * Enable or disable the button group. + */ + protected void enableButtonGroup(boolean enable) + { + if (!showSelectTypesButton && !showSelectAllButtons) + return; + if (selectTypesButton != null) + selectTypesButton.setEnabled(enable); + if (selectAllButton != null) + selectAllButton.setEnabled(enable); + if (deselectAllButton != null) + deselectAllButton.setEnabled(enable); + } + + + protected void clearErrorMessage() + { + if (msgLine != null) + msgLine.clearErrorMessage(); + } + + protected void displayErrorMessage(String msgText) + { + if (msgLine != null) + msgLine.setErrorMessage(msgText); + else + SystemMessageDialog.displayErrorMessage(getShell(),msgText); + } + protected void displayErrorMessage(SystemMessage msg) + { + if (msgLine != null) + msgLine.setErrorMessage(msg); + else + SystemMessageDialog.displayErrorMessage(getShell(),msg); + } + protected void displayExceptionMessage(Exception exc) + { + if (msgLine != null) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.MSG_EXCEPTION_OCCURRED); + msg.makeSubstitution(exc); + msgLine.setErrorMessage(msg); + } + else + SystemMessageDialog.displayExceptionMessage(getShell(), exc); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemFileNewConnectionWizardPage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemFileNewConnectionWizardPage.java new file mode 100644 index 00000000000..4aefbf913a7 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemFileNewConnectionWizardPage.java @@ -0,0 +1,232 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.wizards; +import org.eclipse.jface.wizard.IWizard; +import org.eclipse.rse.core.subsystems.ISubSystemConfiguration; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.ui.SystemResources; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.validators.ISystemValidator; +import org.eclipse.rse.ui.validators.ValidatorServerPortInput; +import org.eclipse.rse.ui.wizards.AbstractSystemNewConnectionWizardPage; +import org.eclipse.rse.ui.wizards.AbstractSystemWizardPage; +import org.eclipse.rse.ui.wizards.ISystemWizardPage; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + + + +/** + * A page that prompts for unique universal files information in the New Connection wizard. + * This page appears for remote Unix, Linux and Windows connections but not for iSeries or Local connections. + */ +public class SystemFileNewConnectionWizardPage extends AbstractSystemNewConnectionWizardPage + +{ + + protected Label labelPortPrompt; + protected Text textPort; + protected ISystemValidator portValidator; + protected SystemMessage errorMessage; + protected boolean enablePortSelection = true;//false; // todo: enable in next releaes + + // SEE DEFECTS 43194 AND 42780 + + /** + * Constructor + */ + public SystemFileNewConnectionWizardPage(IWizard wizard, ISubSystemConfiguration parentFactory) + { + //super(wizard, parentFactory); todo: use this when we enable port selection + super(wizard, parentFactory, parentFactory.getId(), + SystemResources.RESID_NEWCONN_SUBSYSTEMPAGE_FILES_TITLE, + SystemResources.RESID_NEWCONN_SUBSYSTEMPAGE_FILES_DESCRIPTION); + if (enablePortSelection) + getPortValidator(); + } + + /** + * Return true if we support port selection yet + */ + public boolean isInformationalOnly() + { + return !enablePortSelection; + } + + /** + * @see AbstractSystemWizardPage#getInitialFocusControl() + */ + protected Control getInitialFocusControl() + { + if (textPort != null) + return textPort; + else + return null; + } + + public void setEnablePortSelection(boolean flag) + { + enablePortSelection = flag; + } + + /** + * Get the port validator. By default returns new ValidatorPortInput + */ + protected ISystemValidator getPortValidator() + { + if (portValidator == null) + portValidator = new ValidatorServerPortInput(); + return portValidator; + } + + /** + * @see AbstractSystemWizardPage#createContents(Composite) + */ + public Control createContents(Composite parent) + { + int nbrColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, nbrColumns); + + + // Instructional verbage + String text = null; + text = SystemResources.RESID_NEWCONN_SUBSYSTEMPAGE_FILES_VERBAGE1; + //, + // the following is default English text to use if the string is not found in the mri" + // "To connect to your remote system, you must first copy and expand the supplied Java server code jar file on that system, and either manually start that server or the supplied daemon. You will find the instructions for this in the Help perspective. "); + boolean border = false; + int span = nbrColumns; + int widthHint = 200; + + SystemWidgetHelpers.createVerbage(composite_prompts, text, span, border, widthHint); + + SystemWidgetHelpers.createSpacerLine(composite_prompts, span, false); + + text = SystemResources.RESID_NEWCONN_SUBSYSTEMPAGE_FILES_VERBAGE2; + //, + // the following is default English text to use if the string is not found in the mri" + // "If you manually start the communications server, you will need to set the port number property for this connection. To do this, expand your newly created connection in the Remote Systems Explorer perspective. Right click on the Files subsystem and select Properties. You can specify the port to match the port you specified or were assigned for the server."); + + SystemWidgetHelpers.createVerbage(composite_prompts, text, span, border, widthHint); + + + // Port prompt + if (enablePortSelection) + { + String labelText = SystemWidgetHelpers.appendColon(SystemResources.RESID_SUBSYSTEM_PORT_LABEL); + labelPortPrompt = SystemWidgetHelpers.createLabel(composite_prompts, labelText); + + textPort = SystemWidgetHelpers.createTextField( + composite_prompts,null,SystemResources.RESID_SUBSYSTEM_PORT_TIP); + textPort.setText("0"); + + textPort.addModifyListener( + new ModifyListener() { + public void modifyText(ModifyEvent e) { + validatePortInput(); + } + } + ); + } + + + + return composite_prompts; + } + + + /** + * Return true if the port is editable for this subsystem + */ + protected boolean isPortEditable() + { + return parentFactory.isPortEditable(); + } + /** + * Return true if the userId is applicable for this subsystem + */ + protected boolean isUserIdApplicable() + { + return parentFactory.supportsUserId(); + } + + /** + * @see ISystemWizardPage#performFinish() + */ + public boolean performFinish() + { + if (textPort == null) + return true; + else + return (validatePortInput()==null); + } + + /** + * Return the user-entered port number + */ + public int getPortNumber() + { + Integer iPort = null; + if (textPort == null) + { + iPort = new Integer(0); + } + else + { + String sPort = textPort.getText().trim(); + try + { + iPort = new Integer(sPort); + } + catch (Exception exc) + { + iPort = new Integer(0); + } + } + return iPort.intValue(); + } + + /** + * Validate port value as it is typed + */ + protected SystemMessage validatePortInput() + { + this.clearErrorMessage(); + errorMessage = getPortValidator().validate(textPort.getText().trim()); + if (errorMessage != null) + setErrorMessage(errorMessage); + setPageComplete(errorMessage==null); + return errorMessage; + } + + /** + * Return true if the page is complete, so to enable Finish. + * Called by wizard framework. + */ + public boolean isPageComplete() + { + if (textPort == null) + return true; + else + return (textPort.getText().trim().length()>0); + } + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFileWizard.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFileWizard.java new file mode 100644 index 00000000000..ea94235b10a --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFileWizard.java @@ -0,0 +1,388 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.wizards; + +import java.util.Vector; + +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.core.subsystems.ISubSystem; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.ISystemFilterReference; +import org.eclipse.rse.model.ISystemRegistry; +import org.eclipse.rse.model.ISystemRemoteChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeEvents; +import org.eclipse.rse.model.ISystemResourceChangeListener; +import org.eclipse.rse.model.SystemResourceChangeEvent; +import org.eclipse.rse.services.clientserver.archiveutils.ArchiveHandlerManager; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.model.RemoteFileFilterString; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystemConfiguration; +import org.eclipse.rse.subsystems.files.core.subsystems.IVirtualRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.view.ISystemTree; +import org.eclipse.rse.ui.wizards.AbstractSystemWizard; + + +public class SystemNewFileWizard + extends AbstractSystemWizard + implements ISystemMessages +{ + + private SystemNewFileWizardMainPage mainPage; + //protected IRemoteFile parentFolder; + //protected IStructuredSelection selection; + + private static final String CLASSNAME = "SystemNewFileWizard"; + + /** + * Constructor + */ + public SystemNewFileWizard() + { + super(FileResources.RESID_NEWFILE_TITLE, +// SystemPlugin.getDefault().getImageDescriptorFromIDE("wizban/newfile_wiz.gif") + // SystemPlugin.getDefault().getImageDescriptor("wizban/newfile_wiz.gif") + + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFILEWIZARD_ID)); + } + + /** + * Creates the wizard pages. + * This method is an override from the parent Wizard class. + */ + public void addPages() + { + try { + mainPage = createMainPage(); + addPage((WizardPage)mainPage); + //super.addPages(); + } catch (Exception exc) + { + SystemBasePlugin.logError("New File: Error in createPages: ",exc); + } + } + + /** + * Creates the wizard's main page. + * This method is an override from the parent class. + */ + protected SystemNewFileWizardMainPage createMainPage() + { + IRemoteFile[] parentFolders = null; + SystemMessage errMsg = null; + try { + parentFolders = getParentFolders(); + } catch (SystemMessageException exc) + { + // hmm, this means there are no valid folders so we are in error mode. + errMsg = exc.getSystemMessage(); + } + mainPage = new SystemNewFileWizardMainPage(this, parentFolders); + if (errMsg != null) + mainPage.setErrorMessage(errMsg); + return mainPage; + } + + /** + * Completes processing of the wizard. If this + * method returns true, the wizard will close; + * otherwise, it will stay active. + * This method is an override from the parent Wizard class. + * + * @return whether the wizard finished successfully + */ + public boolean performFinish() + { + boolean ok = true; + if (mainPage.performFinish()) + { + SystemMessage msg = null; + IRemoteFile parentFolder = mainPage.getParentFolder(); + String name = mainPage.getfileName(); + String absName = getNewAbsoluteName(parentFolder, name); + IRemoteFileSubSystem rfss = parentFolder.getParentRemoteFileSubSystem(); + if (!parentFolder.exists()) + { + /* Be nice to do this someday... + msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_FOLDER_NOTFOUND_WANTTOCREATE); + msg.makeSubstitution(parentFolder.getAbsolutePath()); + SystemMessageDialog msgDlg = new SystemMessageDialog(getShell(), msg); + if (msgDlg.openQuestionNoException()) + { + try { + parentFolder = rfss.createFolder(parentFolder); + } + catch (RemoteFileIOException exc) + { + SystemPlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileIOException " ); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED_EXIST)).makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + catch (RemoteFileSecurityException exc) + { + SystemPlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileSecurityException " ); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED)).makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + } + else + */ + { + msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_FOLDER_NOTFOUND); + msg.makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + } + // if input is a filter, then we need to test if the new file will meet the filtering criteria of + // that filter... + if (isInputAFilter()) + { + if (!meetsFilterCriteria(getSelectedFilterReference(), parentFolder, absName)) + return false; + } + // ok, proceed with actual creation... + IRemoteFile newFile = null; + try { + IRemoteFile newFilePath = rfss.getRemoteFileObject(absName); + newFile = rfss.createFile(newFilePath); + } catch (RemoteFileIOException exc ) { + SystemBasePlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote file "+ absName + " failed with RemoteFileIOException " ); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FILE_FAILED_EXIST)).makeSubstitution(absName); + mainPage.setMessage(msg); + ok = false; +//DY } catch (Exception RemoteFileSecurityException) { + } catch (RemoteFileSecurityException e) { + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FILE_FAILED)).makeSubstitution(absName); + SystemBasePlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote file "+ absName + " failed with RemoteFileSecurityException "); + //SystemMessage.displayErrorMessage(SystemMessage.getDefaultShell(), msg); + mainPage.setMessage(msg); + ok = false; + } catch (SystemMessageException e) { + SystemBasePlugin.logError(CLASSNAME+ ":", e); + mainPage.setMessage(e.getSystemMessage()); + ok = false; + } + + // return ok; + if (ok) + updateGUI(parentFolder, newFile, getViewer(), isInputAFilter(), getSelectedFilterReference()); + + } + else + ok = false; + + + return ok; + } + + /** + * Create a new absolute name from the parent folder, and the new name + */ + protected static String getNewAbsoluteName(IRemoteFile parentFolder, String newName) + { + String newAbsName = null; + char sep = parentFolder.getSeparatorChar(); + String parentFolderPath = parentFolder.getAbsolutePath(); + + // hack by Mike to allow virtual files and folders. + if (parentFolder instanceof IVirtualRemoteFile) + { + sep = '/'; + } + else if (parentFolder.isArchive()) + { + sep = '/'; + parentFolderPath = parentFolderPath + ArchiveHandlerManager.VIRTUAL_SEPARATOR; + } + + // hack by Phil to fix bug when trying to create file inside root "/"... it + // tried to create "//file.ext". + if ((parentFolderPath.length()==1) && (parentFolderPath.charAt(0)=='/') && + (parentFolderPath.charAt(0)==sep)) + newAbsName = sep + newName; + else + newAbsName = parentFolderPath + sep + newName; + return newAbsName; + } + + /** + * Test if the new file/folder will meet the filtering criteria of the selected filter + */ + protected boolean meetsFilterCriteria(ISystemFilterReference selectedFilterRef, IRemoteFile parentFolder, String newAbsName) + { + boolean meets = false; + IRemoteFileSubSystem parentSubSystem = (IRemoteFileSubSystem)selectedFilterRef.getSubSystem(); + meets = parentSubSystem.doesFilterMatch(selectedFilterRef.getReferencedFilter(),newAbsName); + if (!meets) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_CREATE_RESOURCE_NOTVISIBLE); + SystemMessageDialog msgDlg = new SystemMessageDialog(getShell(), msg); + if (msgDlg.openQuestionNoException()) // ask user if they want to proceed + meets = true; // they do, so pretend it meets the criteria + } + return meets; + } + + + /** + * Called after all a successful create operation to update the GUI in an intuitive way: + *

    + */ + protected static void updateGUI(IRemoteFile parentFolder, IRemoteFile newFileOrFolder, Viewer viewer, + boolean isInputAFilter, ISystemFilterReference selectedFilterRef) + { + ISystemRegistry sr = SystemPlugin.getTheSystemRegistry(); + if (selectedFilterRef != null) + { + selectedFilterRef.markStale(true); + } + + // step 0: refresh all affected filters... + ISubSystem fileSS = newFileOrFolder.getParentRemoteFileSubSystem(); + sr.fireRemoteResourceChangeEvent(ISystemRemoteChangeEvents.SYSTEM_REMOTE_RESOURCE_CREATED, newFileOrFolder, parentFolder, fileSS, null, viewer); + + /* + // step 1: refresh all occurrences of the parent folder + SystemResourceChangeEvent event = new SystemResourceChangeEvent( + parentFolder,ISystemResourceChangeEvent.EVENT_REFRESH_REMOTE, newFileOrFolder); + event.setOriginatingViewer(viewer); // this allows only the originating view to select the new file + sr.fireEvent(event); + */ + // step 2: if the selected input is a filter, vs a folder, refresh that filter... + if (isInputAFilter && (viewer instanceof ISystemTree)) + { + // get originating tree view + ISystemTree treeViewer = (ISystemTree)viewer; + // select new file/folder in this view only, and expand filter if not already expanded... + sr.fireEvent((ISystemResourceChangeListener)treeViewer, + new SystemResourceChangeEvent(newFileOrFolder,ISystemResourceChangeEvents.EVENT_SELECT_REMOTE, selectedFilterRef)); + } + + } + + /** + * Return true if input is a system filter reference, versus a folder + */ + protected boolean isInputAFilter() + { + return (getInputObject() instanceof ISystemFilterReference); + } + /** + * Get the selected filter, or null if a filter is not selected. + */ + protected ISystemFilterReference getSelectedFilterReference() + { + if (isInputAFilter()) + return (ISystemFilterReference)getInputObject(); + else + return null; + } + + /** + * Deduce the parent remote folder to hold the new folder, by examining the current selection + */ + protected IRemoteFile[] getParentFolders() throws SystemMessageException + { + Object input = getInputObject(); + if (input instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)input}; + else if (input instanceof ISystemFilterReference) + return getParentFolders((ISystemFilterReference)input); + else + return null; + } + + /** + * Given a filter reference, return a list of all the unique root folders, one per filter string at most. + * If all of these fail to resolve, an exception is thrown. If some fail to resolve, they are just ignored. + */ + public static IRemoteFile[] getParentFolders(ISystemFilterReference filterRef) throws SystemMessageException + { + ISystemFilter filter = filterRef.getReferencedFilter(); + IRemoteFileSubSystem parentSubSystem = (IRemoteFileSubSystem)filterRef.getSubSystem(); + IRemoteFileSubSystemConfiguration parentFactory = parentSubSystem.getParentRemoteFileSubSystemFactory(); + String[] filterStrings = filter.getFilterStrings(); + RemoteFileFilterString rffs = null; + Vector v = new Vector(); + Vector uniqueNames = new Vector(); + IRemoteFile folder = null; + String pathName = null; + SystemMessageException lastExc = null; + for (int idx=0; idx + *
  4. New File name + * + */ + +public class SystemNewFileWizardMainPage + extends AbstractSystemWizardPage + implements ISystemMessages +{ + + protected String fileNameStr; + protected Text folderName, connectionName, fileName; + protected Combo folderNames; + protected SystemMessage errorMessage; + protected ISystemValidator nameValidator; + protected IRemoteFile[] parentFolders; + protected ISystemMessageLine msgLine; + public String [] allnames; + + /** + * Constructor. + */ + public SystemNewFileWizardMainPage(Wizard wizard, IRemoteFile[] parentFolders) + { + super(wizard, "NewFile", + FileResources.RESID_NEWFILE_PAGE1_TITLE, FileResources.RESID_NEWFILE_PAGE1_DESCRIPTION); + this.parentFolders = parentFolders; + } + + /** + * CreateContents is the one method that must be overridden from the parent class. + * In this method, we populate an SWT container with widgets and return the container + * to the caller (JFace). This is used as the contents of this page. + */ + public Control createContents(Composite parent) + { + + int nbrColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, nbrColumns); + + // Connection name + connectionName = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, FileResources.RESID_NEWFILE_CONNECTIONNAME_LABEL, FileResources.RESID_NEWFILE_CONNECTIONNAME_TIP); + + //labelConnectionName. + + // FolderName + if ((parentFolders == null) || (parentFolders.length == 1)) + folderName = SystemWidgetHelpers.createLabeledTextField(composite_prompts,null, FileResources.RESID_NEWFILE_FOLDER_LABEL, FileResources.RESID_NEWFILE_FOLDER_TIP); + else + folderNames = SystemWidgetHelpers.createLabeledReadonlyCombo(composite_prompts, null, FileResources.RESID_NEWFILE_FOLDER_LABEL, FileResources.RESID_NEWFILE_FOLDER_TIP); + + // File Name + fileName = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, FileResources.RESID_NEWFILE_NAME_LABEL, FileResources.RESID_NEWFILE_NAME_TOOLTIP); + + initializeInput(); + + fileName.addModifyListener( + new ModifyListener() { + public void modifyText(ModifyEvent e) { + validateNameInput(); + } + } + ); + + SystemWidgetHelpers.setCompositeHelp(composite_prompts, SystemPlugin.HELPPREFIX+NEW_FILE_WIZARD); + + return composite_prompts; + + } + + /** + * Return the Control to be given initial focus. + * Override from parent. Return control to be given initial focus. + */ + protected Control getInitialFocusControl() + { + return fileName; + } + + /** + * Init values using input data + */ + protected void initializeInput() + { + connectionName.setEditable(false); + nameValidator = new ValidatorFileName(); + + if ((parentFolders == null) || (parentFolders.length == 0)) + { + folderName.setEditable(false); + fileName.setEditable(false); // why do we do this?? + setPageComplete(false); + return; + } + IRemoteFileSubSystem rfss = parentFolders[0].getParentRemoteFileSubSystem(); + connectionName.setText(rfss.getHostAliasName()); + connectionName.setToolTipText((rfss.getHost()).getHostName()); + + if (folderName != null) + { + folderName.setText(parentFolders[0].getAbsolutePath()); + folderName.setEditable(false); + } + else + { + String[] names = new String[parentFolders.length]; + for (int idx=0; idxISystemValidator object. + * If the ISystemValidator reports an error the error message is displayed + * in the Dialog's message line. + */ + protected SystemMessage validateNameInput() + { + errorMessage = null; + this.clearErrorMessage(); + // this.setDescription(SystemResources.RESID_NEWFILE_PAGE1_DESCRIPTION)); + if (nameValidator != null) + errorMessage= nameValidator.validate(fileName.getText()); + if (errorMessage != null) + setErrorMessage(errorMessage); + setPageComplete(errorMessage==null); + return errorMessage; + } + + /** + * Completes processing of the wizard. If this + * method returns true, the wizard will close; + * otherwise, it will stay active. + * This method is an override from the parent Wizard class. + * + * @return whether the wizard finished successfully + */ + public boolean performFinish() + { + + return true; + } + + // --------------------------------- // + // METHODS FOR EXTRACTING USER DATA ... + // --------------------------------- // + /** + * Return user-entered new file name. + * Call this after finish ends successfully. + */ + public String getfileName() + { + return fileName.getText(); + } + /** + * Return the parent folder selected by the user + */ + public IRemoteFile getParentFolder() + { + if (folderName != null) + return parentFolders[0]; + else + { + int selIdx = folderNames.getSelectionIndex(); + if (selIdx == -1) + selIdx = 0; + return parentFolders[selIdx]; + } + } + /** + * Return true if the page is complete, so to enable Finish. + * Called by wizard framework. + */ + public boolean isPageComplete() + { + return (errorMessage==null) && (fileName.getText().trim().length()>0); + } + + +} \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizard.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizard.java new file mode 100644 index 00000000000..e5107eac930 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizard.java @@ -0,0 +1,274 @@ +/******************************************************************************** + * Copyright (c) 2000, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.wizards; + +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.rse.core.SystemBasePlugin; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.filters.ISystemFilter; +import org.eclipse.rse.filters.ISystemFilterReference; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.services.clientserver.messages.SystemMessageException; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileIOException; +import org.eclipse.rse.subsystems.files.core.subsystems.RemoteFileSecurityException; +import org.eclipse.rse.ui.ISystemIconConstants; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.messages.SystemMessageDialog; +import org.eclipse.rse.ui.wizards.AbstractSystemWizard; + + +public class SystemNewFolderWizard + extends AbstractSystemWizard + implements ISystemMessages +{ + + private SystemNewFolderWizardMainPage mainPage; + //protected IRemoteFile myObject; + //protected IStructuredSelection selection; + + private static final String CLASSNAME = "SystemNewFolderWizard"; + + /** + * Constructor + */ + public SystemNewFolderWizard() + { + super(FileResources.RESID_NEWFOLDER_TITLE, + // SystemPlugin.getDefault().getImageDescriptorFromIDE("wizban/newfolder_wiz.gif") + SystemPlugin.getDefault().getImageDescriptor(ISystemIconConstants.ICON_SYSTEM_NEWFOLDERWIZARD_ID) + ); + } + + /** + * Creates the wizard pages. + * This method is an override from the parent AbstractSystemWizard class. + */ + public void addPages() + { + try { + mainPage = createMainPage(); + addPage((WizardPage)mainPage); + //super.addPages(); + } catch (Exception exc) + { + SystemBasePlugin.logError("New File: Error in createPages: ",exc); + } + } + + /** + * Creates the wizard's main page. + * This method is an override from the parent class. + */ + protected SystemNewFolderWizardMainPage createMainPage() + { + IRemoteFile[] parentFolders = null; + SystemMessage errMsg = null; + try { + parentFolders = getParentFolders(); + } catch (SystemMessageException exc) + { + // hmm, this means there are no valid folders so we are in error mode. + errMsg = exc.getSystemMessage(); + } + mainPage = new SystemNewFolderWizardMainPage(this, parentFolders); + if (errMsg != null) + mainPage.setErrorMessage(errMsg); + return mainPage; + } + + /** + * Completes processing of the wizard. If this + * method returns true, the wizard will close; + * otherwise, it will stay active. + * This method is an override from the parent Wizard class. + * + * @return whether the wizard finished successfully + */ + public boolean performFinish() + { + boolean ok = true; + if (mainPage.performFinish()) + { + SystemMessage msg = null; + IRemoteFile parentFolder = mainPage.getParentFolder(); + String name = mainPage.getfolderName(); + String absName = SystemNewFileWizard.getNewAbsoluteName(parentFolder, name); + IRemoteFileSubSystem rfss = parentFolder.getParentRemoteFileSubSystem(); + if (!parentFolder.exists()) + { + /* Be nice to do this someday... + msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_FOLDER_NOTFOUND_WANTTOCREATE); + msg.makeSubstitution(parentFolder.getAbsolutePath()); + SystemMessageDialog msgDlg = new SystemMessageDialog(getShell(), msg); + if (msgDlg.openQuestionNoException()) + { + try { + parentFolder = rfss.createFolder(parentFolder); + } + catch (RemoteFileIOException exc) + { + SystemPlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileIOException " ); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED_EXIST)).makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + catch (RemoteFileSecurityException exc) + { + SystemPlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileSecurityException " ); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED)).makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + } + else + */ + { + msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_FOLDER_NOTFOUND); + msg.makeSubstitution(parentFolder.getAbsolutePath()); + mainPage.setMessage(msg); + return false; + } + } + // if input is a filter, then we need to test if the new file will meet the filtering criteria of + // that filter... + if (isInputAFilter()) + { + if (!meetsFilterCriteria(getSelectedFilterReference(), parentFolder, absName)) + return false; + } + IRemoteFile newFolder = null; + //IRemoteFile newFolderPath = null; + try { + IRemoteFile newFolderPath = rfss.getRemoteFileObject(absName); + newFolder = rfss.createFolder(newFolderPath); + } catch (RemoteFileIOException exc ) { + SystemBasePlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileIOException " ); + if (exc.getRemoteException() instanceof SystemMessageException) + { + msg = ((SystemMessageException)exc.getRemoteException()).getSystemMessage(); + } + else + { + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED_EXIST)).makeSubstitution(absName); + } + mainPage.setMessage(msg); + ok = false; +// DY } catch (Exception RemoteFileSecurityException) { + } catch (RemoteFileSecurityException e) { + SystemBasePlugin.logDebugMessage(CLASSNAME+ ":", " Creating remote folder "+ absName + " failed with RemoteFileSecurityException "); + msg = (SystemPlugin.getPluginMessage(FILEMSG_CREATE_FOLDER_FAILED)).makeSubstitution(absName); + //SystemMessage.displayErrorMessage(SystemMessage.getDefaultShell(), msg); + mainPage.setMessage(msg); + ok = false; + } catch (SystemMessageException e) { + SystemBasePlugin.logError(CLASSNAME+ ":", e); + mainPage.setMessage(e.getSystemMessage()); + ok = false; + } + + if (ok) + SystemNewFileWizard.updateGUI(parentFolder, newFolder, getViewer(), isInputAFilter(), getSelectedFilterReference()); + + } + else + ok = false; + return ok; + } + /** + * Test if the new file/folder will meet the filtering criteria of the selected filter. + * For folders, since we do not support subsetting by folder names, we simply need to test if any + * of the filter strings in the filter has showSubDirs() set to true. + */ + protected boolean meetsFilterCriteria(ISystemFilterReference selectedFilterRef, IRemoteFile parentFolder, String newAbsName) + { + boolean meets = false; + ISystemFilter filter = selectedFilterRef.getReferencedFilter(); + String[] strings = filter.getFilterStrings(); + if (strings != null) + { + for (int idx=0; !meets && (idx 0 && !filterString.startsWith(parentFolder.getAbsolutePath())) + { + if (!filterString.equals("./*")) //DKM - ./ will always meet + { + meets = false; + } + else + { + meets = true; + } + } + else + { + meets = true; + } + } + } + } + if (!meets) + { + SystemMessage msg = SystemPlugin.getPluginMessage(ISystemMessages.FILEMSG_CREATE_RESOURCE_NOTVISIBLE); + SystemMessageDialog msgDlg = new SystemMessageDialog(getShell(), msg); + if (msgDlg.openQuestionNoException()) // ask user if they want to proceed + meets = true; // they do, so pretend it meets the criteria + } + return meets; + } + + /** + * Return true if input is a system filter reference, versus a folder + */ + protected boolean isInputAFilter() + { + return (getInputObject() instanceof ISystemFilterReference); + } + /** + * Get the selected filter, or null if a filter is not selected. + */ + protected ISystemFilterReference getSelectedFilterReference() + { + if (isInputAFilter()) + return (ISystemFilterReference)getInputObject(); + else + return null; + } + + /** + * Deduce the parent remote folder to hold the new folder, by examining the current selection + */ + protected IRemoteFile[] getParentFolders() throws SystemMessageException + { + Object input = getInputObject(); + if (input instanceof IRemoteFile) + return new IRemoteFile[] {(IRemoteFile)input}; + else if (input instanceof ISystemFilterReference) + { + return SystemNewFileWizard.getParentFolders((ISystemFilterReference)input); + } + else + return null; + } + + +} // end class \ No newline at end of file diff --git a/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizardMainPage.java b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizardMainPage.java new file mode 100644 index 00000000000..2e979356fc2 --- /dev/null +++ b/rse/plugins/org.eclipse.rse.files.ui/src/org/eclipse/rse/files/ui/wizards/SystemNewFolderWizardMainPage.java @@ -0,0 +1,226 @@ +/******************************************************************************** + * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved. + * This program and the accompanying materials are made available under the terms + * of the Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Initial Contributors: + * The following IBM employees contributed to the Remote System Explorer + * component that contains this file: David McKnight, Kushal Munir, + * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, + * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley. + * + * Contributors: + * {Name} (company) - description of contribution. + ********************************************************************************/ + +package org.eclipse.rse.files.ui.wizards; + +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.rse.core.SystemPlugin; +import org.eclipse.rse.files.ui.FileResources; +import org.eclipse.rse.services.clientserver.messages.SystemMessage; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; +import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFileSubSystem; +import org.eclipse.rse.ui.ISystemMessages; +import org.eclipse.rse.ui.SystemWidgetHelpers; +import org.eclipse.rse.ui.messages.ISystemMessageLine; +import org.eclipse.rse.ui.validators.ISystemValidator; +import org.eclipse.rse.ui.validators.ValidatorFolderName; +import org.eclipse.rse.ui.validators.ValidatorUniqueString; +import org.eclipse.rse.ui.wizards.AbstractSystemWizardPage; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Text; + + +/** + * Default main page of the "New Folder" wizard. + * This page asks for the following information: + *
      + *
    • New File name + *
    + */ + +public class SystemNewFolderWizardMainPage + extends AbstractSystemWizardPage + implements ISystemMessages +{ + + protected String fileNameStr; + protected Text folderName, connectionName, newfolderName; + protected Combo folderNames; + protected SystemMessage errorMessage; + protected ISystemValidator nameValidator; + protected IRemoteFile[] parentFolders; + protected ISystemMessageLine msgLine; + public String [] allnames; + + /** + * Constructor. + */ + public SystemNewFolderWizardMainPage(Wizard wizard, IRemoteFile[] parentFolders) + { + super(wizard, "NewFolder", + FileResources.RESID_NEWFOLDER_PAGE1_TITLE, + FileResources.RESID_NEWFOLDER_PAGE1_DESCRIPTION); + // nameValidator = new ValidatorProfileName(SystemPlugin.getTheSystemRegistry().getAllSystemProfileNamesVector()); + nameValidator = new ValidatorUniqueString(allnames, true); + this.parentFolders = parentFolders; + } + + /** + * CreateContents is the one method that must be overridden from the parent class. + * In this method, we populate an SWT container with widgets and return the container + * to the caller (JFace). This is used as the contents of this page. + */ + public Control createContents(Composite parent) + { + + int nbrColumns = 2; + Composite composite_prompts = SystemWidgetHelpers.createComposite(parent, nbrColumns); + + // Connection name + connectionName = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, FileResources.RESID_NEWFOLDER_CONNECTIONNAME_LABEL, FileResources.RESID_NEWFOLDER_CONNECTIONNAME_TIP); + + //labelConnectionName. + + // FolderName + if (parentFolders.length == 1) + folderName = SystemWidgetHelpers.createLabeledTextField(composite_prompts,null, FileResources.RESID_NEWFOLDER_FOLDER_LABEL, FileResources.RESID_NEWFOLDER_FOLDER_TIP); + else + folderNames = SystemWidgetHelpers.createLabeledReadonlyCombo(composite_prompts, null, FileResources.RESID_NEWFOLDER_FOLDER_LABEL, FileResources.RESID_NEWFOLDER_FOLDER_TIP); + + // New Folder Name + newfolderName = SystemWidgetHelpers.createLabeledTextField(composite_prompts, null, FileResources.RESID_NEWFOLDER_NAME_LABEL, FileResources.RESID_NEWFOLDER_NAME_TOOLTIP); + + initializeInput(); + + newfolderName.addModifyListener( + new ModifyListener() { + public void modifyText(ModifyEvent e) { + validateNameInput(); + } + } + ); + + SystemWidgetHelpers.setCompositeHelp(composite_prompts, SystemPlugin.HELPPREFIX+NEW_FOLDER_WIZARD); + + return composite_prompts; + + } + + /** + * Return the Control to be given initial focus. + * Override from parent. Return control to be given initial focus. + */ + protected Control getInitialFocusControl() + { + return newfolderName; + } + + /** + * Init values using input data + */ + protected void initializeInput() + { + connectionName.setEditable(false); + nameValidator = new ValidatorFolderName(); + if (parentFolders == null) + { + folderName.setEditable(false); + newfolderName.setEditable(false); + setPageComplete(false); + return; + } + IRemoteFileSubSystem rfss = parentFolders[0].getParentRemoteFileSubSystem(); + connectionName.setText(rfss.getHostAliasName()); + connectionName.setToolTipText((rfss.getHost()).getHostName()); + + if (folderName != null) + { + folderName.setText(parentFolders[0].getAbsolutePath()); + folderName.setEditable(false); + } + else + { + String[] names = new String[parentFolders.length]; + for (int idx=0; idxISystemValidator object. + * If the ISystemValidator reports an error the error message is displayed + * in the Dialog's message line. + * + */ + protected SystemMessage validateNameInput() + { + errorMessage = null; + this.clearErrorMessage(); + // this.setDescription(SystemResources.RESID_NEWFILE_PAGE1_DESCRIPTION)); + if (nameValidator != null) + errorMessage= nameValidator.validate(newfolderName.getText()); + if (errorMessage != null) + setErrorMessage(errorMessage); + setPageComplete(errorMessage==null); + return errorMessage; + } + + /** + * Completes processing of the wizard. If this + * method returns true, the wizard will close; + * otherwise, it will stay active. + * This method is an override from the parent Wizard class. + * + * @return whether the wizard finished successfully + */ + public boolean performFinish() + { + return true; + } + + // --------------------------------- // + // METHODS FOR EXTRACTING USER DATA ... + // --------------------------------- // + /** + * Return user-entered new file name. + * Call this after finish ends successfully. + */ + public String getfolderName() + { + return newfolderName.getText(); + } + /** + * Return the parent folder selected by the user + */ + public IRemoteFile getParentFolder() + { + if (folderName != null) + return parentFolders[0]; + else + { + int selIdx = folderNames.getSelectionIndex(); + if (selIdx == -1) + selIdx = 0; + return parentFolders[selIdx]; + } + } + /** + * Return true if the page is complete, so to enable Finish. + * Called by wizard framework. + */ + public boolean isPageComplete() + { + return (errorMessage==null) && (newfolderName.getText().trim().length()>0); + } + +} \ No newline at end of file