From: robekras Date: Sun, 25 Nov 2012 16:58:12 +0000 (+0100) Subject: 1) Moved net.sourceforge.phpeclipse.ui\src\net\sourceforge\phpdt back to net.sourcefo... X-Git-Url: http://secure.phpeclipse.com 1) Moved net.sourceforge.phpeclipse.ui\src\net\sourceforge\phpdt back to net.sourceforge.phpeclipse\src\net\sourceforge\phpdt. 2) Modified PHP parser for PHP 5.3. Signed-off-by: robekras --- diff --git a/net.sourceforge.phpeclipse.core/.settings/org.eclipse.jdt.core.prefs b/net.sourceforge.phpeclipse.core/.settings/org.eclipse.jdt.core.prefs index 9d630b4..ccf17fb 100644 --- a/net.sourceforge.phpeclipse.core/.settings/org.eclipse.jdt.core.prefs +++ b/net.sourceforge.phpeclipse.core/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,12 @@ -#Fri Sep 07 14:46:23 PDT 2007 +#Tue Jan 17 21:13:09 CET 2012 eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/net.sourceforge.phpeclipse.core/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.core/META-INF/MANIFEST.MF index 4d6f20c..20ada3f 100644 --- a/net.sourceforge.phpeclipse.core/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPeclipse Web Development Tools Core Bundle-SymbolicName: net.sourceforge.phpeclipse.core -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: webcore.jar Bundle-Activator: net.sourceforge.phpeclipse.core.WebCore Bundle-Vendor: PHPEclipse project team @@ -12,4 +12,3 @@ Export-Package: net.sourceforge.phpeclipse.core, Require-Bundle: org.eclipse.core.runtime, org.eclipse.text Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 diff --git a/net.sourceforge.phpeclipse.debug.core/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.debug.core/META-INF/MANIFEST.MF index 80af959..5bb66f3 100644 --- a/net.sourceforge.phpeclipse.debug.core/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.debug.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse DBG Core Bundle-SymbolicName: net.sourceforge.phpeclipse.debug.core; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: core.jar Bundle-Activator: net.sourceforge.phpdt.internal.debug.core.PHPDebugCorePlugin Bundle-Vendor: PHPEclipse project team @@ -14,6 +14,7 @@ Export-Package: net.sourceforge.phpdt.debug.core, net.sourceforge.phpdt.internal.debug.core.watch;x-internal:=true Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, + org.eclipse.core.resources, org.eclipse.debug.core, net.sourceforge.phpeclipse Bundle-RequiredExecutionEnvironment: J2SE-1.4 diff --git a/net.sourceforge.phpeclipse.debug.feature/feature.xml b/net.sourceforge.phpeclipse.debug.feature/feature.xml index 89b90a4..fec736c 100644 --- a/net.sourceforge.phpeclipse.debug.feature/feature.xml +++ b/net.sourceforge.phpeclipse.debug.feature/feature.xml @@ -2,7 +2,7 @@ @@ -237,18 +237,18 @@ litigation. id="net.sourceforge.phpeclipse.debug.core" download-size="0" install-size="0" - version="0.0.0"/> + version="1.2.10.qualifier"/> + version="1.2.10.qualifier"/> + version="1.2.10.qualifier"/> diff --git a/net.sourceforge.phpeclipse.debug.ui/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.debug.ui/META-INF/MANIFEST.MF index 9f6b68b..2744f7f 100644 --- a/net.sourceforge.phpeclipse.debug.ui/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.debug.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse DBG Debug Bundle-SymbolicName: net.sourceforge.phpeclipse.debug.ui; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: debug.jar Bundle-Activator: net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiPlugin Bundle-Vendor: PHPEclipse project team @@ -18,12 +18,13 @@ Require-Bundle: org.eclipse.ui.ide, org.eclipse.ui.workbench.texteditor, org.eclipse.ui.editors, org.eclipse.core.runtime, + org.eclipse.core.resources, org.eclipse.ui, + org.eclipse.debug.core, org.eclipse.debug.ui, net.sourceforge.phpeclipse.debug.core, net.sourceforge.phpeclipse.launching, net.sourceforge.phpeclipse, net.sourceforge.phpeclipse.ui Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Import-Package: net.sourceforge.phpeclipse.xdebug.php.model diff --git a/net.sourceforge.phpeclipse.externaltools/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.externaltools/META-INF/MANIFEST.MF index 4586d82..d140d31 100644 --- a/net.sourceforge.phpeclipse.externaltools/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.externaltools/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHP ExternalTools Plug-in Bundle-SymbolicName: net.sourceforge.phpeclipse.externaltools; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: externaltools.jar Bundle-Activator: net.sourceforge.phpeclipse.externaltools.ExternalToolsPlugin Bundle-Vendor: PHPEclipse project team @@ -24,10 +24,10 @@ Require-Bundle: org.eclipse.ui, org.eclipse.ui.console, org.eclipse.ui.ide, org.eclipse.ui.editors, + org.eclipse.core.resources, org.eclipse.core.runtime, org.eclipse.debug.ui, org.eclipse.ui.externaltools, net.sourceforge.phpeclipse.ui -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy diff --git a/net.sourceforge.phpeclipse.help/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.help/META-INF/MANIFEST.MF index 981e9fb..9b14286 100644 --- a/net.sourceforge.phpeclipse.help/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.help/META-INF/MANIFEST.MF @@ -2,5 +2,5 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse Help Plug-in Bundle-SymbolicName: net.sourceforge.phpeclipse.help; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-Vendor: PHPEclipse Team diff --git a/net.sourceforge.phpeclipse.launching/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.launching/META-INF/MANIFEST.MF index 378796f..8a880da 100644 --- a/net.sourceforge.phpeclipse.launching/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.launching/META-INF/MANIFEST.MF @@ -2,19 +2,21 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse launching Bundle-SymbolicName: net.sourceforge.phpeclipse.launching; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: launch.jar Bundle-Activator: net.sourceforge.phpdt.internal.launching.PHPLaunchingPlugin Bundle-Vendor: PHPEclipse project team Bundle-Localization: plugin Export-Package: net.sourceforge.phpdt.internal.launching;x-internal:=true Require-Bundle: org.eclipse.core.runtime, + org.eclipse.core.resources, org.eclipse.ui, + org.eclipse.debug.core, org.eclipse.jface.text, + org.eclipse.ui.workbench.texteditor, net.sourceforge.phpeclipse, net.sourceforge.phpeclipse.debug.core, org.eclipse.debug.ui, net.sourceforge.phpeclipse.ui, org.eclipse.ui.ide -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy diff --git a/net.sourceforge.phpeclipse.phphelp/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.phphelp/META-INF/MANIFEST.MF index 3ac305f..cf59fc4 100644 --- a/net.sourceforge.phpeclipse.phphelp/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.phphelp/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse Help Manual Bundle-SymbolicName: net.sourceforge.phpeclipse.phphelp; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: phphelp.jar Bundle-Activator: net.sourceforge.phpdt.phphelp.PHPHelpPlugin Bundle-Vendor: PHPEclipse Development Team @@ -21,5 +21,7 @@ Require-Bundle: org.eclipse.core.runtime, org.eclipse.ui.workbench.texteditor, net.sourceforge.phpeclipse.ui;bundle-version="0.0.0" Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 -Import-Package: org.eclipse.ui.texteditor +Import-Package: net.sourceforge.phpdt.internal.ui.viewsupport, + net.sourceforge.phpeclipse.phpeditor, + net.sourceforge.phpeclipse.phpeditor.php, + org.eclipse.ui.texteditor diff --git a/net.sourceforge.phpeclipse.phpmanual.htmlparser/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.phpmanual.htmlparser/META-INF/MANIFEST.MF index 33a8834..c470b01 100644 --- a/net.sourceforge.phpeclipse.phpmanual.htmlparser/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.phpmanual.htmlparser/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Htmlparser Plug-in Bundle-SymbolicName: net.sourceforge.phpeclipse.phpmanual.htmlparser -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: filterbuilder.jar, htmllexer.jar, htmlparser.jar, diff --git a/net.sourceforge.phpeclipse.phpmanual/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.phpmanual/META-INF/MANIFEST.MF index fc55542..b0e8205 100644 --- a/net.sourceforge.phpeclipse.phpmanual/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.phpmanual/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse Manual Bundle-SymbolicName: net.sourceforge.phpeclipse.phpmanual; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: phpmanual.jar Bundle-Activator: net.sourceforge.phpeclipse.phpmanual.PHPManualUIPlugin Bundle-Vendor: PHPEclipse Development Team @@ -15,5 +15,4 @@ Require-Bundle: org.eclipse.core.runtime, net.sourceforge.phpeclipse.phpmanual.htmlparser, net.sourceforge.phpeclipse.ui Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Import-Package: org.eclipse.ui.texteditor diff --git a/net.sourceforge.phpeclipse.phpmanual/src/net/sourceforge/phpeclipse/phpmanual/views/PHPManualView.java b/net.sourceforge.phpeclipse.phpmanual/src/net/sourceforge/phpeclipse/phpmanual/views/PHPManualView.java index d08944a..f838bc5 100644 --- a/net.sourceforge.phpeclipse.phpmanual/src/net/sourceforge/phpeclipse/phpmanual/views/PHPManualView.java +++ b/net.sourceforge.phpeclipse.phpmanual/src/net/sourceforge/phpeclipse/phpmanual/views/PHPManualView.java @@ -20,7 +20,6 @@ import net.sourceforge.phpdt.phphelp.PHPHelpPlugin; import net.sourceforge.phpeclipse.PHPeclipsePlugin; import net.sourceforge.phpeclipse.phpeditor.PHPEditor; import net.sourceforge.phpeclipse.phpmanual.PHPManualUIPlugin; -import net.sourceforge.phpeclipse.ui.WebUI; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; @@ -348,7 +347,7 @@ public class PHPManualView extends ViewPart implements INullSelectionListener, I */ private PHPEditor getJavaEditor() { try { - IEditorPart part = /*PHPeclipsePlugin*/WebUI.getActivePage().getActiveEditor(); + IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor(); if (part instanceof PHPEditor) return (PHPEditor) part; else diff --git a/net.sourceforge.phpeclipse.smarty.ui/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.smarty.ui/META-INF/MANIFEST.MF index b1a0c73..5872a06 100644 --- a/net.sourceforge.phpeclipse.smarty.ui/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.smarty.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPeclipse Smarty UI Bundle-SymbolicName: net.sourceforge.phpeclipse.smarty.ui;singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: smartyui.jar Bundle-Activator: net.sourceforge.phpdt.smarty.ui.SmartyUI Bundle-Vendor: PHPEclipse project team @@ -10,12 +10,15 @@ Export-Package: net.sourceforge.phpdt.smarty.ui, net.sourceforge.phpdt.smarty.ui.internal;x-internal:=true, net.sourceforge.phpdt.smarty.ui.internal.editor;x-internal:=true, net.sourceforge.phpdt.smarty.ui.internal.text;x-internal:=true -Require-Bundle: org.eclipse.ui, +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.core.resources, + org.eclipse.core.filebuffers, + org.eclipse.ui, + org.eclipse.ui.ide, + org.eclipse.ui.editors, org.eclipse.ui.workbench.texteditor, org.eclipse.jface.text, net.sourceforge.phpeclipse.ui, - org.eclipse.ui.editors;bundle-version="3.4.0", - org.eclipse.core.runtime;bundle-version="3.4.0", - org.eclipse.ui.ide -Bundle-RequiredExecutionEnvironment: J2SE-1.4 + net.sourceforge.phpeclipse.xml.ui Bundle-ActivationPolicy: lazy + diff --git a/net.sourceforge.phpeclipse.ui/.settings/org.eclipse.jdt.core.prefs b/net.sourceforge.phpeclipse.ui/.settings/org.eclipse.jdt.core.prefs index f95f009..fc28a3a 100644 --- a/net.sourceforge.phpeclipse.ui/.settings/org.eclipse.jdt.core.prefs +++ b/net.sourceforge.phpeclipse.ui/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,12 @@ -#Fri Sep 07 14:51:48 PDT 2007 +#Tue Jan 17 21:13:31 CET 2012 eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/net.sourceforge.phpeclipse.ui/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.ui/META-INF/MANIFEST.MF index 0d0ab9c..728a3d3 100644 --- a/net.sourceforge.phpeclipse.ui/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.ui/META-INF/MANIFEST.MF @@ -3,52 +3,12 @@ Generated-from: 1150021273000;type=2 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse UI Bundle-SymbolicName: net.sourceforge.phpeclipse.ui; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: ui.jar Bundle-Activator: net.sourceforge.phpeclipse.ui.WebUI Bundle-Vendor: PHPEclipse Development Team Bundle-Localization: plugin -Export-Package: net.sourceforge.phpdt.internal.corext.codemanipulation;x-internal:=true, - net.sourceforge.phpdt.internal.ui;x-internal:=true, - net.sourceforge.phpdt.internal.ui.actions;x-internal:=true, - net.sourceforge.phpdt.internal.ui.dialogs;x-internal:=true, - net.sourceforge.phpdt.internal.ui.dnd;x-internal:=true, - net.sourceforge.phpdt.internal.ui.filters;x-internal:=true, - net.sourceforge.phpdt.internal.ui.phpdocexport;x-internal:=true, - net.sourceforge.phpdt.internal.ui.preferences;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.comment;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.folding;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.java;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.java.hover;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.link;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.phpdoc;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.spelling;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.spelling.engine;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.template;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.template.contentassist;x-internal:=true, - net.sourceforge.phpdt.internal.ui.text.template.preferences;x-internal:=true, - net.sourceforge.phpdt.internal.ui.util;x-internal:=true, - net.sourceforge.phpdt.internal.ui.viewsupport;x-internal:=true, - net.sourceforge.phpdt.internal.ui.wizards;x-internal:=true, - net.sourceforge.phpdt.internal.ui.wizards.dialogfields;x-internal:=true, - net.sourceforge.phpdt.ltk.ui, - net.sourceforge.phpdt.ltk.ui.actions, - net.sourceforge.phpdt.ltk.ui.wizards, - net.sourceforge.phpdt.ui, - net.sourceforge.phpdt.ui.actions, - net.sourceforge.phpdt.ui.text, - net.sourceforge.phpdt.ui.text.folding, - net.sourceforge.phpdt.ui.text.java.hover, - net.sourceforge.phpdt.ui.wizards, - net.sourceforge.phpeclipse.builder, - net.sourceforge.phpeclipse.obfuscator, - net.sourceforge.phpeclipse.obfuscator.export, - net.sourceforge.phpeclipse.phpeditor, - net.sourceforge.phpeclipse.phpeditor.actions, - net.sourceforge.phpeclipse.phpeditor.php, - net.sourceforge.phpeclipse.phpeditor.util, - net.sourceforge.phpeclipse.ui, +Export-Package: net.sourceforge.phpeclipse.ui, net.sourceforge.phpeclipse.ui.editor, net.sourceforge.phpeclipse.ui.internal;x-internal:=true, net.sourceforge.phpeclipse.ui.overlaypages, @@ -59,16 +19,9 @@ Export-Package: net.sourceforge.phpdt.internal.corext.codemanipulation;x-interna net.sourceforge.phpeclipse.ui.text.rules, net.sourceforge.phpeclipse.ui.text.source, net.sourceforge.phpeclipse.ui.views.outline, - net.sourceforge.phpeclipse.ui.views.util, - net.sourceforge.phpeclipse.wizards.html, - net.sourceforge.phpeclipse.xml.ui, - net.sourceforge.phpeclipse.xml.ui.internal.compare;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.editor;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.outline;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.preferences;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.text;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.text + net.sourceforge.phpeclipse.ui.views.util Require-Bundle: net.sourceforge.phpeclipse.core, + org.eclipse.core.resources, org.eclipse.core.runtime, org.eclipse.jface.text, org.eclipse.debug.ui, @@ -78,13 +31,7 @@ Require-Bundle: net.sourceforge.phpeclipse.core, org.eclipse.ui.views, org.eclipse.ui.console, org.eclipse.ui.workbench.texteditor, - net.sourceforge.phpeclipse.webbrowser, - net.sourceforge.phpeclipse;bundle-version="0.0.0", - net.sourceforge.phpeclipse.xml.core, - org.eclipse.compare, - org.eclipse.core.resources;bundle-version="3.4.1" -Bundle-RequiredExecutionEnvironment: J2SE-1.4 + net.sourceforge.phpeclipse.webbrowser Bundle-ActivationPolicy: lazy -Import-Package: org.eclipse.ltk.core.refactoring.participants, - org.eclipse.ltk.ui.refactoring, - org.eclipse.search.ui +Import-Package: org.eclipse.search.ui + diff --git a/net.sourceforge.phpeclipse.ui/plugin.properties b/net.sourceforge.phpeclipse.ui/plugin.properties index d7b7c12..0aa3596 100644 --- a/net.sourceforge.phpeclipse.ui/plugin.properties +++ b/net.sourceforge.phpeclipse.ui/plugin.properties @@ -18,51 +18,8 @@ preferencePageName = PHPeclipse viewCategoryName = PHPeclipse perspectivePHP.name=PHP -newWizardCategory.name=PHP -newWizardPHPProject.name=PHP Project -newWizardPHPFile.name=PHP File -newWizardHTMLFile.name=HTML file - -OpenActionSet.label=Open Declaration/Include -OpenDeclaration=Open Declaration/Include -ExportWizards.Obfuscator = Obfuscate PHP Project to File system -ExportWizards.ObfuscatorDescription = Obfuscate PHP resources to the local file system - -compilerPageName=PHP Parser -todoPageName=PHP Task Tags - -phpEditorName=PHP Editor - -sourceHover= Source -sourceHoverDescription= Shows the source of the selected element. -sequentialHover= Combined Hover -sequentialHoverDescription= Tries the hovers in the sequence listed in the table below this one and uses the one which fits best for the selected element and the current context. -annotationHover= Annotation Description -annotationHoverDescription= Shows the description of the selected annotation. -problemHover= Problem Description -problemHoverDescription= Shows the description of the selected problem. - - -category.source.name=PHP Source -category.source.description= PHP Source Actions - -context.editingPHPSource.name= Editing PHP Source -context.editingPHPSource.description= Editing PHP Source Context - - -javaDocumentFactory=PHP Document Factory -javaDocumentSetupParticipant=PHP Document Setup Participant templates.contextType.xml=xml templates.contextType.html=html templates.contextType.smarty=smarty templates.contextType.javascript=javascript - - -compilerOptionsPrefName= PHP Parser -todoTaskPrefName= Task Tags -templatePageName= Templates -spellingPrefName= Spelling -codeAssistPageName= Code Assist -editorPageName= Editor -editorMarkOccurrencesPage= Mark Occurrences diff --git a/net.sourceforge.phpeclipse.ui/plugin.xml b/net.sourceforge.phpeclipse.ui/plugin.xml index 1c4259d..e44ef09 100644 --- a/net.sourceforge.phpeclipse.ui/plugin.xml +++ b/net.sourceforge.phpeclipse.ui/plugin.xml @@ -12,1107 +12,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create a new PHP project. - - - - - - Create a basic PHP file. - - - - - Create a basic HTML file. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %ExportWizards.ObfuscatorDescription - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %phpEditorFontDefintion.description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - %ProblemsLabelDecorator.description - - - - - - - - - - - - - %OverrideIndicatorLabelDecorator.description - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GenStubSettings) - * @param imports - * Imports required by the stub are added to the imports - * structure. If imports structure is null all - * type names are qualified. - * @throws JavaModelException - */ -// public static String genStub(ICompilationUnit cu, String destTypeName, -// IMethod method, IType definingType, GenStubSettings settings) -// throws CoreException { -// // IImportsStructure imports) throws CoreException { -// String methName = method.getElementName(); -// String[] paramNames = suggestArgumentNames(method.getJavaProject(), -// method.getParameterNames()); -// String returnType = method.isConstructor() ? null : method -// .getReturnType(); -// String lineDelimiter = String.valueOf('\n'); // reformatting required -// -// StringBuffer buf = new StringBuffer(); -// // add method comment -// if (settings.createComments && cu != null) { -// IMethod overridden = null; -// if (settings.methodOverwrites && returnType != null) { -// overridden = JavaModelUtil.findMethod(methName, method -// .getParameterTypes(), false, definingType.getMethods()); -// } -// String comment = getMethodComment(cu, destTypeName, methName, -// paramNames, method.getExceptionTypes(), returnType, -// overridden, lineDelimiter); -// if (comment != null) { -// buf.append(comment); -// } else { -// buf.append("/**").append(lineDelimiter); //$NON-NLS-1$ -// buf.append(" *").append(lineDelimiter); //$NON-NLS-1$ -// buf.append(" */").append(lineDelimiter); //$NON-NLS-1$ -// } -// buf.append(lineDelimiter); -// } -// // add method declaration -// String bodyContent = null; -// if (!settings.noBody) { -// String bodyStatement = getDefaultMethodBodyStatement(methName, -// paramNames, returnType, settings.callSuper); -// bodyContent = getMethodBodyContent(returnType == null, method -// .getJavaProject(), destTypeName, methName, bodyStatement, -// lineDelimiter); -// if (bodyContent == null) { -// bodyContent = ""; //$NON-NLS-1$ -// } -// } -// int flags = settings.methodModifiers; -// if (flags == -1) { -// flags = method.getFlags(); -// } -// -// genMethodDeclaration(destTypeName, method, flags, bodyContent, buf); // imports, -// // buf); -// return buf.toString(); -// } - - /** - * Generates a method stub not including the method comment. Given a - * template method and the body content, a stub with the same signature will - * be constructed so it can be added to a type. - * - * @param destTypeName - * The name of the type to which the method will be added to - * @param method - * A method template (method belongs to different type than the - * parent) - * @param bodyContent - * Content of the body - * @param imports - * Imports required by the stub are added to the imports - * structure. If imports structure is null all - * type names are qualified. - * @param buf - * The buffer to append the gerenated code. - * @throws JavaModelException - */ -// public static void genMethodDeclaration(String destTypeName, -// IMethod method, String bodyContent, StringBuffer buf) -// throws CoreException { // IImportsStructure imports, StringBuffer -// // buf) throws CoreException { -// genMethodDeclaration(destTypeName, method, method.getFlags(), -// bodyContent, buf); -// } - - /** - * Generates a method stub not including the method comment. Given a - * template method and the body content, a stub with the same signature will - * be constructed so it can be added to a type. - * - * @param destTypeName - * The name of the type to which the method will be added to - * @param method - * A method template (method belongs to different type than the - * parent) - * @param bodyContent - * Content of the body - * @param imports - * Imports required by the stub are added to the imports - * structure. If imports structure is null all - * type names are qualified. - * @param buf - * The buffer to append the gerenated code. - * @throws JavaModelException - */ -// public static void genMethodDeclaration(String destTypeName, -// IMethod method, int flags, String bodyContent, StringBuffer buf) -// throws CoreException { -// // IImportsStructure imports, StringBuffer buf) throws CoreException { -// IType parentType = method.getDeclaringType(); -// String methodName = method.getElementName(); -// String[] paramTypes = method.getParameterTypes(); -// String[] paramNames = suggestArgumentNames(parentType.getJavaProject(), -// method.getParameterNames()); -// -// String[] excTypes = method.getExceptionTypes(); -// -// boolean isConstructor = method.isConstructor(); -// String retTypeSig = isConstructor ? null : method.getReturnType(); -// -// int lastParam = paramTypes.length - 1; -// -// if (Flags.isPublic(flags) -// || (parentType.isInterface() && bodyContent != null)) { -// buf.append("public "); //$NON-NLS-1$ -// } else if (Flags.isProtected(flags)) { -// buf.append("protected "); //$NON-NLS-1$ -// } else if (Flags.isPrivate(flags)) { -// buf.append("private "); //$NON-NLS-1$ -// } -// // if (Flags.isSynchronized(flags)) { -// // buf.append("synchronized "); //$NON-NLS-1$ -// // } -// // if (Flags.isVolatile(flags)) { -// // buf.append("volatile "); //$NON-NLS-1$ -// // } -// // if (Flags.isStrictfp(flags)) { -// // buf.append("strictfp "); //$NON-NLS-1$ -// // } -// if (Flags.isStatic(flags)) { -// buf.append("static "); //$NON-NLS-1$ -// } -// -// if (isConstructor) { -// buf.append(destTypeName); -// } else { -// String retTypeFrm; -// if (!isPrimitiveType(retTypeSig)) { -// retTypeFrm = resolveAndAdd(retTypeSig, parentType); -// } else { -// retTypeFrm = Signature.toString(retTypeSig); -// } -// buf.append(retTypeFrm); -// buf.append(' '); -// buf.append(methodName); -// } -// buf.append('('); -// for (int i = 0; i <= lastParam; i++) { -// String paramTypeSig = paramTypes[i]; -// String paramTypeFrm; -// -// if (!isPrimitiveType(paramTypeSig)) { -// paramTypeFrm = resolveAndAdd(paramTypeSig, parentType); -// } else { -// paramTypeFrm = Signature.toString(paramTypeSig); -// } -// buf.append(paramTypeFrm); -// buf.append(' '); -// buf.append(paramNames[i]); -// if (i < lastParam) { -// buf.append(", "); //$NON-NLS-1$ -// } -// } -// buf.append(')'); -// -// int lastExc = excTypes.length - 1; -// if (lastExc >= 0) { -// buf.append(" throws "); //$NON-NLS-1$ -// for (int i = 0; i <= lastExc; i++) { -// String excTypeSig = excTypes[i]; -// String excTypeFrm = resolveAndAdd(excTypeSig, parentType); -// buf.append(excTypeFrm); -// if (i < lastExc) { -// buf.append(", "); //$NON-NLS-1$ -// } -// } -// } -// if (bodyContent == null) { -// buf.append(";\n\n"); //$NON-NLS-1$ -// } else { -// buf.append(" {\n\t"); //$NON-NLS-1$ -// if ((bodyContent != null) && (bodyContent.length() > 0)) { -// buf.append(bodyContent); -// buf.append('\n'); -// } -// buf.append("}\n"); //$NON-NLS-1$ -// } -// } - -// public static String getDefaultMethodBodyStatement(String methodName, -// String[] paramNames, String retTypeSig, boolean callSuper) { -// StringBuffer buf = new StringBuffer(); -// if (callSuper) { -// if (retTypeSig != null) { -// if (!Signature.SIG_VOID.equals(retTypeSig)) { -// buf.append("return "); //$NON-NLS-1$ -// } -// buf.append("super."); //$NON-NLS-1$ -// buf.append(methodName); -// } else { -// buf.append("super"); //$NON-NLS-1$ -// } -// buf.append('('); -// for (int i = 0; i < paramNames.length; i++) { -// if (i > 0) { -// buf.append(", "); //$NON-NLS-1$ -// } -// buf.append(paramNames[i]); -// } -// buf.append(");"); //$NON-NLS-1$ -// } else { -// if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { -// if (!isPrimitiveType(retTypeSig) -// || Signature.getArrayCount(retTypeSig) > 0) { -// buf.append("return null;"); //$NON-NLS-1$ -// } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { -// buf.append("return false;"); //$NON-NLS-1$ -// } else { -// buf.append("return 0;"); //$NON-NLS-1$ -// } -// } -// } -// return buf.toString(); -// } - - public static String getMethodBodyContent(boolean isConstructor, - IJavaProject project, String destTypeName, String methodName, - String bodyStatement, String lineDelimiter) throws CoreException { - String templateName = isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB - : CodeTemplateContextType.METHODSTUB; - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return bodyStatement; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, - destTypeName); - context.setVariable(CodeTemplateContextType.BODY_STATEMENT, - bodyStatement); - String str = evaluateTemplate(context, template); - if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) { - return bodyStatement; - } - return str; - } - - public static String getGetterMethodBodyContent(IJavaProject project, - String destTypeName, String methodName, String fieldName, - String lineDelimiter) throws CoreException { - String templateName = CodeTemplateContextType.GETTERSTUB; - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, - destTypeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - - return evaluateTemplate(context, template); - } - - public static String getSetterMethodBodyContent(IJavaProject project, - String destTypeName, String methodName, String fieldName, - String paramName, String lineDelimiter) throws CoreException { - String templateName = CodeTemplateContextType.SETTERSTUB; - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), project, lineDelimiter); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, - destTypeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName); - context.setVariable(CodeTemplateContextType.PARAM, paramName); - - return evaluateTemplate(context, template); - } - -// public static String getCatchBodyContent(ICompilationUnit cu, -// String exceptionType, String variableName, String lineDelimiter) -// throws CoreException { -// Template template = WebUI.getDefault() -// .getCodeTemplateStore().findTemplate( -// CodeTemplateContextType.CATCHBLOCK); -// if (template == null) { -// return null; -// } -// -// CodeTemplateContext context = new CodeTemplateContext(template -// .getContextTypeId(), cu.getJavaProject(), lineDelimiter); -// context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, -// exceptionType); -// context -// .setVariable(CodeTemplateContextType.EXCEPTION_VAR, -// variableName); //$NON-NLS-1$ -// return evaluateTemplate(context, template); -// } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, - * String, String) - */ - public static String getCompilationUnitContent(ICompilationUnit cu, - String typeComment, String typeContent, String lineDelimiter) - throws CoreException { - IPackageFragment pack = (IPackageFragment) cu.getParent(); - String packDecl = pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$ - - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate( - CodeTemplateContextType.NEWTYPE); - if (template == null) { - return null; - } - - IJavaProject project = cu.getJavaProject(); - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), project, lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, - packDecl); - context.setVariable(CodeTemplateContextType.TYPE_COMMENT, - typeComment != null ? typeComment : ""); //$NON-NLS-1$ - context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, - typeContent); - context.setVariable(CodeTemplateContextType.TYPENAME, Signature - .getQualifier(cu.getElementName())); - return evaluateTemplate(context, template); - } - - /* - * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, - * String, String) - */ - public static String getTypeComment(ICompilationUnit cu, - String typeQualifiedName, String lineDelim) throws CoreException { - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate( - CodeTemplateContextType.TYPECOMMENT); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), cu.getJavaProject(), lineDelim); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature - .getQualifier(typeQualifiedName)); - context.setVariable(CodeTemplateContextType.TYPENAME, Signature - .getSimpleName(typeQualifiedName)); - return evaluateTemplate(context, template); - } - - // private static String[] getParameterTypesQualifiedNames(IMethodBinding - // binding) { - // ITypeBinding[] typeBindings= binding.getParameterTypes(); - // String[] result= new String[typeBindings.length]; - // for (int i= 0; i < result.length; i++) { - // result[i]= typeBindings[i].getQualifiedName(); - // } - // return result; - // } - -// private static String getSeeTag(String declaringClassQualifiedName, -// String methodName, String[] parameterTypesQualifiedNames) { -// StringBuffer buf = new StringBuffer(); -// buf.append("@see "); //$NON-NLS-1$ -// buf.append(declaringClassQualifiedName); -// buf.append('#'); -// buf.append(methodName); -// buf.append('('); -// for (int i = 0; i < parameterTypesQualifiedNames.length; i++) { -// if (i > 0) { -// buf.append(", "); //$NON-NLS-1$ -// } -// buf.append(parameterTypesQualifiedNames[i]); -// } -// buf.append(')'); -// return buf.toString(); -// } - - private static String getSeeTag(IMethod overridden) - throws JavaModelException { - IType declaringType = overridden.getDeclaringType(); - StringBuffer buf = new StringBuffer(); - buf.append("@see "); //$NON-NLS-1$ - buf.append(declaringType.getFullyQualifiedName('.')); - buf.append('#'); - buf.append(overridden.getElementName()); - buf.append('('); - String[] paramTypes = overridden.getParameterTypes(); - for (int i = 0; i < paramTypes.length; i++) { - if (i > 0) { - buf.append(", "); //$NON-NLS-1$ - } - String curr = paramTypes[i]; - buf.append(JavaModelUtil.getResolvedTypeName(curr, declaringType)); - int arrayCount = Signature.getArrayCount(curr); - while (arrayCount > 0) { - buf.append("[]"); //$NON-NLS-1$ - arrayCount--; - } - } - buf.append(')'); - return buf.toString(); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(IMethod,IMethod,String) - */ - public static String getMethodComment(IMethod method, IMethod overridden, - String lineDelimiter) throws CoreException { - String retType = method.isConstructor() ? null : method.getReturnType(); - String[] paramNames = method.getParameterNames(); - - return getMethodComment(method.getCompilationUnit(), method - .getDeclaringType().getElementName(), method.getElementName(), - paramNames, method.getExceptionTypes(), retType, overridden, - lineDelimiter); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, - * String, String, String[], String[], String, IMethod, String) - */ - public static String getMethodComment(ICompilationUnit cu, String typeName, - String methodName, String[] paramNames, String[] excTypeSig, - String retTypeSig, IMethod overridden, String lineDelimiter) - throws CoreException { - String templateName = CodeTemplateContextType.METHODCOMMENT; - if (retTypeSig == null) { - templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT; - } else if (overridden != null) { - templateName = CodeTemplateContextType.OVERRIDECOMMENT; - } - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - - if (retTypeSig != null) { - context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature - .toString(retTypeSig)); - } - if (overridden != null) { - context.setVariable(CodeTemplateContextType.SEE_TAG, - getSeeTag(overridden)); - } - TemplateBuffer buffer; - try { - buffer = context.evaluate(template); - } catch (BadLocationException e) { - throw new CoreException(Status.CANCEL_STATUS); - } catch (TemplateException e) { - throw new CoreException(Status.CANCEL_STATUS); - } - if (buffer == null) { - return null; - } - - String str = buffer.getString(); - if (Strings.containsOnlyWhitespaces(str)) { - return null; - } - TemplateVariable position = findTagVariable(buffer); // look if - // Javadoc tags - // have to be - // added - if (position == null) { - return str; - } - - IDocument textBuffer = new Document(str); - String[] exceptionNames = new String[excTypeSig.length]; - for (int i = 0; i < excTypeSig.length; i++) { - exceptionNames[i] = Signature.toString(excTypeSig[i]); - } - String returnType = retTypeSig != null ? Signature.toString(retTypeSig) - : null; - int[] tagOffsets = position.getOffsets(); - for (int i = tagOffsets.length - 1; i >= 0; i--) { // from last to - // first - try { - insertTag(textBuffer, tagOffsets[i], position.getLength(), - paramNames, exceptionNames, returnType, false, - lineDelimiter); - } catch (BadLocationException e) { - throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, - e)); - } - } - return textBuffer.get(); - } - - public static String getFieldComment(ICompilationUnit cu, String typeName, - String fieldName, String lineDelimiter) throws CoreException { - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate( - CodeTemplateContextType.FIELDCOMMENT); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - - return evaluateTemplate(context, template); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, - * String, String, String, String, String, String, String) - */ - public static String getSetterComment(ICompilationUnit cu, String typeName, - String methodName, String fieldName, String fieldType, - String paramName, String bareFieldName, String lineDelimiter) - throws CoreException { - String templateName = CodeTemplateContextType.SETTERCOMMENT; - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); - context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, - bareFieldName); - context.setVariable(CodeTemplateContextType.PARAM, paramName); - - return evaluateTemplate(context, template); - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, - * String, String, String, String, String, String) - */ - public static String getGetterComment(ICompilationUnit cu, String typeName, - String methodName, String fieldName, String fieldType, - String bareFieldName, String lineDelimiter) throws CoreException { - String templateName = CodeTemplateContextType.GETTERCOMMENT; - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate(templateName); - if (template == null) { - return null; - } - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), cu.getJavaProject(), lineDelimiter); - context.setCompilationUnitVariables(cu); - context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - methodName); - context.setVariable(CodeTemplateContextType.FIELD, fieldName); - context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); - context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, - bareFieldName); - - return evaluateTemplate(context, template); - } - - public static String evaluateTemplate(CodeTemplateContext context, - Template template) throws CoreException { - TemplateBuffer buffer; - try { - buffer = context.evaluate(template); - } catch (BadLocationException e) { - throw new CoreException(Status.CANCEL_STATUS); - } catch (TemplateException e) { - throw new CoreException(Status.CANCEL_STATUS); - } - if (buffer == null) - return null; - String str = buffer.getString(); - if (Strings.containsOnlyWhitespaces(str)) { - return null; - } - return str; - } - - /** - * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, - * String, MethodDeclaration, IMethodBinding, String) - */ - // public static String getMethodComment(ICompilationUnit cu, String - // typeName, IMethodBinding overridden, String lineDelimiter) throws - // CoreException { - // if (overridden != null) { - // String declaringClassQualifiedName= - // overridden.getDeclaringClass().getQualifiedName(); - // String[] parameterTypesQualifiedNames= - // getParameterTypesQualifiedNames(overridden); - // return getMethodComment(cu, typeName, decl, true, - // overridden.isDeprecated(), declaringClassQualifiedName, - // parameterTypesQualifiedNames, lineDelimiter); - // } else { - // return getMethodComment(cu, typeName, decl, false, false, null, null, - // lineDelimiter); - // } - // } - /** - * Returns the comment for a method using the comment code templates. - * null is returned if the template is empty. - * - * @param cu - * The compilation unit to which the method belongs - * @param typeName - * Name of the type to which the method belongs. - * @param decl - * The AST MethodDeclaration node that will be added as new - * method. - * @param isOverridden - * true iff decl overrides another method - * @param isDeprecated - * true iff the method that decl overrides is - * deprecated. Note: it must not be true if - * isOverridden is false. - * @param declaringClassQualifiedName - * Fully qualified name of the type in which the overriddden - * method (if any exists) in declared. If isOverridden is - * false, this is ignored. - * @param parameterTypesQualifiedNames - * Fully qualified names of parameter types of the type in which - * the overriddden method (if any exists) in declared. If - * isOverridden is false, this is ignored. - * @return String Returns the method comment or null if the - * configured template is empty. (formatting required) - * @throws CoreException - */ - // public static String getMethodComment(ICompilationUnit cu, String - // typeName, MethodDeclaration decl, boolean isOverridden, boolean - // isDeprecated, String declaringClassQualifiedName, String[] - // parameterTypesQualifiedNames, String lineDelimiter) throws CoreException - // { - // String templateName= CodeTemplateContextType.METHODCOMMENT; - // if (decl.isConstructor()) { - // templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; - // } else if (isOverridden) { - // templateName= CodeTemplateContextType.OVERRIDECOMMENT; - // } - // Template template= - // PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); - // if (template == null) { - // return null; - // } - // CodeTemplateContext context= new - // CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), - // lineDelimiter); - // context.setCompilationUnitVariables(cu); - // context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); - // context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, - // decl.getName().getIdentifier()); - // if (!decl.isConstructor()) { - // context.setVariable(CodeTemplateContextType.RETURN_TYPE, - // ASTNodes.asString(decl.getReturnType())); - // } - // if (isOverridden) { - // String methodName= decl.getName().getIdentifier(); - // context.setVariable(CodeTemplateContextType.SEE_TAG, - // getSeeTag(declaringClassQualifiedName, methodName, - // parameterTypesQualifiedNames)); - // } - // - // TemplateBuffer buffer; - // try { - // buffer= context.evaluate(template); - // } catch (BadLocationException e) { - // throw new CoreException(Status.CANCEL_STATUS); - // } catch (TemplateException e) { - // throw new CoreException(Status.CANCEL_STATUS); - // } - // if (buffer == null) - // return null; - // String str= buffer.getString(); - // if (Strings.containsOnlyWhitespaces(str)) { - // return null; - // } - // TemplateVariable position= findTagVariable(buffer); // look if Javadoc - // tags have to be added - // if (position == null) { - // return str; - // } - // - // IDocument textBuffer= new Document(str); - // List params= decl.parameters(); - // String[] paramNames= new String[params.size()]; - // for (int i= 0; i < params.size(); i++) { - // SingleVariableDeclaration elem= (SingleVariableDeclaration) - // params.get(i); - // paramNames[i]= elem.getName().getIdentifier(); - // } - // List exceptions= decl.thrownExceptions(); - // String[] exceptionNames= new String[exceptions.size()]; - // for (int i= 0; i < exceptions.size(); i++) { - // exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) - // exceptions.get(i)); - // } - // String returnType= !decl.isConstructor() ? - // ASTNodes.asString(decl.getReturnType()) : null; - // int[] tagOffsets= position.getOffsets(); - // for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first - // try { - // insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, - // exceptionNames, returnType, isDeprecated, lineDelimiter); - // } catch (BadLocationException e) { - // throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); - // } - // } - // return textBuffer.get(); - // } - private static TemplateVariable findTagVariable(TemplateBuffer buffer) { - TemplateVariable[] positions = buffer.getVariables(); - for (int i = 0; i < positions.length; i++) { - TemplateVariable curr = positions[i]; - if (CodeTemplateContextType.TAGS.equals(curr.getType())) { - return curr; - } - } - return null; - } - - private static void insertTag(IDocument textBuffer, int offset, int length, - String[] paramNames, String[] exceptionNames, String returnType, - boolean isDeprecated, String lineDelimiter) - throws BadLocationException { - IRegion region = textBuffer.getLineInformationOfOffset(offset); - if (region == null) { - return; - } - String lineStart = textBuffer.get(region.getOffset(), offset - - region.getOffset()); - - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < paramNames.length; i++) { - if (buf.length() > 0) { - buf.append(lineDelimiter); - buf.append(lineStart); - } - buf.append("@param ");buf.append(paramNames[i]); //$NON-NLS-1$ - } - if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$ - if (buf.length() > 0) { - buf.append(lineDelimiter); - buf.append(lineStart); - } - buf.append("@return"); //$NON-NLS-1$ - } - if (exceptionNames != null) { - for (int i = 0; i < exceptionNames.length; i++) { - if (buf.length() > 0) { - buf.append(lineDelimiter); - buf.append(lineStart); - } - buf.append("@throws ");buf.append(exceptionNames[i]); //$NON-NLS-1$ - } - } - if (isDeprecated) { - if (buf.length() > 0) { - buf.append(lineDelimiter); - buf.append(lineStart); - } - buf.append("@deprecated"); //$NON-NLS-1$ - } - textBuffer.replace(offset, length, buf.toString()); - } - -// private static boolean isPrimitiveType(String typeName) { -// char first = Signature.getElementType(typeName).charAt(0); -// return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); -// } - -// private static String resolveAndAdd(String refTypeSig, IType declaringType) -// throws JavaModelException {// , IImportsStructure imports) throws -// // JavaModelException { -// String resolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, -// declaringType); -// if (resolvedTypeName != null) { -// StringBuffer buf = new StringBuffer(); -// // if (imports != null) { -// // buf.append(imports.addImport(resolvedTypeName)); -// // } else { -// buf.append(resolvedTypeName); -// // } -// int arrayCount = Signature.getArrayCount(refTypeSig); -// for (int i = 0; i < arrayCount; i++) { -// buf.append("[]"); //$NON-NLS-1$ -// } -// return buf.toString(); -// } -// return Signature.toString(refTypeSig); -// } - - /** - * Finds a method in a list of methods. - * - * @return The found method or null, if nothing found - */ -// private static IMethod findMethod(IMethod method, List allMethods) -// throws JavaModelException { -// String name = method.getElementName(); -// String[] paramTypes = method.getParameterTypes(); -// boolean isConstructor = method.isConstructor(); -// -// for (int i = allMethods.size() - 1; i >= 0; i--) { -// IMethod curr = (IMethod) allMethods.get(i); -// if (JavaModelUtil.isSameMethodSignature(name, paramTypes, -// isConstructor, curr)) { -// return curr; -// } -// } -// return null; -// } - - /** - * Creates needed constructors for a type. - * - * @param type - * The type to create constructors for - * @param supertype - * The type's super type - * @param settings - * Options for comment generation - * @param imports - * Required imports are added to the import structure. Structure - * can be null, types are qualified then. - * @return Returns the generated stubs or null if the - * creation has been canceled - */ - // public static String[] evalConstructors(IType type, IType supertype, - // IImportsStructure imports) throws CoreException { - // IMethod[] superMethods= supertype.getMethods(); - // String typeName= type.getElementName(); - // ICompilationUnit cu= type.getCompilationUnit(); - // IMethod[] methods= type.getMethods(); - // GenStubSettings genStubSettings= new GenStubSettings(settings); - // genStubSettings.callSuper= true; - // - // ArrayList newMethods= new ArrayList(superMethods.length); - // for (int i= 0; i < superMethods.length; i++) { - // IMethod curr= superMethods[i]; - // if (curr.isConstructor() && (JavaModelUtil.isVisibleInHierarchy(curr, - // type.getPackageFragment()))) { - // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, - // methods) == null) { - // genStubSettings.methodModifiers= Flags.AccPublic | - // JdtFlags.clearAccessModifiers(curr.getFlags()); - // String newStub= genStub(cu, typeName, curr, curr.getDeclaringType(), - // genStubSettings, imports); - // newMethods.add(newStub); - // } - // } - // } - // return (String[]) newMethods.toArray(new String[newMethods.size()]); - // } - /** - * Returns all unimplemented constructors of a type including root type - * default constructors if there are no other superclass constructors - * unimplemented. - * - * @param type - * The type to create constructors for - * @return Returns the generated stubs or null if the - * creation has been canceled - */ - // public static IMethod[] getOverridableConstructors(IType type) throws - // CoreException { - // List constructorMethods= new ArrayList(); - // ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); - // IType supertype= hierarchy.getSuperclass(type); - // if (supertype == null) - // return (new IMethod[0]); - // - // IMethod[] superMethods= supertype.getMethods(); - // boolean constuctorFound= false; - // String typeName= type.getElementName(); - // IMethod[] methods= type.getMethods(); - // for (int i= 0; i < superMethods.length; i++) { - // IMethod curr= superMethods[i]; - // if (curr.isConstructor()) { - // constuctorFound= true; - // if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) - // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, - // methods) == null) - // constructorMethods.add(curr); - // - // } - // } - // - // // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38487 - // if (!constuctorFound) { - // IType objectType= type.getJavaProject().findType("java.lang.Object"); - // //$NON-NLS-1$ - // IMethod curr= objectType.getMethod("Object", EMPTY); //$NON-NLS-1$ - // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, - // methods) == null) { - // constructorMethods.add(curr); - // } - // } - // return (IMethod[]) constructorMethods.toArray(new - // IMethod[constructorMethods.size()]); - // } - /** - * Returns all overridable methods of a type - * - * @param type - * The type to search the overridable methods for - * @param hierarchy - * The type hierarchy of the type - * @param isSubType - * If set, the result can include methods of the passed type, if - * not only methods from super types are considered - * @return Returns the all methods that can be overridden - */ - // public static IMethod[] getOverridableMethods(IType type, ITypeHierarchy - // hierarchy, boolean isSubType) throws JavaModelException { - // List allMethods= new ArrayList(); - // - // IMethod[] typeMethods= type.getMethods(); - // for (int i= 0; i < typeMethods.length; i++) { - // IMethod curr= typeMethods[i]; - // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && - // !Flags.isPrivate(curr.getFlags())) { - // allMethods.add(curr); - // } - // } - // - // IType[] superTypes= hierarchy.getAllSuperclasses(type); - // for (int i= 0; i < superTypes.length; i++) { - // IMethod[] methods= superTypes[i].getMethods(); - // for (int k= 0; k < methods.length; k++) { - // IMethod curr= methods[k]; - // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && - // !Flags.isPrivate(curr.getFlags())) { - // if (findMethod(curr, allMethods) == null) { - // allMethods.add(curr); - // } - // } - // } - // } - // - // IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); - // for (int i= 0; i < superInterfaces.length; i++) { - // IMethod[] methods= superInterfaces[i].getMethods(); - // for (int k= 0; k < methods.length; k++) { - // IMethod curr= methods[k]; - // - // // binary interfaces can contain static initializers (variable - // intializations) - // // 1G4CKUS - // if (!Flags.isStatic(curr.getFlags())) { - // IMethod impl= findMethod(curr, allMethods); - // if (impl == null || !JavaModelUtil.isVisibleInHierarchy(impl, - // type.getPackageFragment()) || prefereInterfaceMethod(hierarchy, curr, - // impl)) { - // if (impl != null) { - // allMethods.remove(impl); - // } - // // implement an interface method when it does not exist in the hierarchy - // // or when it throws less exceptions that the implemented - // allMethods.add(curr); - // } - // } - // } - // } - // if (!isSubType) { - // allMethods.removeAll(Arrays.asList(typeMethods)); - // } - // // remove finals - // for (int i= allMethods.size() - 1; i >= 0; i--) { - // IMethod curr= (IMethod) allMethods.get(i); - // if (Flags.isFinal(curr.getFlags())) { - // allMethods.remove(i); - // } - // } - // return (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); - // } - // private static boolean prefereInterfaceMethod(ITypeHierarchy hierarchy, - // IMethod interfaceMethod, IMethod curr) throws JavaModelException { - // if (Flags.isFinal(curr.getFlags())) { - // return false; - // } - // IType interfaceType= interfaceMethod.getDeclaringType(); - // IType[] interfaces= - // hierarchy.getAllSuperInterfaces(curr.getDeclaringType()); - // for (int i= 0; i < interfaces.length; i++) { - // if (interfaces[i] == interfaceType) { - // return false; - // } - // } - // return curr.getExceptionTypes().length > - // interfaceMethod.getExceptionTypes().length; - // } - /** - * Generate method stubs for methods to overrride - * - * @param type - * The type to search the overridable methods for - * @param hierarchy - * The type hierarchy of the type - * @param methodsToImplement - * Methods to override or implement - * @param settings - * Options for comment generation - * @param imports - * Required imports are added to the import structure. Structure - * can be null, types are qualified then. - * @return Returns the generated stubs - */ - // public static String[] genOverrideStubs(IMethod[] methodsToImplement, - // IType type, ITypeHierarchy hierarchy, CodeGenerationSettings settings, - // IImportsStructure imports) throws CoreException { - // GenStubSettings genStubSettings= new GenStubSettings(settings); - // genStubSettings.methodOverwrites= true; - // ICompilationUnit cu= type.getCompilationUnit(); - // String[] result= new String[methodsToImplement.length]; - // for (int i= 0; i < methodsToImplement.length; i++) { - // IMethod curr= methodsToImplement[i]; - // IMethod overrides= - // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, - // curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); - // if (overrides != null) { - // genStubSettings.callSuper= true; - // curr= overrides; - // } - // genStubSettings.methodModifiers= curr.getFlags(); - // IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, - // type, curr.getElementName(), curr.getParameterTypes(), - // curr.isConstructor()); - // if (desc == null) { - // desc= curr; - // } - // result[i]= genStub(cu, type.getElementName(), curr, - // desc.getDeclaringType(), genStubSettings, imports); - // } - // return result; - // } - /** - * Searches for unimplemented methods of a type. - * - * @param isSubType - * If set, the evaluation is for a subtype of the given type. If - * not set, the evaluation is for the type itself. - * @param settings - * Options for comment generation - * @param imports - * Required imports are added to the import structure. Structure - * can be null, types are qualified then. - * @return Returns the generated stubs or null if the - * creation has been canceled - */ - // public static String[] evalUnimplementedMethods(IType type, - // ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings - // settings, - // IImportsStructure imports) throws CoreException { - // - // IMethod[] inheritedMethods= getOverridableMethods(type, hierarchy, - // isSubType); - // - // List toImplement= new ArrayList(); - // for (int i= 0; i < inheritedMethods.length; i++) { - // IMethod curr= inheritedMethods[i]; - // if (JdtFlags.isAbstract(curr)) { - // toImplement.add(curr); - // } - // } - // IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new - // IMethod[toImplement.size()]); - // return genOverrideStubs(toImplementArray, type, hierarchy, settings, - // imports); - // } - /** - * Examines a string and returns the first line delimiter found. - */ -// public static String getLineDelimiterUsed(IJavaElement elem) -// throws JavaModelException { -// ICompilationUnit cu = (ICompilationUnit) elem -// .getAncestor(IJavaElement.COMPILATION_UNIT); -// if (cu != null && cu.exists()) { -// IBuffer buf = cu.getBuffer(); -// int length = buf.getLength(); -// for (int i = 0; i < length; i++) { -// char ch = buf.getChar(i); -// if (ch == SWT.CR) { -// if (i + 1 < length) { -// if (buf.getChar(i + 1) == SWT.LF) { -// return "\r\n"; //$NON-NLS-1$ -// } -// } -// return "\r"; //$NON-NLS-1$ -// } else if (ch == SWT.LF) { -// return "\n"; //$NON-NLS-1$ -// } -// } -// } -// return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ -// } - - /** - * Embodies the policy which line delimiter to use when inserting into a - * document. - */ - public static String getLineDelimiterFor(IDocument doc) { - // new for: 1GF5UU0: ITPJUI:WIN2000 - "Organize Imports" in php editor - // inserts lines in wrong format - String lineDelim = null; - try { - lineDelim = doc.getLineDelimiter(0); - } catch (BadLocationException e) { - } - if (lineDelim == null) { - String systemDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - String[] lineDelims = doc.getLegalLineDelimiters(); - for (int i = 0; i < lineDelims.length; i++) { - if (lineDelims[i].equals(systemDelimiter)) { - lineDelim = systemDelimiter; - break; - } - } - if (lineDelim == null) { - lineDelim = lineDelims.length > 0 ? lineDelims[0] - : systemDelimiter; - } - } - return lineDelim; - } - - /** - * Evaluates the indention used by a Java element. (in tabulators) - */ - // public static int getIndentUsed(IJavaElement elem) throws - // JavaModelException { - // if (elem instanceof ISourceReference) { - // ICompilationUnit cu= (ICompilationUnit) - // elem.getAncestor(IJavaElement.COMPILATION_UNIT); - // if (cu != null) { - // IBuffer buf= cu.getBuffer(); - // int offset= ((ISourceReference)elem).getSourceRange().getOffset(); - // int i= offset; - // // find beginning of line - // while (i > 0 && !Strings.isLineDelimiterChar(buf.getChar(i - 1)) ){ - // i--; - // } - // return Strings.computeIndent(buf.getText(i, offset - i), - // CodeFormatterUtil.getTabWidth()); - // } - // } - // return 0; - // } - public static String codeFormat(String sourceString, - int initialIndentationLevel, String lineDelim) { - ICodeFormatter formatter = ToolFactory.createDefaultCodeFormatter(null); - return formatter.format(sourceString, initialIndentationLevel, null, - lineDelim); - } - - /** - * Returns the element after the give element. - */ - // public static IJavaElement findNextSibling(IJavaElement member) throws - // JavaModelException { - // IJavaElement parent= member.getParent(); - // if (parent instanceof IParent) { - // IJavaElement[] elements= ((IParent)parent).getChildren(); - // for (int i= elements.length - 2; i >= 0 ; i--) { - // if (member.equals(elements[i])) { - // return elements[i+1]; - // } - // } - // } - // return null; - // } - // - public static String getTodoTaskTag(IJavaProject project) { - String markers = null; - if (project == null) { - markers = JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); - } else { - markers = project.getOption(JavaCore.COMPILER_TASK_TAGS, true); - } - - if (markers != null && markers.length() > 0) { - int idx = markers.indexOf(','); - if (idx == -1) { - return markers; - } else { - return markers.substring(0, idx); - } - } - return null; - } - - /* - * Workarounds for bug 38111 - */ - // public static String[] getArgumentNameSuggestions(IJavaProject project, - // String baseName, int dimensions, String[] excluded) { - // String name= workaround38111(baseName); - // String[] res= NamingConventions.suggestArgumentNames(project, "", name, - // dimensions, excluded); //$NON-NLS-1$ - // return sortByLength(res); // longest first - // } - // - // public static String[] getFieldNameSuggestions(IJavaProject project, - // String baseName, int dimensions, int modifiers, String[] excluded) { - // String name= workaround38111(baseName); - // String[] res= NamingConventions.suggestFieldNames(project, "", name, - // dimensions, modifiers, excluded); //$NON-NLS-1$ - // return sortByLength(res); // longest first - // } - // - // public static String[] getLocalNameSuggestions(IJavaProject project, - // String baseName, int dimensions, String[] excluded) { - // String name= workaround38111(baseName); - // String[] res= NamingConventions.suggestLocalVariableNames(project, "", - // name, dimensions, excluded); //$NON-NLS-1$ - // return sortByLength(res); // longest first - // } -// private static String[] sortByLength(String[] proposals) { -// Arrays.sort(proposals, new Comparator() { -// public int compare(Object o1, Object o2) { -// return ((String) o2).length() - ((String) o1).length(); -// } -// }); -// return proposals; -// } - -/* private static String workaround38111(String baseName) { - if (BASE_TYPES.contains(baseName)) - return baseName; - return Character.toUpperCase(baseName.charAt(0)) - + baseName.substring(1); - } -*/ -// private static final List BASE_TYPES = Arrays -// .asList(new String[] { -// "boolean", "byte", "char", "double", "float", "int", "long", "short" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ - -// public static String suggestArgumentName(IJavaProject project, -// String baseName, String[] excluded) { -// // String[] argnames= getArgumentNameSuggestions(project, baseName, 0, -// // excluded); -// // if (argnames.length > 0) { -// // return argnames[0]; -// // } -// return baseName; -// } - -// public static String[] suggestArgumentNames(IJavaProject project, -// String[] paramNames) { -// String prefixes = project.getOption( -// JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); -// String suffixes = project.getOption( -// JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); -// if (prefixes.length() + suffixes.length() == 0) { -// return paramNames; -// } -// -// String[] newNames = new String[paramNames.length]; -// // Ensure that the codegeneration preferences are respected -// for (int i = 0; i < paramNames.length; i++) { -// String curr = paramNames[i]; -// if (!hasPrefixOrSuffix(prefixes, suffixes, curr)) { -// newNames[i] = suggestArgumentName(project, paramNames[i], null); -// } else { -// newNames[i] = curr; -// } -// } -// return newNames; -// } - -// public static boolean hasFieldName(IJavaProject project, String name) { -// String prefixes = project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, -// true); -// String suffixes = project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, -// true); -// String staticPrefixes = project.getOption( -// JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true); -// String staticSuffixes = project.getOption( -// JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true); -// -// return hasPrefixOrSuffix(prefixes, suffixes, name) -// || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name); -// } - -// public static boolean hasParameterName(IJavaProject project, String name) { -// String prefixes = project.getOption( -// JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); -// String suffixes = project.getOption( -// JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); -// return hasPrefixOrSuffix(prefixes, suffixes, name); -// } - -// public static boolean hasLocalVariableName(IJavaProject project, String name) { -// String prefixes = project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, -// true); -// String suffixes = project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, -// true); -// return hasPrefixOrSuffix(prefixes, suffixes, name); -// } - -// public static boolean hasConstantName(String name) { -// return Character.isUpperCase(name.charAt(0)); -// } - -// private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, -// String name) { -// final String listSeparartor = ","; //$NON-NLS-1$ -// -// StringTokenizer tok = new StringTokenizer(prefixes, listSeparartor); -// while (tok.hasMoreTokens()) { -// String curr = tok.nextToken(); -// if (name.startsWith(curr)) { -// return true; -// } -// } -// -// tok = new StringTokenizer(suffixes, listSeparartor); -// while (tok.hasMoreTokens()) { -// String curr = tok.nextToken(); -// if (name.endsWith(curr)) { -// return true; -// } -// } -// return false; -// } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java deleted file mode 100644 index 953501b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java +++ /dev/null @@ -1,126 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -import java.util.Iterator; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaProject; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultLineTracker; -import org.eclipse.jface.text.ILineTracker; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateBuffer; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.text.templates.TemplateTranslator; -import org.eclipse.jface.text.templates.TemplateVariableResolver; - -public class CodeTemplateContext extends TemplateContext { - - private String fLineDelimiter; - - private IJavaProject fProject; - - public CodeTemplateContext(String contextTypeName, IJavaProject project, - String lineDelim) { - super(WebUI.getDefault().getCodeTemplateContextRegistry() - .getContextType(contextTypeName)); - fLineDelimiter = lineDelim; - fProject = project; - } - - public IJavaProject getJavaProject() { - return fProject; - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#evaluate(net.sourceforge.phpdt.internal.corext.template.Template) - */ - public TemplateBuffer evaluate(Template template) - throws BadLocationException, TemplateException { - // test that all variables are defined - Iterator iterator = getContextType().resolvers(); - while (iterator.hasNext()) { - TemplateVariableResolver var = (TemplateVariableResolver) iterator - .next(); - if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) { - // Assert.isNotNull(getVariable(var.getType()), "Variable " + - // var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - if (!canEvaluate(template)) - return null; - - String pattern = changeLineDelimiter(template.getPattern(), - fLineDelimiter); - - TemplateTranslator translator = new TemplateTranslator(); - TemplateBuffer buffer = translator.translate(pattern); - getContextType().resolve(buffer, this); - - return buffer; - } - - private static String changeLineDelimiter(String code, String lineDelim) { - try { - ILineTracker tracker = new DefaultLineTracker(); - tracker.set(code); - int nLines = tracker.getNumberOfLines(); - if (nLines == 1) { - return code; - } - - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < nLines; i++) { - if (i != 0) { - buf.append(lineDelim); - } - IRegion region = tracker.getLineInformation(i); - String line = code.substring(region.getOffset(), region - .getOffset() - + region.getLength()); - buf.append(line); - } - return buf.toString(); - } catch (BadLocationException e) { - // can not happen - return code; - } - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#canEvaluate(net.sourceforge.phpdt.internal.corext.template.Template) - */ - public boolean canEvaluate(Template template) { - return true; - } - - public void setCompilationUnitVariables(ICompilationUnit cu) { - setVariable(CodeTemplateContextType.FILENAME, cu.getElementName()); - setVariable(CodeTemplateContextType.PACKAGENAME, cu.getParent() - .getElementName()); - setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject() - .getElementName()); - } - - public void setFileNameVariable(String filename, String projectname) { - setVariable(CodeTemplateContextType.FILENAME, filename); - setVariable(CodeTemplateContextType.PROJECTNAME, projectname); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java deleted file mode 100644 index 67543bf..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java +++ /dev/null @@ -1,528 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -import java.util.ArrayList; - -import net.sourceforge.phpdt.core.ToolFactory; -import net.sourceforge.phpdt.core.compiler.IScanner; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; - -import org.eclipse.jface.text.templates.ContextTypeRegistry; -import org.eclipse.jface.text.templates.GlobalTemplateVariables; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.text.templates.TemplateVariable; -import org.eclipse.jface.text.templates.TemplateVariableResolver; - -/** - */ -public class CodeTemplateContextType extends TemplateContextType { - - /* context types */ - public static final String CATCHBLOCK_CONTEXTTYPE = "php_catchblock_context"; //$NON-NLS-1$ - - public static final String METHODBODY_CONTEXTTYPE = "php_methodbody_context"; //$NON-NLS-1$ - - public static final String CONSTRUCTORBODY_CONTEXTTYPE = "php_constructorbody_context"; //$NON-NLS-1$ - - public static final String GETTERBODY_CONTEXTTYPE = "php_getterbody_context"; //$NON-NLS-1$ - - public static final String SETTERBODY_CONTEXTTYPE = "php_setterbody_context"; //$NON-NLS-1$ - - public static final String NEWTYPE_CONTEXTTYPE = "php_newtype_context"; //$NON-NLS-1$ - - public static final String NEWHTML_CONTEXTTYPE = "php_newhtml_context"; //$NON-NLS-1$ - - public static final String TYPECOMMENT_CONTEXTTYPE = "php_typecomment_context"; //$NON-NLS-1$ - - public static final String FIELDCOMMENT_CONTEXTTYPE = "php_fieldcomment_context"; //$NON-NLS-1$ - - public static final String METHODCOMMENT_CONTEXTTYPE = "php_methodcomment_context"; //$NON-NLS-1$ - - public static final String CONSTRUCTORCOMMENT_CONTEXTTYPE = "php_constructorcomment_context"; //$NON-NLS-1$ - - public static final String OVERRIDECOMMENT_CONTEXTTYPE = "php_overridecomment_context"; //$NON-NLS-1$ - - public static final String GETTERCOMMENT_CONTEXTTYPE = "php_gettercomment_context"; //$NON-NLS-1$ - - public static final String SETTERCOMMENT_CONTEXTTYPE = "php_settercomment_context"; //$NON-NLS-1$ - - /* templates */ - public static final String COMMENT_SUFFIX = "comment"; //$NON-NLS-1$ - - public static final String CATCHBLOCK = "catchblock"; //$NON-NLS-1$ - - public static final String METHODSTUB = "methodbody"; //$NON-NLS-1$ - - public static final String NEWTYPE = "newtype"; //$NON-NLS-1$ - - public static final String NEWHTML = "newhtml"; //$NON-NLS-1$ - - public static final String CONSTRUCTORSTUB = "constructorbody"; //$NON-NLS-1$ - - public static final String GETTERSTUB = "getterbody"; //$NON-NLS-1$ - - public static final String SETTERSTUB = "setterbody"; //$NON-NLS-1$ - - public static final String TYPECOMMENT = "type" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String FIELDCOMMENT = "field" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String METHODCOMMENT = "method" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String CONSTRUCTORCOMMENT = "constructor" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String OVERRIDECOMMENT = "override" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String GETTERCOMMENT = "getter" + COMMENT_SUFFIX; //$NON-NLS-1$ - - public static final String SETTERCOMMENT = "setter" + COMMENT_SUFFIX; //$NON-NLS-1$ - - /* resolver types */ - public static final String EXCEPTION_TYPE = "exception_type"; //$NON-NLS-1$ - - public static final String EXCEPTION_VAR = "exception_var"; //$NON-NLS-1$ - - public static final String ENCLOSING_METHOD = "enclosing_method"; //$NON-NLS-1$ - - public static final String ENCLOSING_TYPE = "enclosing_type"; //$NON-NLS-1$ - - public static final String BODY_STATEMENT = "body_statement"; //$NON-NLS-1$ - - public static final String FIELD = "field"; //$NON-NLS-1$ - - public static final String FIELD_TYPE = "field_type"; //$NON-NLS-1$ - - public static final String BARE_FIELD_NAME = "bare_field_name"; //$NON-NLS-1$ - - public static final String PARAM = "param"; //$NON-NLS-1$ - - public static final String RETURN_TYPE = "return_type"; //$NON-NLS-1$ - - public static final String SEE_TAG = "see_to_overridden"; //$NON-NLS-1$ - - public static final String TAGS = "tags"; //$NON-NLS-1$ - - public static final String TYPENAME = "type_name"; //$NON-NLS-1$ - - public static final String FILENAME = "file_name"; //$NON-NLS-1$ - - public static final String PACKAGENAME = "package_name"; //$NON-NLS-1$ - - public static final String PROJECTNAME = "project_name"; //$NON-NLS-1$ - - public static final String PACKAGE_DECLARATION = "package_declaration"; //$NON-NLS-1$ - - public static final String TYPE_DECLARATION = "type_declaration"; //$NON-NLS-1$ - - public static final String TYPE_COMMENT = "typecomment"; //$NON-NLS-1$ - - /** - * Resolver that resolves to the variable defined in the context. - */ - public static class CodeTemplateVariableResolver extends - TemplateVariableResolver { - public CodeTemplateVariableResolver(String type, String description) { - super(type, description); - } - - protected String resolve(TemplateContext context) { - return context.getVariable(getType()); - } - } - - /** - * Resolver for javadoc tags. - */ - public static class TagsVariableResolver extends TemplateVariableResolver { - public TagsVariableResolver() { - super( - TAGS, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.tags")); //$NON-NLS-1$ - } - - protected String resolve(TemplateContext context) { - return "@"; //$NON-NLS-1$ - } - } - - /** - * Resolver for todo tags. - */ - protected static class Todo extends TemplateVariableResolver { - - public Todo() { - super( - "todo", JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ - } - - protected String resolve(TemplateContext context) { - String todoTaskTag = StubUtility - .getTodoTaskTag(((CodeTemplateContext) context) - .getJavaProject()); - if (todoTaskTag == null) - return "XXX"; //$NON-NLS-1$ - - return todoTaskTag; - } - } - - private boolean fIsComment; - - public CodeTemplateContextType(String contextName) { - super(contextName); - - fIsComment = false; - - // global - addResolver(new GlobalTemplateVariables.Dollar()); - addResolver(new GlobalTemplateVariables.Date()); - addResolver(new GlobalTemplateVariables.Year()); - addResolver(new GlobalTemplateVariables.Time()); - addResolver(new GlobalTemplateVariables.User()); - addResolver(new Todo()); - - if (CATCHBLOCK_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - EXCEPTION_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.exceptiontype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - EXCEPTION_VAR, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.exceptionvar"))); //$NON-NLS-1$ - } else if (METHODBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - BODY_STATEMENT, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ - } else if (CONSTRUCTORBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - BODY_STATEMENT, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ - } else if (GETTERBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - } else if (SETTERBODY_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PARAM, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ - } else if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - TYPENAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PACKAGE_DECLARATION, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - TYPE_DECLARATION, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - TYPE_COMMENT, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ - addCompilationUnitVariables(); - } else if (NEWHTML_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - TYPENAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PACKAGE_DECLARATION, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - TYPE_DECLARATION, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - TYPE_COMMENT, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ - addCompilationUnitVariables(); - } else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - TYPENAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new TagsVariableResolver()); - addCompilationUnitVariables(); - fIsComment = true; - } else if (FIELDCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - FIELD_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.fieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.fieldname"))); //$NON-NLS-1$ - addCompilationUnitVariables(); - fIsComment = true; - } else if (METHODCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - RETURN_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.returntype"))); //$NON-NLS-1$ - addResolver(new TagsVariableResolver()); - addCompilationUnitVariables(); - fIsComment = true; - } else if (OVERRIDECOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - SEE_TAG, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.seetag"))); //$NON-NLS-1$ - addResolver(new TagsVariableResolver()); - addCompilationUnitVariables(); - fIsComment = true; - } else if (CONSTRUCTORCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new TagsVariableResolver()); - addCompilationUnitVariables(); - fIsComment = true; - } else if (GETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - BARE_FIELD_NAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ - addCompilationUnitVariables(); - fIsComment = true; - } else if (SETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD_TYPE, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - FIELD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - ENCLOSING_METHOD, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PARAM, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - BARE_FIELD_NAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ - addCompilationUnitVariables(); - fIsComment = true; - } - } - - private void addCompilationUnitVariables() { - addResolver(new CodeTemplateVariableResolver( - FILENAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.filename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PACKAGENAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.packagename"))); //$NON-NLS-1$ - addResolver(new CodeTemplateVariableResolver( - PROJECTNAME, - JavaTemplateMessages - .getString("CodeTemplateContextType.variable.description.projectname"))); //$NON-NLS-1$ - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validateVariables(net.sourceforge.phpdt.internal.corext.template.TemplateVariable[]) - */ - protected void validateVariables(TemplateVariable[] variables) - throws TemplateException { - ArrayList required = new ArrayList(5); - //String contextName = getId(); - // if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { - // required.add(PACKAGE_DECLARATION); - // required.add(TYPE_DECLARATION); - // } - for (int i = 0; i < variables.length; i++) { - String type = variables[i].getType(); - if (getResolver(type) == null) { - throw new TemplateException( - JavaTemplateMessages - .getFormattedString( - "CodeTemplateContextType.validate.unknownvariable", type)); //$NON-NLS-1$ - } - required.remove(type); - } - if (!required.isEmpty()) { - String missing = (String) required.get(0); - throw new TemplateException( - JavaTemplateMessages - .getFormattedString( - "CodeTemplateContextType.validate.missingvariable", missing)); //$NON-NLS-1$ - } - super.validateVariables(variables); - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.corext.template.ContextType#createContext() - */ -// public TemplateContext createContext() { -// return null; -// } - - public static void registerContextTypes(ContextTypeRegistry registry) { - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.CATCHBLOCK_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.METHODBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.CONSTRUCTORBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.GETTERBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.SETTERBODY_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.NEWTYPE_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.NEWHTML_CONTEXTTYPE)); - - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.METHODCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.CONSTRUCTORCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.OVERRIDECOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.GETTERCOMMENT_CONTEXTTYPE)); - registry.addContextType(new CodeTemplateContextType( - CodeTemplateContextType.SETTERCOMMENT_CONTEXTTYPE)); - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validate(java.lang.String) - */ - public void validate(String pattern) throws TemplateException { - super.validate(pattern); - if (fIsComment) { - if (!isValidComment(pattern)) { - throw new TemplateException( - JavaTemplateMessages - .getString("CodeTemplateContextType.validate.invalidcomment")); //$NON-NLS-1$ - } - } - } - - private boolean isValidComment(String template) { - IScanner scanner = ToolFactory.createScanner(true, false, false, true);// false); - scanner.setSource(template.toCharArray()); - try { - int next = scanner.getNextToken(); - while (next == ITerminalSymbols.TokenNameCOMMENT_LINE - || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC - || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { - next = scanner.getNextToken(); - } - return next == ITerminalSymbols.TokenNameEOF; - } catch (InvalidInputException e) { - } - return false; - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java deleted file mode 100644 index 700b4ac..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -import java.io.File; -import java.io.InputStream; -import java.util.ResourceBundle; - -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -//import org.eclipse.jface.text.templates.Template; - -/** - * CodeTemplates gives access to the available code templates. - * - * @since 3.0 - * @deprecated use - * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getCodeTemplateStore()} - * instead - */ -public class CodeTemplates extends - net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { - - private static final String DEFAULT_FILE = "default-codetemplates.xml"; //$NON-NLS-1$ - - private static final String TEMPLATE_FILE = "codetemplates.xml"; //$NON-NLS-1$ - - private static final ResourceBundle fgResourceBundle = ResourceBundle - .getBundle(JavaTemplateMessages.class.getName()); - - /** Singleton. */ - private static CodeTemplates fgTemplates; - -// public static Template getCodeTemplate(String name) { -// return getInstance().getFirstTemplate(name); -// } - - /** - * Returns an instance of templates. - */ - public static CodeTemplates getInstance() { - if (fgTemplates == null) - fgTemplates = new CodeTemplates(); - - return fgTemplates; - } - - private CodeTemplates() { - super( - "codetemplate", WebUI.getDefault().getCodeTemplateContextRegistry()); //$NON-NLS-1$ - create(); - } - - private void create() { - - try { - addFromStream(getDefaultsAsStream(), false, true, fgResourceBundle); - File templateFile = getTemplateFile(); - if (templateFile.exists()) { - addFromFile(templateFile, false, fgResourceBundle); - } - saveToFile(templateFile); - - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - clear(); - } - - } - - /** - * Resets the template set. - */ - public void reset() throws CoreException { - clear(); - addFromFile(getTemplateFile(), false, fgResourceBundle); - } - - /** - * Resets the template set with the default templates. - */ -// public void restoreDefaults() throws CoreException { -// clear(); -// addFromStream(getDefaultsAsStream(), false, true, fgResourceBundle); -// } - - /** - * Saves the template set. - */ -// public void save() throws CoreException { -// saveToFile(getTemplateFile()); -// } - - private static InputStream getDefaultsAsStream() { - return CodeTemplates.class.getResourceAsStream(DEFAULT_FILE); - } - - private static File getTemplateFile() { - IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); - path = path.append(TEMPLATE_FILE); - - return path.toFile(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java deleted file mode 100644 index 5c6f25c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java +++ /dev/null @@ -1,664 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -//import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.core.ICompilationUnit; -//import net.sourceforge.phpdt.internal.corext.Assert; -//import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitCompletion.LocalVariable; -import net.sourceforge.phpdt.internal.corext.util.Strings; -import net.sourceforge.phpdt.internal.ui.preferences.CodeFormatterPreferencePage; -import net.sourceforge.phpdt.internal.ui.text.template.contentassist.MultiVariable; -//import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -//import org.eclipse.jface.dialogs.MessageDialog; -//import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateBuffer; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.text.templates.TemplateTranslator; -import org.eclipse.jface.text.templates.TemplateVariable; -//import org.eclipse.swt.widgets.Shell; - -/** - * A context for java source. - */ -public class JavaContext extends CompilationUnitContext { - - /** The platform default line delimiter. */ - private static final String PLATFORM_LINE_DELIMITER = System - .getProperty("line.separator"); //$NON-NLS-1$ - - /** A code completion requestor for guessing local variable names. */ - //private CompilationUnitCompletion fCompletion; - - /** - * Creates a java template context. - * - * @param type - * the context type. - * @param document - * the document. - * @param completionOffset - * the completion offset within the document. - * @param completionLength - * the completion length. - * @param compilationUnit - * the compilation unit (may be null). - */ - public JavaContext(TemplateContextType type, IDocument document, - int completionOffset, int completionLength, - ICompilationUnit compilationUnit) { - super(type, document, completionOffset, completionLength, - compilationUnit); - } - - /** - * Returns the indentation level at the position of code completion. - */ - private int getIndentation() { - int start = getStart(); - IDocument document = getDocument(); - try { - IRegion region = document.getLineInformationOfOffset(start); - String lineContent = document.get(region.getOffset(), region - .getLength()); - return Strings.computeIndent(lineContent, - CodeFormatterPreferencePage.getTabSize()); - // return Strings.computeIndent(lineContent, - // CodeFormatterUtil.getTabWidth()); - } catch (BadLocationException e) { - return 0; - } - } - - /* - * @see TemplateContext#evaluate(Template template) - */ - public TemplateBuffer evaluate(Template template) - throws BadLocationException, TemplateException { - - if (!canEvaluate(template)) - throw new TemplateException(JavaTemplateMessages - .getString("Context.error.cannot.evaluate")); //$NON-NLS-1$ - - TemplateTranslator translator = new TemplateTranslator() { - /* - * @see org.eclipse.jface.text.templates.TemplateTranslator#createVariable(java.lang.String, - * java.lang.String, int[]) - */ - protected TemplateVariable createVariable(String type, String name, - int[] offsets) { - return new MultiVariable(type, name, offsets); - } - }; - TemplateBuffer buffer = translator.translate(template); - - getContextType().resolve(buffer, this); - String lineDelimiter = null; - try { - lineDelimiter = getDocument().getLineDelimiter(0); - } catch (BadLocationException e) { - } - - if (lineDelimiter == null) - lineDelimiter = PLATFORM_LINE_DELIMITER; -// IPreferenceStore prefs = WebUI.getDefault() -// .getPreferenceStore(); - // axelcl start - // boolean useCodeFormatter = - // prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER); - boolean useCodeFormatter = false; - // axelcl end - - JavaFormatter formatter = new JavaFormatter(lineDelimiter, - getIndentation(), useCodeFormatter); - formatter.format(buffer, this); - // debug start - // String res = buffer.getString(); - // res = res.replaceAll("\n","/n"); - // res = res.replaceAll("\t","/t"); - // System.out.println(res); - // debug end - return buffer; - } - - /* - * @see TemplateContext#canEvaluate(Template templates) - */ - public boolean canEvaluate(Template template) { - String key = getKey(); - - if (fForceEvaluation) - return true; - - return template.matches(key, getContextType().getId()) - && key.length() != 0 - && template.getName().toLowerCase().startsWith( - key.toLowerCase()); - } - - public boolean canEvaluate(String identifier) { - String prefix = getKey(); - return identifier.toLowerCase().startsWith(prefix.toLowerCase()); - } - - /* - * @see DocumentTemplateContext#getCompletionPosition(); - */ - public int getStart() { - - try { - IDocument document = getDocument(); - - if (getCompletionLength() == 0) { - - int start = getCompletionOffset(); - while ((start != 0) - && Character.isUnicodeIdentifierPart(document - .getChar(start - 1))) - start--; - - if ((start != 0) - && (Character.isUnicodeIdentifierStart(document - .getChar(start - 1)) || (document - .getChar(start - 1) == '$'))) - start--; - - return start; - - } else { - - int start = getCompletionOffset(); - int end = getCompletionOffset() + getCompletionLength(); - - while (start != 0 - && Character.isUnicodeIdentifierPart(document - .getChar(start - 1))) - start--; - if ((start != 0) - && (Character.isUnicodeIdentifierStart(document - .getChar(start - 1)) || (document - .getChar(start - 1) == '$'))) - start--; - while (start != end - && Character.isWhitespace(document.getChar(start))) - start++; - - if (start == end) - start = getCompletionOffset(); - - return start; - } - - } catch (BadLocationException e) { - return super.getStart(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() - */ - public int getEnd() { - - if (getCompletionLength() == 0) - return super.getEnd(); - - try { - IDocument document = getDocument(); - - int start = getCompletionOffset(); - int end = getCompletionOffset() + getCompletionLength(); - - while (start != end - && Character.isWhitespace(document.getChar(end - 1))) - end--; - - return end; - - } catch (BadLocationException e) { - return super.getEnd(); - } - } - - /* - * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() - */ - public String getKey() { - - // if (getCompletionLength() == 0) { - // return super.getKey(); - // } - - try { - IDocument document = getDocument(); - - int start = getStart(); - int end = getCompletionOffset(); - return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ - - } catch (BadLocationException e) { - return super.getKey(); - } - } - - /** - * Returns the character before start position of completion. - */ - public char getCharacterBeforeStart() { - int start = getStart(); - - try { - return start == 0 ? ' ' : getDocument().getChar(start - 1); - - } catch (BadLocationException e) { - return ' '; - } - } - -// private static void handleException(Shell shell, Exception e) { -// String title = JavaTemplateMessages -// .getString("JavaContext.error.title"); //$NON-NLS-1$ -// if (e instanceof CoreException) -// ExceptionHandler.handle((CoreException) e, shell, title, null); -// else if (e instanceof InvocationTargetException) -// ExceptionHandler.handle((InvocationTargetException) e, shell, -// title, null); -// else { -// PHPeclipsePlugin.log(e); -// MessageDialog.openError(shell, title, e.getMessage()); -// } -// } - - // private CompilationUnitCompletion getCompletion() { - // ICompilationUnit compilationUnit= getCompilationUnit(); - // if (fCompletion == null) { - // fCompletion= new CompilationUnitCompletion(compilationUnit); - // - // if (compilationUnit != null) { - // try { - // compilationUnit.codeComplete(getStart(), fCompletion); - // } catch (JavaModelException e) { - // // ignore - // } - // } - // } - // - // return fCompletion; - // } - - /** - * Returns the name of a guessed local array, null if no - * local array exists. - */ - // public String guessArray() { - // return firstOrNull(guessArrays()); - // } - /** - * Returns the name of a guessed local array, null if no - * local array exists. - */ - // public String[] guessArrays() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[] ret= new String[localArrays.length]; - // for (int i= 0; i < ret.length; i++) { - // ret[ret.length - i - 1]= localArrays[i].name; - // } - // return ret; - // } - /** - * Returns the name of the type of a local array, null if no - * local array exists. - */ - // public String guessArrayType() { - // return firstOrNull(guessArrayTypes()); - // } -// private String firstOrNull(String[] strings) { -// if (strings.length > 0) -// return strings[0]; -// else -// return null; -// } - - /** - * Returns the name of the type of a local array, null if no - * local array exists. - */ - // public String[][] guessGroupedArrayTypes() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[][] ret= new String[localArrays.length][]; - // - // for (int i= 0; i < localArrays.length; i++) { - // String type= getArrayTypeFromLocalArray(completion, - // localArrays[localArrays.length - i - 1]); - // ret[i]= new String[] {type}; - // } - // - // return ret; - // } - /** - * Returns the name of the type of a local array, null if no - * local array exists. - */ - // public String[] guessArrayTypes() { - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // List ret= new ArrayList(); - // - // for (int i= 0; i < localArrays.length; i++) { - // String type= getArrayTypeFromLocalArray(completion, - // localArrays[localArrays.length - i - 1]); - // if (!ret.contains(type)) - // ret.add(type); - // } - // - // return (String[]) ret.toArray(new String[ret.size()]); - // } -// private String getArrayTypeFromLocalArray( -// CompilationUnitCompletion completion, LocalVariable array) { -// String arrayTypeName = array.typeName; -// String typeName = getScalarType(arrayTypeName); -// int dimension = getArrayDimension(arrayTypeName) - 1; -// Assert.isTrue(dimension >= 0); -// -// String qualifiedName = createQualifiedTypeName(array.typePackageName, -// typeName); -// String innerTypeName = completion.simplifyTypeName(qualifiedName); -// -// return innerTypeName == null ? createArray(typeName, dimension) -// : createArray(innerTypeName, dimension); -// } - -// private static String createArray(String type, int dimension) { -// StringBuffer buffer = new StringBuffer(type); -// for (int i = 0; i < dimension; i++) -// buffer.append("[]"); //$NON-NLS-1$ -// return buffer.toString(); -// } - -// private static String getScalarType(String type) { -// return type.substring(0, type.indexOf('[')); -// } - -// private static int getArrayDimension(String type) { -// -// int dimension = 0; -// int index = type.indexOf('['); -// -// while (index != -1) { -// dimension++; -// index = type.indexOf('[', index + 1); -// } -// -// return dimension; -// } - -// private static String createQualifiedTypeName(String packageName, -// String className) { -// StringBuffer buffer = new StringBuffer(); -// -// if (packageName.length() != 0) { -// buffer.append(packageName); -// buffer.append('.'); -// } -// buffer.append(className); -// -// return buffer.toString(); -// } - - /** - * Returns a proposal for a variable name of a local array element, - * null if no local array exists. - */ - // public String guessArrayElement() { - // return firstOrNull(guessArrayElements()); - // } - /** - * Returns a proposal for a variable name of a local array element, - * null if no local array exists. - */ - // public String[] guessArrayElements() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return new String[0]; - // } - // - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // List ret= new ArrayList(); - // - // for (int i= 0; i < localArrays.length; i++) { - // int idx= localArrays.length - i - 1; - // - // LocalVariable var= localArrays[idx]; - // - // IJavaProject project= cu.getJavaProject(); - // String typeName= var.typeName; - // String baseTypeName= typeName.substring(0, typeName.lastIndexOf('[')); - // - // String indexName= getIndex(); - // String[] excludedNames= completion.getLocalVariableNames(); - // if (indexName != null) { - // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); - // excludedNamesList.add(indexName); - // excludedNames= (String[])excludedNamesList.toArray(new - // String[excludedNamesList.size()]); - // } - // String[] proposals= NamingConventions.suggestLocalVariableNames(project, - // var.typePackageName, baseTypeName, 0, excludedNames); - // for (int j= 0; j < proposals.length; j++) { - // if (!ret.contains(proposals[j])) - // ret.add(proposals[j]); - // } - // } - // - // return (String[]) ret.toArray(new String[ret.size()]); - // } - /** - * Returns a proposal for a variable name of a local array element, - * null if no local array exists. - */ - // public String[][] guessGroupedArrayElements() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return new String[0][]; - // } - // - // CompilationUnitCompletion completion= getCompletion(); - // LocalVariable[] localArrays= completion.findLocalArrays(); - // - // String[][] ret= new String[localArrays.length][]; - // - // for (int i= 0; i < localArrays.length; i++) { - // int idx= localArrays.length - i - 1; - // - // LocalVariable var= localArrays[idx]; - // - // IJavaProject project= cu.getJavaProject(); - // String typeName= var.typeName; - // int dim= -1; // we expect at least one array - // int lastIndex= typeName.length(); - // int bracket= typeName.lastIndexOf('['); - // while (bracket != -1) { - // lastIndex= bracket; - // dim++; - // bracket= typeName.lastIndexOf('[', bracket - 1); - // } - // typeName= typeName.substring(0, lastIndex); - // - // String indexName= getIndex(); - // String[] excludedNames= completion.getLocalVariableNames(); - // if (indexName != null) { - // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); - // excludedNamesList.add(indexName); - // excludedNames= (String[])excludedNamesList.toArray(new - // String[excludedNamesList.size()]); - // } - // String[] proposals= NamingConventions.suggestLocalVariableNames(project, - // var.typePackageName, typeName, dim, excludedNames); - // - // ret[i]= proposals; - // } - // - // return ret; - // } - /** - * Returns an array index name. 'i', 'j', 'k' are tried until no name - * collision with an existing local variable occurs. If all names collide, - * null is returned. - */ - // public String getIndex() { - // CompilationUnitCompletion completion= getCompletion(); - // String[] proposals= {"i", "j", "k"}; //$NON-NLS-1$ //$NON-NLS-2$ - // //$NON-NLS-3$ - // - // for (int i= 0; i != proposals.length; i++) { - // String proposal = proposals[i]; - // - // if (!completion.existsLocalName(proposal)) - // return proposal; - // } - // - // return null; - // } - /** - * Returns the name of a local collection, null if no local - * collection exists. - */ - // public String guessCollection() { - // return firstOrNull(guessCollections()); - // } - /** - * Returns the names of local collections. - */ - // public String[] guessCollections() { - // CompilationUnitCompletion completion= getCompletion(); - // try { - // LocalVariable[] localCollections= completion.findLocalCollections(); - // String[] ret= new String[localCollections.length]; - // for (int i= 0; i < ret.length; i++) { - // ret[ret.length - i - 1]= localCollections[i].name; - // } - // - // return ret; - // - // } catch (JavaModelException e) { - // JavaPlugin.log(e); - // } - // - // return new String[0]; - // } - /** - * Returns an iterator name ('iter'). If 'iter' already exists as local - * variable, null is returned. - */ - // public String getIterator() { - // CompilationUnitCompletion completion= getCompletion(); - // String[] proposals= {"iter"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - // - // for (int i= 0; i != proposals.length; i++) { - // String proposal = proposals[i]; - // - // if (!completion.existsLocalName(proposal)) - // return proposal; - // } - // - // return null; - // } - // public void addIteratorImport() { - // ICompilationUnit cu= getCompilationUnit(); - // if (cu == null) { - // return; - // } - // - // try { - // Position position= new Position(getCompletionOffset(), - // getCompletionLength()); - // IDocument document= getDocument(); - // final String category= "__template_position_importer" + - // System.currentTimeMillis(); //$NON-NLS-1$ - // IPositionUpdater updater= new DefaultPositionUpdater(category); - // document.addPositionCategory(category); - // document.addPositionUpdater(updater); - // document.addPosition(position); - // - // CodeGenerationSettings settings= - // JavaPreferencesSettings.getCodeGenerationSettings(); - // ImportsStructure structure= new ImportsStructure(cu, - // settings.importOrder, settings.importThreshold, true); - // structure.addImport("java.util.Iterator"); //$NON-NLS-1$ - // structure.create(false, null); - // - // document.removePosition(position); - // document.removePositionUpdater(updater); - // document.removePositionCategory(category); - // - // setCompletionOffset(position.getOffset()); - // setCompletionLength(position.getLength()); - // - // } catch (CoreException e) { - // handleException(null, e); - // } catch (BadLocationException e) { - // handleException(null, e); - // } catch (BadPositionCategoryException e) { - // handleException(null, e); - // } - // } - /** - * Evaluates a 'java' template in thecontext of a compilation unit - */ - public static String evaluateTemplate(Template template, - ICompilationUnit compilationUnit, int position) - throws CoreException, BadLocationException, TemplateException { - - TemplateContextType contextType = WebUI.getDefault() - .getTemplateContextRegistry().getContextType("java"); //$NON-NLS-1$ - if (contextType == null) - throw new CoreException( - new Status( - IStatus.ERROR, - PHPeclipsePlugin.PLUGIN_ID, - IStatus.ERROR, - JavaTemplateMessages - .getString("JavaContext.error.message"), null)); //$NON-NLS-1$ - - IDocument document = new Document(); - if (compilationUnit != null && compilationUnit.exists()) - document.set(compilationUnit.getSource()); - - JavaContext context = new JavaContext(contextType, document, position, - 0, compilationUnit); - context.setForceEvaluation(true); - - TemplateBuffer buffer = context.evaluate(template); - if (buffer == null) - return null; - return buffer.getString(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java deleted file mode 100644 index 7063273..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java +++ /dev/null @@ -1,393 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.internal.corext.util.CodeFormatterUtil; -import net.sourceforge.phpdt.internal.corext.util.Strings; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; -import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.templates.DocumentTemplateContext; -import org.eclipse.jface.text.templates.GlobalTemplateVariables; -import org.eclipse.jface.text.templates.TemplateBuffer; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.jface.text.templates.TemplateVariable; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.RangeMarker; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; - -/** - * A template editor using the Java formatter to format a template buffer. - */ -public class JavaFormatter { - - private static final String MARKER = "/*${" + GlobalTemplateVariables.Cursor.NAME + "}*/"; //$NON-NLS-1$ //$NON-NLS-2$ - - /** The line delimiter to use if code formatter is not used. */ - private final String fLineDelimiter; - - /** The initial indent level */ - private final int fInitialIndentLevel; - - /** The java partitioner */ - private boolean fUseCodeFormatter; - - /** - * Creates a JavaFormatter with the target line delimiter. - * - * @param lineDelimiter - * the line delimiter to use - * @param initialIndentLevel - * the initial indentation level - * @param useCodeFormatter - * true if the core code formatter should be used - */ - public JavaFormatter(String lineDelimiter, int initialIndentLevel, - boolean useCodeFormatter) { - fLineDelimiter = lineDelimiter; - fUseCodeFormatter = useCodeFormatter; - fInitialIndentLevel = initialIndentLevel; - } - - /** - * Formats the template buffer. - * - * @param buffer - * @param context - * @throws BadLocationException - */ - public void format(TemplateBuffer buffer, TemplateContext context) - throws BadLocationException { - try { - if (fUseCodeFormatter) - // try to format and fall back to indenting - try { - format(buffer, (JavaContext) context); - } catch (BadLocationException e) { - indent(buffer); - } catch (MalformedTreeException e) { - indent(buffer); - } - else - indent(buffer); - - // don't trim the buffer if the replacement area is empty - // case: surrounding empty lines with block - if (context instanceof DocumentTemplateContext) { - DocumentTemplateContext dtc = (DocumentTemplateContext) context; - if (dtc.getStart() == dtc.getCompletionOffset()) - if (dtc.getDocument().get(dtc.getStart(), - dtc.getEnd() - dtc.getEnd()).trim().length() == 0) - return; - } - - trimBegin(buffer); - } catch (MalformedTreeException e) { - throw new BadLocationException(); - } - } - - private static int getCaretOffset(TemplateVariable[] variables) { - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - - if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) - return variable.getOffsets()[0]; - } - - return -1; - } - - private boolean isInsideCommentOrString(String string, int offset) { - - IDocument document = new Document(string); - WebUI.getDefault().getJavaTextTools() - .setupJavaDocumentPartitioner(document); - - try { - ITypedRegion partition = document.getPartition(offset); - String partitionType = partition.getType(); - - return partitionType != null - && (partitionType - .equals(IPHPPartitions.PHP_MULTILINE_COMMENT) - || partitionType - .equals(IPHPPartitions.PHP_SINGLELINE_COMMENT) - || partitionType - .equals(IPHPPartitions.PHP_STRING_DQ) - || partitionType - .equals(IPHPPartitions.PHP_STRING_SQ) - || partitionType - .equals(IPHPPartitions.PHP_STRING_HEREDOC) || partitionType - .equals(IPHPPartitions.PHP_PHPDOC_COMMENT)); - - } catch (BadLocationException e) { - return false; - } - } - - private void format(TemplateBuffer templateBuffer, JavaContext context) - throws BadLocationException { - // XXX 4360, 15247 - // workaround for code formatter limitations - // handle a special case where cursor position is surrounded by - // whitespaces - - String string = templateBuffer.getString(); - TemplateVariable[] variables = templateBuffer.getVariables(); - - int caretOffset = getCaretOffset(variables); - if ((caretOffset > 0) - && Character.isWhitespace(string.charAt(caretOffset - 1)) - && (caretOffset < string.length()) - && Character.isWhitespace(string.charAt(caretOffset)) - && !isInsideCommentOrString(string, caretOffset)) { - List positions = variablesToPositions(variables); - - TextEdit insert = new InsertEdit(caretOffset, MARKER); - string = edit(string, positions, insert); - positionsToVariables(positions, variables); - templateBuffer.setContent(string, variables); - - plainFormat(templateBuffer, context); - - string = templateBuffer.getString(); - variables = templateBuffer.getVariables(); - caretOffset = getCaretOffset(variables); - - positions = variablesToPositions(variables); - TextEdit delete = new DeleteEdit(caretOffset, MARKER.length()); - string = edit(string, positions, delete); - positionsToVariables(positions, variables); - templateBuffer.setContent(string, variables); - - } else { - plainFormat(templateBuffer, context); - } - } - - private void plainFormat(TemplateBuffer templateBuffer, JavaContext context) - throws BadLocationException { - } - - // private void plainFormat(TemplateBuffer templateBuffer, JavaContext - // context) throws BadLocationException { - // - // IDocument doc= new Document(templateBuffer.getString()); - // - // TemplateVariable[] variables= templateBuffer.getVariables(); - // - // List offsets= variablesToPositions(variables); - // - // Map options; - // if (context.getCompilationUnit() != null) - // options= context.getCompilationUnit().getJavaProject().getOptions(true); - // else - // options= JavaCore.getOptions(); - // - // TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_UNKNOWN, - // doc.get(), fInitialIndentLevel, fLineDelimiter, options); - // if (edit == null) - // throw new BadLocationException(); // fall back to indenting - // - // MultiTextEdit root; - // if (edit instanceof MultiTextEdit) - // root= (MultiTextEdit) edit; - // else { - // root= new MultiTextEdit(0, doc.getLength()); - // root.addChild(edit); - // } - // for (Iterator it= offsets.iterator(); it.hasNext();) { - // TextEdit position= (TextEdit) it.next(); - // try { - // root.addChild(position); - // } catch (MalformedTreeException e) { - // // position conflicts with formatter edit - // // ignore this position - // } - // } - // - // root.apply(doc, TextEdit.UPDATE_REGIONS); - // - // positionsToVariables(offsets, variables); - // - // templateBuffer.setContent(doc.get(), variables); - // } - - private void indent(TemplateBuffer templateBuffer) - throws BadLocationException, MalformedTreeException { - - TemplateVariable[] variables = templateBuffer.getVariables(); - List positions = variablesToPositions(variables); - - IDocument document = new Document(templateBuffer.getString()); - MultiTextEdit root = new MultiTextEdit(0, document.getLength()); - root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions - .size()])); - - JavaHeuristicScanner scanner = new JavaHeuristicScanner(document); - JavaIndenter indenter = new JavaIndenter(document, scanner); - - // first line - int offset = document.getLineOffset(0); - TextEdit edit = new InsertEdit(offset, CodeFormatterUtil - .createIndentString(fInitialIndentLevel)); - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - - formatDelimiter(document, root, 0); - - // following lines - int lineCount = document.getNumberOfLines(); - - for (int line = 1; line < lineCount; line++) { - IRegion region = document.getLineInformation(line); - offset = region.getOffset(); - StringBuffer indent = indenter.computeIndentation(offset); - if (indent == null) - continue; - // axelcl delete start - // int nonWS = - // scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + - // region.getLength()); - // if (nonWS == JavaHeuristicScanner.NOT_FOUND) - // continue; - // edit = new ReplaceEdit(offset, nonWS - offset, - // indent.toString()); - // axelcl delete end - // axelcl insert start - int nonWS = offset; - edit = new ReplaceEdit(offset, nonWS - offset, CodeFormatterUtil - .createIndentString(fInitialIndentLevel)); - // axelcl insert end - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - - formatDelimiter(document, root, line); - } - - positionsToVariables(positions, variables); - templateBuffer.setContent(document.get(), variables); - } - - /** - * Changes the delimiter to the configured line delimiter. - * - * @param document - * the temporary document being edited - * @param root - * the root edit containing all positions that will be updated - * along the way - * @param line - * the line to format - * @throws BadLocationException - * if applying the changes fails - */ - private void formatDelimiter(IDocument document, MultiTextEdit root, - int line) throws BadLocationException { - IRegion region = document.getLineInformation(line); - String lineDelimiter = document.getLineDelimiter(line); - if (lineDelimiter != null) { - TextEdit edit = new ReplaceEdit(region.getOffset() - + region.getLength(), lineDelimiter.length(), - fLineDelimiter); - root.addChild(edit); - root.apply(document, TextEdit.UPDATE_REGIONS); - root.removeChild(edit); - } - } - - private static void trimBegin(TemplateBuffer templateBuffer) - throws BadLocationException { - String string = templateBuffer.getString(); - TemplateVariable[] variables = templateBuffer.getVariables(); - - List positions = variablesToPositions(variables); - - int i = 0; - while ((i != string.length()) - && Character.isWhitespace(string.charAt(i))) - i++; - - string = edit(string, positions, new DeleteEdit(0, i)); - positionsToVariables(positions, variables); - - templateBuffer.setContent(string, variables); - } - - private static String edit(String string, List positions, TextEdit edit) - throws BadLocationException { - MultiTextEdit root = new MultiTextEdit(0, string.length()); - root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions - .size()])); - root.addChild(edit); - IDocument document = new Document(string); - root.apply(document); - - return document.get(); - } - - private static List variablesToPositions(TemplateVariable[] variables) { - List positions = new ArrayList(5); - for (int i = 0; i != variables.length; i++) { - int[] offsets = variables[i].getOffsets(); - - // trim positions off whitespace - String value = variables[i].getDefaultValue(); - int wsStart = 0; - while (wsStart < value.length() - && Character.isWhitespace(value.charAt(wsStart)) - && !Strings.isLineDelimiterChar(value.charAt(wsStart))) - wsStart++; - - variables[i].getValues()[0] = value.substring(wsStart); - - for (int j = 0; j != offsets.length; j++) { - offsets[j] += wsStart; - positions.add(new RangeMarker(offsets[j], 0)); - } - } - return positions; - } - - private static void positionsToVariables(List positions, - TemplateVariable[] variables) { - Iterator iterator = positions.iterator(); - - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - - int[] offsets = new int[variable.getOffsets().length]; - for (int j = 0; j != offsets.length; j++) - offsets[j] = ((TextEdit) iterator.next()).getOffset(); - - variable.setOffsets(offsets); - } - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java deleted file mode 100644 index 98a9e42..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java +++ /dev/null @@ -1,109 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.corext.template.php; - -import java.io.File; -//import java.io.InputStream; -import java.util.ResourceBundle; - -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; - -/** - * Templates gives access to the available templates. - * - * @deprecated As of 3.0, replaced by - * {@link org.eclipse.jface.text.templates.persistence.TemplateStore} - */ -public class Templates extends - net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { - - //private static final String DEFAULT_FILE = "default-templates.xml"; //$NON-NLS-1$ - - private static final String TEMPLATE_FILE = "templates.xml"; //$NON-NLS-1$ - - private static final ResourceBundle fgResourceBundle = ResourceBundle - .getBundle(JavaTemplateMessages.class.getName()); - - /** Singleton. */ - private static Templates fgTemplates; - - /** - * Returns an instance of templates. - * - * @deprecated As of 3.0, replaced by - * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getTemplateStore()} - */ - public static Templates getInstance() { - if (fgTemplates == null) - fgTemplates = new Templates(); - - return fgTemplates; - } - - public Templates() { - super( - "template", WebUI.getDefault().getTemplateContextRegistry()); //$NON-NLS-1$ - create(); - } - - private void create() { - - try { - File templateFile = getTemplateFile(); - if (templateFile.exists()) { - addFromFile(templateFile, true, fgResourceBundle); - } - - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - clear(); - } - - } - - /** - * Resets the template set. - */ - public void reset() throws CoreException { - clear(); - addFromFile(getTemplateFile(), true, fgResourceBundle); - } - - /** - * Resets the template set with the default templates. - */ -// public void restoreDefaults() throws CoreException { -// clear(); -// addFromStream(getDefaultsAsStream(), true, true, fgResourceBundle); -// } - - /** - * Saves the template set. - */ -// public void save() throws CoreException { -// saveToFile(getTemplateFile()); -// } - -// private static InputStream getDefaultsAsStream() { -// return Templates.class.getResourceAsStream(DEFAULT_FILE); -// } - - private static File getTemplateFile() { - IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); - path = path.append(TEMPLATE_FILE); - - return path.toFile(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java deleted file mode 100644 index 7b6eaa6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java +++ /dev/null @@ -1,763 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -/** - * Help context ids for the Java UI. - *

- * This interface contains constants only; it is not intended to be implemented - * or extended. - *

- * - */ -public interface IJavaHelpContextIds { - public static final String PREFIX = WebUI.PLUGIN_ID + '.'; - - // Actions - public static final String GETTERSETTER_ACTION = PREFIX - + "getter_setter_action_context"; //$NON-NLS-1$ - - public static final String ADD_METHODSTUB_ACTION = PREFIX - + "add_methodstub_action_context"; //$NON-NLS-1$ - - public static final String ADD_UNIMPLEMENTED_METHODS_ACTION = PREFIX - + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ - - public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION = PREFIX - + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ - - public static final String SHOW_IN_PACKAGEVIEW_ACTION = PREFIX - + "show_in_packageview_action_context"; //$NON-NLS-1$ - - public static final String SHOW_IN_HIERARCHYVIEW_ACTION = PREFIX - + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ - - public static final String FOCUS_ON_SELECTION_ACTION = PREFIX - + "focus_on_selection_action"; //$NON-NLS-1$ - - public static final String FOCUS_ON_TYPE_ACTION = PREFIX - + "focus_on_type_action"; //$NON-NLS-1$ - - public static final String TYPEHIERARCHY_HISTORY_ACTION = PREFIX - + "typehierarchy_history_action"; //$NON-NLS-1$ - - public static final String FILTER_PUBLIC_ACTION = PREFIX - + "filter_public_action"; //$NON-NLS-1$ - - public static final String FILTER_FIELDS_ACTION = PREFIX - + "filter_fields_action"; //$NON-NLS-1$ - - public static final String FILTER_STATIC_ACTION = PREFIX - + "filter_static_action"; //$NON-NLS-1$ - - public static final String SHOW_INHERITED_ACTION = PREFIX - + "show_inherited_action"; //$NON-NLS-1$ - - public static final String SHOW_SUPERTYPES = PREFIX - + "show_supertypes_action"; //$NON-NLS-1$ - - public static final String SHOW_SUBTYPES = PREFIX + "show_subtypes_action"; //$NON-NLS-1$ - - public static final String SHOW_HIERARCHY = PREFIX - + "show_hierarchy_action"; //$NON-NLS-1$ - - public static final String ENABLE_METHODFILTER_ACTION = PREFIX - + "enable_methodfilter_action"; //$NON-NLS-1$ - - public static final String ADD_IMPORT_ON_SELECTION_ACTION = PREFIX - + "add_imports_on_selection_action_context"; //$NON-NLS-1$ - - public static final String ORGANIZE_IMPORTS_ACTION = PREFIX - + "organize_imports_action_context"; //$NON-NLS-1$ - - public static final String ADD_TO_CLASSPATH_ACTION = PREFIX - + "addjtoclasspath_action_context"; //$NON-NLS-1$ - - public static final String REMOVE_FROM_CLASSPATH_ACTION = PREFIX - + "removefromclasspath_action_context"; //$NON-NLS-1$ - - public static final String TOGGLE_PRESENTATION_ACTION = PREFIX - + "toggle_presentation_action_context"; //$NON-NLS-1$ - - public static final String TOGGLE_TEXTHOVER_ACTION = PREFIX - + "toggle_texthover_action_context"; //$NON-NLS-1$ - - public static final String OPEN_CLASS_WIZARD_ACTION = PREFIX - + "open_class_wizard_action"; //$NON-NLS-1$ - - public static final String OPEN_INTERFACE_WIZARD_ACTION = PREFIX - + "open_interface_wizard_action"; //$NON-NLS-1$ - - public static final String SORT_MEMBERS_ACTION = PREFIX - + "sort_members_action"; //$NON-NLS-1$ - - public static final String OPEN_PACKAGE_WIZARD_ACTION = PREFIX - + "open_package_wizard_action"; //$NON-NLS-1$ - - public static final String OPEN_PROJECT_WIZARD_ACTION = PREFIX - + "open_project_wizard_action"; //$NON-NLS-1$ - - public static final String OPEN_SNIPPET_WIZARD_ACTION = PREFIX - + "open_snippet_wizard_action"; //$NON-NLS-1$ - - public static final String EDIT_WORKING_SET_ACTION = PREFIX - + "edit_working_set_action"; //$NON-NLS-1$ - - public static final String CLEAR_WORKING_SET_ACTION = PREFIX - + "clear_working_set_action"; //$NON-NLS-1$ - - public static final String GOTO_MARKER_ACTION = PREFIX - + "goto_marker_action"; //$NON-NLS-1$ - - public static final String GOTO_PACKAGE_ACTION = PREFIX - + "goto_package_action"; //$NON-NLS-1$ - - public static final String GOTO_TYPE_ACTION = PREFIX + "goto_type_action"; //$NON-NLS-1$ - - public static final String GOTO_MATCHING_BRACKET_ACTION = PREFIX - + "goto_matching_bracket_action"; //$NON-NLS-1$ - - public static final String GOTO_NEXT_MEMBER_ACTION = PREFIX - + "goto_next_member_action"; //$NON-NLS-1$ - - public static final String GOTO_PREVIOUS_MEMBER_ACTION = PREFIX - + "goto_previous_member_action"; //$NON-NLS-1$ - - public static final String HISTORY_ACTION = PREFIX + "history_action"; //$NON-NLS-1$ - - public static final String HISTORY_LIST_ACTION = PREFIX - + "history_list_action"; //$NON-NLS-1$ - - public static final String LEXICAL_SORTING_OUTLINE_ACTION = PREFIX - + "lexical_sorting_outline_action"; //$NON-NLS-1$ - - public static final String LEXICAL_SORTING_BROWSING_ACTION = PREFIX - + "lexical_sorting_browsing_action"; //$NON-NLS-1$ - - public static final String OPEN_JAVA_PERSPECTIVE_ACTION = PREFIX - + "open_java_perspective_action"; //$NON-NLS-1$ - - public static final String ADD_DELEGATE_METHODS_ACTION = PREFIX - + "add_delegate_methods_action"; //$NON-NLS-1$ - - public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION = PREFIX - + "open_java_browsing_perspective_action"; //$NON-NLS-1$ - - public static final String OPEN_PROJECT_ACTION = PREFIX - + "open_project_action"; //$NON-NLS-1$ - - public static final String OPEN_TYPE_ACTION = PREFIX + "open_type_action"; //$NON-NLS-1$ - - public static final String OPEN_TYPE_IN_HIERARCHY_ACTION = PREFIX - + "open_type_in_hierarchy_action"; //$NON-NLS-1$ - - public static final String ADD_JAVADOC_STUB_ACTION = PREFIX - + "add_javadoc_stub_action"; //$NON-NLS-1$ - - public static final String ADD_TASK_ACTION = PREFIX + "add_task_action"; //$NON-NLS-1$ - - public static final String EXTERNALIZE_STRINGS_ACTION = PREFIX - + "externalize_strings_action"; //$NON-NLS-1$ - - public static final String EXTRACT_METHOD_ACTION = PREFIX - + "extract_method_action"; //$NON-NLS-1$ - - public static final String EXTRACT_TEMP_ACTION = PREFIX - + "extract_temp_action"; //$NON-NLS-1$ - - public static final String PROMOTE_TEMP_TO_FIELD_ACTION = PREFIX - + "promote_temp_to_field_action"; //$NON-NLS-1$ - - public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION = PREFIX - + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ - - public static final String EXTRACT_CONSTANT_ACTION = PREFIX - + "extract_constant_action"; //$NON-NLS-1$ - - public static final String EXTRACT_INTERFACE_ACTION = PREFIX - + "extract_interface_action"; //$NON-NLS-1$ - - public static final String MOVE_INNER_TO_TOP_ACTION = PREFIX - + "move_inner_to_top_level_action"; //$NON-NLS-1$ - - public static final String USE_SUPERTYPE_ACTION = PREFIX - + "use_supertype_action"; //$NON-NLS-1$ - - public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION = PREFIX - + "find_declarations_in_workspace_action"; //$NON-NLS-1$ - - public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION = PREFIX - + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ - - public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION = PREFIX - + "find_declarations_in_working_set_action"; //$NON-NLS-1$ - - public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION = PREFIX - + "find_implementors_in_workspace_action"; //$NON-NLS-1$ - - public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION = PREFIX - + "find_implementors_in_working_set_action"; //$NON-NLS-1$ - - public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION = PREFIX - + "find_references_in_workspace_action"; //$NON-NLS-1$ - - public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION = PREFIX - + "find_references_in_hierarchy_action"; //$NON-NLS-1$ - - public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION = PREFIX - + "find_references_in_working_set_action"; //$NON-NLS-1$ - - public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION = PREFIX - + "find_read_references_in_workspace_action"; //$NON-NLS-1$ - - public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION = PREFIX - + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ - - public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION = PREFIX - + "find_read_references_in_working_set_action"; //$NON-NLS-1$ - - public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION = PREFIX - + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ - - public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION = PREFIX - + "find_write_references_in_working_set_action"; //$NON-NLS-1$ - - public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION = PREFIX - + "find_write_references_in_workspace_action"; //$NON-NLS-1$ - - public static final String FIND_OCCURRENCES_IN_FILE_ACTION = PREFIX - + "find_occurrences_in_file_action"; //$NON-NLS-1$ - - public static final String WORKING_SET_FIND_ACTION = PREFIX - + "working_set_find_action"; //$NON-NLS-1$ - - public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION = PREFIX - + "find_strings_to_externalize_action"; //$NON-NLS-1$ - - public static final String INLINE_ACTION = PREFIX + "inline_action"; //$NON-NLS-1$ - - public static final String MODIFY_PARAMETERS_ACTION = PREFIX - + "modify_parameters_action"; //$NON-NLS-1$ - - public static final String MOVE_ACTION = PREFIX + "move_action"; //$NON-NLS-1$ - - public static final String OPEN_ACTION = PREFIX + "open_action"; //$NON-NLS-1$ - - public static final String OPEN_EXTERNAL_JAVADOC_ACTION = PREFIX - + "open_external_javadoc_action"; //$NON-NLS-1$ - - public static final String OPEN_SUPER_IMPLEMENTATION_ACTION = PREFIX - + "open_super_implementation_action"; //$NON-NLS-1$ - - public static final String PULL_UP_ACTION = PREFIX + "pull_up_action"; //$NON-NLS-1$ - - public static final String PUSH_DOWN_ACTION = PREFIX + "push_down_action"; //$NON-NLS-1$ - - public static final String REFRESH_ACTION = PREFIX + "refresh_action"; //$NON-NLS-1$ - - public static final String RENAME_ACTION = PREFIX + "rename_action"; //$NON-NLS-1$ - - public static final String SELF_ENCAPSULATE_ACTION = PREFIX - + "self_encapsulate_action"; //$NON-NLS-1$ - - public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION = PREFIX - + "show_in_navigator_action"; //$NON-NLS-1$ - - public static final String SURROUND_WITH_TRY_CATCH_ACTION = PREFIX - + "surround_with_try_catch_action"; //$NON-NLS-1$ - - public static final String OPEN_RESOURCE_ACTION = PREFIX - + "open_resource_action"; //$NON-NLS-1$ - - public static final String SELECT_WORKING_SET_ACTION = PREFIX - + "select_working_set_action"; //$NON-NLS-1$ - - public static final String STRUCTURED_SELECTION_HISTORY_ACTION = PREFIX - + "structured_selection_history_action"; //$NON-NLS-1$ - - public static final String STRUCTURED_SELECT_ENCLOSING_ACTION = PREFIX - + "structured_select_enclosing_action"; //$NON-NLS-1$ - - public static final String STRUCTURED_SELECT_NEXT_ACTION = PREFIX - + "structured_select_next_action"; //$NON-NLS-1$ - - public static final String STRUCTURED_SELECT_PREVIOUS_ACTION = PREFIX - + "structured_select_previous_action"; //$NON-NLS-1$ - - public static final String TOGGLE_ORIENTATION_ACTION = PREFIX - + "toggle_orientations_action"; //$NON-NLS-1$ - - public static final String CUT_ACTION = PREFIX + "cut_action"; //$NON-NLS-1$ - - public static final String COPY_ACTION = PREFIX + "copy_action"; //$NON-NLS-1$ - - public static final String PASTE_ACTION = PREFIX + "paste_action"; //$NON-NLS-1$ - - public static final String DELETE_ACTION = PREFIX + "delete_action"; //$NON-NLS-1$ - - public static final String SELECT_ALL_ACTION = PREFIX + "select_all_action"; //$NON-NLS-1$ - - public static final String OPEN_TYPE_HIERARCHY_ACTION = PREFIX - + "open_type_hierarchy_action"; //$NON-NLS-1$ - - public static final String COLLAPSE_ALL_ACTION = PREFIX - + "open_type_hierarchy_action"; //$NON-NLS-1$ - - public static final String GOTO_RESOURCE_ACTION = PREFIX - + "goto_resource_action"; //$NON-NLS-1$ - - public static final String LINK_EDITOR_ACTION = PREFIX - + "link_editor_action"; //$NON-NLS-1$ - - public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION = PREFIX - + "go_into_top_level_type_action"; //$NON-NLS-1$ - - public static final String COMPARE_WITH_HISTORY_ACTION = PREFIX - + "compare_with_history_action"; //$NON-NLS-1$ - - public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION = PREFIX - + "replace_with_previous_from_history_action"; //$NON-NLS-1$ - - public static final String REPLACE_WITH_HISTORY_ACTION = PREFIX - + "replace_with_history_action"; //$NON-NLS-1$ - - public static final String ADD_FROM_HISTORY_ACTION = PREFIX - + "add_from_history_action"; //$NON-NLS-1$ - - public static final String LAYOUT_FLAT_ACTION = PREFIX - + "layout_flat_action"; //$NON-NLS-1$ - - public static final String LAYOUT_HIERARCHICAL_ACTION = PREFIX - + "layout_hierarchical_action"; //$NON-NLS-1$ - - public static final String NEXT_CHANGE_ACTION = PREFIX - + "next_change_action"; //$NON-NLS-1$ - - public static final String PREVIOUS_CHANGE_ACTION = PREFIX - + "previous_change_action"; //$NON-NLS-1$ - - public static final String NEXT_PROBLEM_ACTION = PREFIX - + "next_problem_action"; //$NON-NLS-1$ - - public static final String PREVIOUS_PROBLEM_ACTION = PREFIX - + "previous_problem_action"; //$NON-NLS-1$ - - public static final String JAVA_SELECT_MARKER_RULER_ACTION = PREFIX - + "java_select_marker_ruler_action"; //$NON-NLS-1$ - - public static final String GOTO_NEXT_ERROR_ACTION = PREFIX - + "goto_next_error_action"; //$NON-NLS-1$ - - public static final String GOTO_PREVIOUS_ERROR_ACTION = PREFIX - + "goto_previous_error_action"; //$NON-NLS-1$ - - public static final String SHOW_QUALIFIED_NAMES_ACTION = PREFIX - + "show_qualified_names_action"; //$NON-NLS-1$ - - public static final String SORT_BY_DEFINING_TYPE_ACTION = PREFIX - + "sort_by_defining_type_action"; //$NON-NLS-1$ - - public static final String FORMAT_ACTION = PREFIX + "format_action"; //$NON-NLS-1$ - - public static final String COMMENT_ACTION = PREFIX + "comment_action"; //$NON-NLS-1$ - - public static final String UNCOMMENT_ACTION = PREFIX + "uncomment_action"; //$NON-NLS-1$ - - public static final String QUICK_FIX_ACTION = PREFIX + "quick_fix_action"; //$NON-NLS-1$ - - public static final String CONTENT_ASSIST_ACTION = PREFIX - + "content_assist_action"; //$NON-NLS-1$ - - public static final String PARAMETER_HINTS_ACTION = PREFIX - + "parameter_hints_action"; //$NON-NLS-1$ - - public static final String SHOW_JAVADOC_ACTION = PREFIX - + "show_javadoc_action"; //$NON-NLS-1$ - - public static final String SHOW_OUTLINE_ACTION = PREFIX - + "show_outline_action"; //$NON-NLS-1$ - - public static final String OPEN_STRUCTURE_ACTION = PREFIX - + "open_structure_action"; //$NON-NLS-1$ - - // Dialogs - public static final String MAINTYPE_SELECTION_DIALOG = PREFIX - + "maintype_selection_dialog_context"; //$NON-NLS-1$ - - public static final String OPEN_TYPE_DIALOG = PREFIX - + "open_type_dialog_context"; //$NON-NLS-1$ - - public static final String SOURCE_ATTACHMENT_DIALOG = PREFIX - + "source_attachment_dialog_context"; //$NON-NLS-1$ - - public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG = PREFIX - + "advanced_dialog_context"; //$NON-NLS-1$ - - public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG = PREFIX - + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ - - public static final String NEW_VARIABLE_ENTRY_DIALOG = PREFIX - + "new_variable_dialog_context"; //$NON-NLS-1$ - - public static final String NONNLS_DIALOG = PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ - - public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG = PREFIX - + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ - - public static final String MULTI_TYPE_SELECTION_DIALOG = PREFIX - + "multi_type_selection_dialog_context"; //$NON-NLS-1$ - - public static final String SUPER_INTERFACE_SELECTION_DIALOG = PREFIX - + "super_interface_selection_dialog_context"; //$NON-NLS-1$ - - public static final String OVERRIDE_TREE_SELECTION_DIALOG = PREFIX - + "override_tree_selection_dialog_context"; //$NON-NLS-1$ - - public static final String MOVE_DESTINATION_DIALOG = PREFIX - + "move_destination_dialog_context"; //$NON-NLS-1$ - - public static final String CHOOSE_VARIABLE_DIALOG = PREFIX - + "choose_variable_dialog_context"; //$NON-NLS-1$ - - public static final String EDIT_TEMPLATE_DIALOG = PREFIX - + "edit_template_dialog_context"; //$NON-NLS-1$ - - public static final String HISTORY_LIST_DIALOG = PREFIX - + "history_list_dialog_context"; //$NON-NLS-1$ - - public static final String IMPORT_ORGANIZE_INPUT_DIALOG = PREFIX - + "import_organize_input_dialog_context"; //$NON-NLS-1$ - - public static final String TODO_TASK_INPUT_DIALOG = PREFIX - + "todo_task_input_dialog_context"; //$NON-NLS-1$ - - public static final String JAVADOC_PROPERTY_DIALOG = PREFIX - + "javadoc_property_dialog_context"; //$NON-NLS-1$ - - public static final String NEW_CONTAINER_DIALOG = PREFIX - + "new_container_dialog_context"; //$NON-NLS-1$ - - public static final String EXCLUSION_PATTERN_DIALOG = PREFIX - + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ - - public static final String OUTPUT_LOCATION_DIALOG = PREFIX - + "output_location_dialog_context"; //$NON-NLS-1$ - - public static final String VARIABLE_CREATION_DIALOG = PREFIX - + "variable_creation_dialog_context"; //$NON-NLS-1$ - - public static final String JAVA_SEARCH_PAGE = PREFIX - + "java_search_page_context"; //$NON-NLS-1$ - - public static final String NLS_SEARCH_PAGE = PREFIX - + "nls_search_page_context"; //$NON-NLS-1$ - - public static final String JAVA_EDITOR = PREFIX + "java_editor_context"; //$NON-NLS-1$ - - public static final String GOTO_RESOURCE_DIALOG = PREFIX - + "goto_resource_dialog"; //$NON-NLS-1$ - - public static final String COMPARE_DIALOG = PREFIX - + "compare_dialog_context"; //$NON-NLS-1$ - - public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG = PREFIX - + "add_element_from_history_dialog_context"; //$NON-NLS-1$ - - public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX - + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ - - public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX - + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ - - // view parts - public static final String TYPE_HIERARCHY_VIEW = PREFIX - + "type_hierarchy_view_context"; //$NON-NLS-1$ - - public static final String PACKAGES_VIEW = PREFIX + "package_view_context"; //$NON-NLS-1$ - - public static final String PROJECTS_VIEW = PREFIX + "projects_view_context"; //$NON-NLS-1$ - - public static final String PACKAGES_BROWSING_VIEW = PREFIX - + "packages_browsing_view_context"; //$NON-NLS-1$ - - public static final String TYPES_VIEW = PREFIX + "types_view_context"; //$NON-NLS-1$ - - public static final String MEMBERS_VIEW = PREFIX + "members_view_context"; //$NON-NLS-1$ - - // Preference/Property pages - public static final String APPEARANCE_PREFERENCE_PAGE = PREFIX - + "appearance_preference_page_context"; //$NON-NLS-1$ - - public static final String SORT_ORDER_PREFERENCE_PAGE = PREFIX - + "sort_order_preference_page_context"; //$NON-NLS-1$ - - public static final String BUILD_PATH_PROPERTY_PAGE = PREFIX - + "build_path_property_page_context"; //$NON-NLS-1$ - - public static final String CP_VARIABLES_PREFERENCE_PAGE = PREFIX - + "cp_variables_preference_page_context"; //$NON-NLS-1$ - - public static final String CODEFORMATTER_PREFERENCE_PAGE = PREFIX - + "codeformatter_preference_page_context"; //$NON-NLS-1$ - - public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE = PREFIX - + "source_attachment_property_page_context"; //$NON-NLS-1$ - - public static final String COMPILER_PROPERTY_PAGE = PREFIX - + "compiler_property_page_context"; //$NON-NLS-1$ - - public static final String TODOTASK_PROPERTY_PAGE = PREFIX - + "tasktags_property_page_context"; //$NON-NLS-1$ - - public static final String CODE_MANIPULATION_PREFERENCE_PAGE = PREFIX - + "code_manipulation_preference_context"; //$NON-NLS-1$ - - public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE = PREFIX - + "organizeimports_preference_page_context"; //$NON-NLS-1$ - - public static final String JAVA_BASE_PREFERENCE_PAGE = PREFIX - + "java_base_preference_page_context"; //$NON-NLS-1$ - - public static final String REFACTORING_PREFERENCE_PAGE = PREFIX - + "refactoring_preference_page_context"; //$NON-NLS-1$ - - public static final String JAVA_EDITOR_PREFERENCE_PAGE = PREFIX - + "java_editor_preference_page_context"; //$NON-NLS-1$ - - public static final String COMPILER_PREFERENCE_PAGE = PREFIX - + "compiler_preference_page_context"; //$NON-NLS-1$ - - public static final String TODOTASK_PREFERENCE_PAGE = PREFIX - + "tasktags_preference_page_context"; //$NON-NLS-1$ - - public static final String TEMPLATE_PREFERENCE_PAGE = PREFIX - + "template_preference_page_context"; //$NON-NLS-1$ - - public static final String JAVADOC_PREFERENCE_PAGE = PREFIX - + "javadoc_preference_page_context"; //$NON-NLS-1$ - - public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE = PREFIX - + "new_java_project_preference_page_context"; //$NON-NLS-1$ - - public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE = PREFIX - + "new_java_project_preference_page_context"; //$NON-NLS-1$ - - public static final String JAVA_ELEMENT_INFO_PAGE = PREFIX - + "java_element_info_page_context"; //$NON-NLS-1$ - - // Wizard pages - public static final String NEW_JAVAPROJECT_WIZARD_PAGE = PREFIX - + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ - - public static final String NEW_SNIPPET_WIZARD_PAGE = PREFIX - + "new_snippet_wizard_page_context"; //$NON-NLS-1$ - - public static final String NEW_PACKAGE_WIZARD_PAGE = PREFIX - + "new_package_wizard_page_context"; //$NON-NLS-1$ - - public static final String NEW_CLASS_WIZARD_PAGE = PREFIX - + "new_class_wizard_page_context"; //$NON-NLS-1$ - - public static final String NEW_INTERFACE_WIZARD_PAGE = PREFIX - + "new_interface_wizard_page_context"; //$NON-NLS-1$ - - public static final String NEW_PACKAGEROOT_WIZARD_PAGE = PREFIX - + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ - - public static final String JARPACKAGER_WIZARD_PAGE = PREFIX - + "jar_packager_wizard_page_context"; //$NON-NLS-1$ - - public static final String JARMANIFEST_WIZARD_PAGE = PREFIX - + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ - - public static final String JAROPTIONS_WIZARD_PAGE = PREFIX - + "jar_options_wizard_page_context"; //$NON-NLS-1$ - - public static final String JAVA_WORKING_SET_PAGE = PREFIX - + "java_working_set_page_context"; //$NON-NLS-1$ - - public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE = PREFIX - + "classpath_container_default_page_context"; //$NON-NLS-1$ - - public static final String JAVADOC_STANDARD_PAGE = PREFIX - + "javadoc_standard_page_context"; //$NON-NLS-1$ - - public static final String JAVADOC_SPECIFICS_PAGE = PREFIX - + "javadoc_specifics_page_context"; //$NON-NLS-1$ - - public static final String JAVADOC_TREE_PAGE = PREFIX - + "javadoc_tree_page_context"; //$NON-NLS-1$ - - // same help for all refactoring preview pages - public static final String REFACTORING_PREVIEW_WIZARD_PAGE = PREFIX - + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_CU_ERROR_WIZARD_PAGE = PREFIX - + "move_cu_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_PARAMS_WIZARD_PAGE = PREFIX - + "rename_params_wizard_page"; //$NON-NLS-1$ - - public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE = PREFIX - + "rename_params_error_wizard_page"; //$NON-NLS-1$ - - public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE = PREFIX - + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ - - public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE = PREFIX - + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ - - public static final String EXTERNALIZE_ERROR_WIZARD_PAGE = PREFIX - + "externalize_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_INTERFACE_WIZARD_PAGE = PREFIX - + "extract_interface_temp_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE = PREFIX - + "extract_interface_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_METHOD_WIZARD_PAGE = PREFIX - + "extract_method_wizard_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE = PREFIX - + "extract_method_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_TEMP_WIZARD_PAGE = PREFIX - + "extract_temp_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE = PREFIX - + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_CONSTANT_WIZARD_PAGE = PREFIX - + "extract_constant_page_context"; //$NON-NLS-1$ - - public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE = PREFIX - + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE = PREFIX - + "promote_temp_to_field_page_context"; //$NON-NLS-1$ - - public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE = PREFIX - + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE = PREFIX - + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ - - public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE = PREFIX - + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String MODIFY_PARAMETERS_WIZARD_PAGE = PREFIX - + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ - - public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE = PREFIX - + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_MEMBERS_WIZARD_PAGE = PREFIX - + "move_members_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE = PREFIX - + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE = PREFIX - + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ - - public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE = PREFIX - + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String PULL_UP_WIZARD_PAGE = PREFIX - + "pull_up_wizard_page_context"; //$NON-NLS-1$ - - public static final String PULL_UP_ERROR_WIZARD_PAGE = PREFIX - + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String PUSH_DOWN_WIZARD_PAGE = PREFIX - + "push_down_wizard_page_context"; //$NON-NLS-1$ - - public static final String PUSH_DOWN_ERROR_WIZARD_PAGE = PREFIX - + "push_down_error_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_PACKAGE_WIZARD_PAGE = PREFIX - + "rename_package_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE = PREFIX - + "rename_package_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_TEMP_WIZARD_PAGE = PREFIX - + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_TEMP_ERROR_WIZARD_PAGE = PREFIX - + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_CU_WIZARD_PAGE = PREFIX - + "rename_cu_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_CU_ERROR_WIZARD_PAGE = PREFIX - + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_METHOD_WIZARD_PAGE = PREFIX - + "rename_method_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_METHOD_ERROR_WIZARD_PAGE = PREFIX - + "rename_method_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_TYPE_WIZARD_PAGE = PREFIX - + "rename_type_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_TYPE_ERROR_WIZARD_PAGE = PREFIX - + "rename_type_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_FIELD_WIZARD_PAGE = PREFIX - + "rename_field_wizard_page_context"; //$NON-NLS-1$ - - public static final String RENAME_FIELD_ERROR_WIZARD_PAGE = PREFIX - + "rename_field_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String SEF_WIZARD_PAGE = PREFIX - + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ - - public static final String SEF_ERROR_WIZARD_PAGE = PREFIX - + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String USE_SUPERTYPE_WIZARD_PAGE = PREFIX - + "use_supertype_wizard_page_context"; //$NON-NLS-1$ - - public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE = PREFIX - + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String INLINE_METHOD_WIZARD_PAGE = PREFIX - + "inline_method_wizard_page_context"; //$NON-NLS-1$ - - public static final String INLINE_METHOD_ERROR_WIZARD_PAGE = PREFIX - + "inline_method_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String INLINE_CONSTANT_WIZARD_PAGE = PREFIX - + "inline_constant_wizard_page_context"; //$NON-NLS-1$ - - public static final String INLINE_CONSTANT_ERROR_WIZARD_PAGE = PREFIX - + "inline_constant_error_wizard_page_context"; //$NON-NLS-1$ - - public static final String INLINE_TEMP_ERROR_WIZARD_PAGE = PREFIX - + "inline_temp_error_wizard_page_context"; //$NON-NLS-1$ - - // reused ui-blocks - public static final String BUILD_PATH_BLOCK = PREFIX - + "build_paths_context"; //$NON-NLS-1$ - - public static final String SOURCE_ATTACHMENT_BLOCK = PREFIX - + "source_attachment_context"; //$NON-NLS-1$ - - // Custom Filters - public static final String CUSTOM_FILTERS_DIALOG = PREFIX - + "open_custom_filters_dialog_context"; //$NON-NLS-1$ -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java deleted file mode 100644 index 1d5e62b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java +++ /dev/null @@ -1,924 +0,0 @@ -package net.sourceforge.phpdt.internal.ui; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Iterator; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.ImageRegistry; -import org.eclipse.swt.graphics.Image; - -public class PHPUiImages { - - protected static final String NAME_PREFIX = "net.sourceforge.phpdt.internal.ui."; - - protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); - - protected static URL fgIconBaseURL = null; - - // static { - // String pathSuffix = "icons/"; - // try { - // fgIconBaseURL = - // new URL( - // PHPeclipsePlugin - // .getDefault() - // .getDescriptor() - // .getInstallURL(), - // pathSuffix); - // } catch (MalformedURLException e) { - // PHPeclipsePlugin.log(e); - // } - // } - - // Determine display depth. If depth > 4 then we use high color images. - // Otherwise low color - // images are used - static { - fgIconBaseURL = WebUI.getDefault().getBundle().getEntry( - "/icons/"); //$NON-NLS-1$ - } - - private static ImageRegistry fgImageRegistry = null; - - private static HashMap fgAvoidSWTErrorMap = null; - - protected static final String OBJ_PREFIX = "obj16"; - - protected static final String OVR_PREFIX = "ovr16"; - - protected static final String CTOOL_PREFIX = "ctool16"; - - public static final String IMG_CLASS = NAME_PREFIX - + "class_default_obj.gif"; - - public static final String IMG_DEFINE = NAME_PREFIX + "define_obj.gif"; - - public static final String IMG_BUILTIN = NAME_PREFIX + "builtin_obj.gif"; - - public static final String IMG_FUN = NAME_PREFIX + "fun_obj.gif"; - - public static final String IMG_INC = NAME_PREFIX + "impc_obj.gif"; - - public static final String IMG_VAR = NAME_PREFIX + "var_obj.gif"; - - public static final String IMG_TABLE = NAME_PREFIX + "table_obj.gif"; - - public static final String IMG_COLUMN = NAME_PREFIX + "column_obj.gif"; - - public static final String IMG_OBJS_WARNING = NAME_PREFIX - + "warning_obj.gif"; - - public static final String IMG_OBJS_INFO = NAME_PREFIX + "info_obj.gif"; - - public static final String IMG_CTOOLS_PHP_PAGE = NAME_PREFIX - + "php_page.gif"; - - public static final String IMG_CTOOLS_PHP = NAME_PREFIX + "php.gif"; - - public static final String IMG_CLEAR = NAME_PREFIX + "clear.gif"; - - public static final ImageDescriptor DESC_CLASS = createManaged(OBJ_PREFIX, - IMG_CLASS); - - public static final ImageDescriptor DESC_DEFINE = createManaged(OBJ_PREFIX, - IMG_DEFINE); - - public static final ImageDescriptor DESC_BUILTIN = createManaged( - OBJ_PREFIX, IMG_BUILTIN); - - public static final ImageDescriptor DESC_FUN = createManaged(OBJ_PREFIX, - IMG_FUN); - - public static final ImageDescriptor DESC_INC = createManaged(OBJ_PREFIX, - IMG_INC); - - public static final ImageDescriptor DESC_VAR = createManaged(OBJ_PREFIX, - IMG_VAR); - - public static final ImageDescriptor DESC_TABLE = createManaged(OBJ_PREFIX, - IMG_TABLE); - - public static final ImageDescriptor DESC_COLUMN = createManaged(OBJ_PREFIX, - IMG_COLUMN); - - public static final ImageDescriptor DESC_OBJS_WARNING = createManaged( - OBJ_PREFIX, IMG_OBJS_WARNING); - - public static final ImageDescriptor DESC_OBJS_INFO = createManaged( - OBJ_PREFIX, IMG_OBJS_INFO); - - public static final ImageDescriptor DESC_CTOOL_PHP_PAGE = createManaged( - CTOOL_PREFIX, IMG_CTOOLS_PHP_PAGE); - - public static final ImageDescriptor DESC_CTOOL_PHP = createManaged( - CTOOL_PREFIX, IMG_CTOOLS_PHP); - - public static final ImageDescriptor DESC_CLEAR = createManaged(OBJ_PREFIX, - IMG_CLEAR); - - /* - * Set of predefined Image Descriptors. - */ - private static final String T_OBJ = "obj16"; //$NON-NLS-1$ - - private static final String T_OVR = "ovr16"; //$NON-NLS-1$ - - private static final String T_WIZBAN = "wizban"; //$NON-NLS-1$ - - private static final String T_CLCL = "clcl16"; //$NON-NLS-1$ - - private static final String T_DLCL = "dlcl16"; //$NON-NLS-1$ - - private static final String T_ELCL = "elcl16"; //$NON-NLS-1$ - - private static final String T_CTOOL = "ctool16"; //$NON-NLS-1$ - - private static final String T_CVIEW = "cview16"; //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWCLASS = create(T_WIZBAN, - "newclass_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_ELCL_FILTER = create(T_ELCL, - "filter_ps.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_DLCL_FILTER = create(T_DLCL, - "filter_ps.gif"); //$NON-NLS-1$ - - /* - * Available cached Images in the Java plugin image registry. - */ - public static final String IMG_MISC_PUBLIC = NAME_PREFIX - + "methpub_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_MISC_PROTECTED = NAME_PREFIX - + "methpro_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_MISC_PRIVATE = NAME_PREFIX - + "methpri_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_MISC_DEFAULT = NAME_PREFIX - + "methdef_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_FIELD_PUBLIC = NAME_PREFIX - + "field_public_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_FIELD_PROTECTED = NAME_PREFIX - + "field_protected_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_FIELD_PRIVATE = NAME_PREFIX - + "field_private_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_FIELD_DEFAULT = NAME_PREFIX - + "field_default_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_GHOST = NAME_PREFIX + "ghost.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_TSK = NAME_PREFIX - + "search_tsk.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_PACKDECL = NAME_PREFIX - + "packd_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_IMPDECL = NAME_PREFIX + "imp_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_IMPCONT = NAME_PREFIX + "impc_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JSEARCH = NAME_PREFIX - + "jsearch_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_DECL = NAME_PREFIX - + "search_decl_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_REF = NAME_PREFIX - + "search_ref_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CLASS = NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CLASSALT = NAME_PREFIX - + "classfo_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CLASS_DEFAULT = NAME_PREFIX - + "class_default_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_INTERFACE = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_INTERFACEALT = NAME_PREFIX - + "intf_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_INTERFACE_DEFAULT = NAME_PREFIX - + "int_default_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CUNIT = NAME_PREFIX + "phpedit.png"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CUNIT_RESOURCE = NAME_PREFIX - + "jcu_resource_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CFILE = NAME_PREFIX + "classf_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CFILECLASS = NAME_PREFIX - + "class_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_CFILEINT = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_LOGICAL_PACKAGE = NAME_PREFIX - + "logical_package_obj.gif";//$NON-NLS-1$ - - public static final String IMG_OJS_EMPTY_LOGICAL_PACKAGE = NAME_PREFIX - + "empty_logical_package_obj.gif";//$NON-NLS-1$ - - public static final String IMG_OBJS_PACKAGE = NAME_PREFIX - + "package_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EMPTY_PACK_RESOURCE = NAME_PREFIX - + "empty_pack_fldr_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EMPTY_PACKAGE = NAME_PREFIX - + "empty_pack_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_PACKFRAG_ROOT = NAME_PREFIX - + "packagefolder_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_MISSING_PACKFRAG_ROOT = NAME_PREFIX - + "packagefolder_nonexist_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_MISSING_JAR = NAME_PREFIX - + "jar_nonexist_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JAR = NAME_PREFIX + "jar_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EXTJAR = NAME_PREFIX + "jar_l_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JAR_WSRC = NAME_PREFIX - + "jar_src_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EXTJAR_WSRC = NAME_PREFIX - + "jar_lsrc_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_ENV_VAR = NAME_PREFIX - + "envvar_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_MISSING_ENV_VAR = NAME_PREFIX - + "envvar_nonexist_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JAVA_MODEL = NAME_PREFIX - + "java_model_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_UNKNOWN = NAME_PREFIX - + "unknown_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_LIBRARY = NAME_PREFIX - + "library_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_JAVADOCTAG = NAME_PREFIX - + "jdoc_tag_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_HTMLTAG = NAME_PREFIX - + "html_tag_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_TEMPLATE = NAME_PREFIX - + "template_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_EXCEPTION = NAME_PREFIX - + "jexception_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_ERROR = NAME_PREFIX - + "jrtexception_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_BREAKPOINT_INSTALLED = NAME_PREFIX - + "brkpi_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_FIXABLE_PROBLEM = NAME_PREFIX - + "quickfix_warning_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_FIXABLE_ERROR = NAME_PREFIX - + "quickfix_error_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SNIPPET_EVALUATING = NAME_PREFIX - + "jsbook_run_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_REFACTORING_FATAL = NAME_PREFIX - + "fatalerror_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_REFACTORING_ERROR = NAME_PREFIX - + "error_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_REFACTORING_WARNING = NAME_PREFIX - + "warning_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_REFACTORING_INFO = NAME_PREFIX - + "info_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_NLS_TRANSLATE = NAME_PREFIX - + "translate.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_NLS_NEVER_TRANSLATE = NAME_PREFIX - + "never_translate.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_NLS_SKIP = NAME_PREFIX + "skip.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_READACCESS = NAME_PREFIX - + "occ_read.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_WRITEACCESS = NAME_PREFIX - + "occ_write.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJS_SEARCH_OCCURRENCE = NAME_PREFIX - + "occ_match.gif"; //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VIEW_ERRORWARNING_TAB = create( - T_CVIEW, "errorwarning_tab.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VIEW_CLASSFILEGENERATION_TAB = create( - T_CVIEW, "classfilegeneration_tab.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_VIEW_JDKCOMPLIANCE_TAB = create( - T_CVIEW, "jdkcompliance_tab.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_CLCL_FILTER = create(T_CLCL, - "filter_ps.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_CLCL_CODE_ASSIST = create(T_CLCL, - "metharg_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_DLCL_CODE_ASSIST = create(T_DLCL, - "metharg_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_MISC_PUBLIC = createManaged(T_OBJ, - IMG_MISC_PUBLIC); - - public static final ImageDescriptor DESC_MISC_PROTECTED = createManaged( - T_OBJ, IMG_MISC_PROTECTED); - - public static final ImageDescriptor DESC_MISC_PRIVATE = createManaged( - T_OBJ, IMG_MISC_PRIVATE); - - public static final ImageDescriptor DESC_MISC_DEFAULT = createManaged( - T_OBJ, IMG_MISC_DEFAULT); - - public static final ImageDescriptor DESC_FIELD_PUBLIC = createManaged( - T_OBJ, IMG_FIELD_PUBLIC); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_FIELD_PROTECTED = createManaged( - T_OBJ, IMG_FIELD_PROTECTED); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_FIELD_PRIVATE = createManaged( - T_OBJ, IMG_FIELD_PRIVATE); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_FIELD_DEFAULT = createManaged( - T_OBJ, IMG_FIELD_DEFAULT); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_MENU_SHIFT_RIGHT = create(T_CTOOL, - "shift_r_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_MENU_SHIFT_LEFT = create(T_CTOOL, - "shift_l_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_GHOST = createManaged(T_OBJ, - IMG_OBJS_GHOST); - - public static final ImageDescriptor DESC_OBJS_PACKDECL = createManaged( - T_OBJ, IMG_OBJS_PACKDECL); - - public static final ImageDescriptor DESC_OBJS_IMPDECL = createManaged( - T_OBJ, IMG_OBJS_IMPDECL); - - public static final ImageDescriptor DESC_OBJS_IMPCONT = createManaged( - T_OBJ, IMG_OBJS_IMPCONT); - - public static final ImageDescriptor DESC_OBJS_JSEARCH = createManaged( - T_OBJ, IMG_OBJS_JSEARCH); - - public static final ImageDescriptor DESC_OBJS_SEARCH_DECL = createManaged( - T_OBJ, IMG_OBJS_SEARCH_DECL); - - public static final ImageDescriptor DESC_OBJS_SEARCH_REF = createManaged( - T_OBJ, IMG_OBJS_SEARCH_REF); - - public static final ImageDescriptor DESC_OBJS_CUNIT = createManaged(T_OBJ, - IMG_OBJS_CUNIT); - - public static final ImageDescriptor DESC_OBJS_CUNIT_RESOURCE = createManaged( - T_OBJ, IMG_OBJS_CUNIT_RESOURCE); - - public static final ImageDescriptor DESC_OBJS_CFILE = createManaged(T_OBJ, - IMG_OBJS_CFILE); - - public static final ImageDescriptor DESC_OBJS_CFILECLASS = createManaged( - T_OBJ, IMG_OBJS_CFILECLASS); - - public static final ImageDescriptor DESC_OBJS_CFILEINT = createManaged( - T_OBJ, IMG_OBJS_CFILEINT); - - public static final ImageDescriptor DESC_OBJS_PACKAGE = createManaged( - T_OBJ, IMG_OBJS_PACKAGE); - - public static final ImageDescriptor DESC_OBJS_EMPTY_LOGICAL_PACKAGE = createManaged( - T_OBJ, IMG_OJS_EMPTY_LOGICAL_PACKAGE); - - public static final ImageDescriptor DESC_OBJS_LOGICAL_PACKAGE = createManaged( - T_OBJ, IMG_OBJS_LOGICAL_PACKAGE); - - public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE_RESOURCES = createManaged( - T_OBJ, IMG_OBJS_EMPTY_PACK_RESOURCE); - - public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE = createManaged( - T_OBJ, IMG_OBJS_EMPTY_PACKAGE); - - public static final ImageDescriptor DESC_OBJS_PACKFRAG_ROOT = createManaged( - T_OBJ, IMG_OBJS_PACKFRAG_ROOT); - - public static final ImageDescriptor DESC_OBJS_MISSING_PACKFRAG_ROOT = createManaged( - T_OBJ, IMG_OBJS_MISSING_PACKFRAG_ROOT); - - public static final ImageDescriptor DESC_OBJS_JAVA_MODEL = createManaged( - T_OBJ, IMG_OBJS_JAVA_MODEL); - - public static final ImageDescriptor DESC_OBJS_CLASS = createManaged(T_OBJ, - IMG_OBJS_CLASS); - - public static final ImageDescriptor DESC_OBJS_CLASS_DEFAULT = createManaged( - T_OBJ, IMG_OBJS_CLASS_DEFAULT); - - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PUBLIC = create( - T_OBJ, "innerclass_public_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_DEFAULT = create( - T_OBJ, "innerclass_default_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PROTECTED = create( - T_OBJ, "innerclass_protected_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PRIVATE = create( - T_OBJ, "innerclass_private_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_CLASSALT = createManaged( - T_OBJ, IMG_OBJS_CLASSALT); - - public static final ImageDescriptor DESC_OBJS_INTERFACE = createManaged( - T_OBJ, IMG_OBJS_INTERFACE); - - public static final ImageDescriptor DESC_OBJS_INTERFACE_DEFAULT = createManaged( - T_OBJ, IMG_OBJS_INTERFACE_DEFAULT); - - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PUBLIC = create( - T_OBJ, "innerinterface_public_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_DEFAULT = create( - T_OBJ, "innerinterface_default_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PROTECTED = create( - T_OBJ, "innerinterface_protected_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PRIVATE = create( - T_OBJ, "innerinterface_private_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_INTERFACEALT = createManaged( - T_OBJ, IMG_OBJS_INTERFACEALT); - - public static final ImageDescriptor DESC_OBJS_JAR = createManaged(T_OBJ, - IMG_OBJS_JAR); - - public static final ImageDescriptor DESC_OBJS_MISSING_JAR = createManaged( - T_OBJ, IMG_OBJS_MISSING_JAR); - - public static final ImageDescriptor DESC_OBJS_EXTJAR = createManaged(T_OBJ, - IMG_OBJS_EXTJAR); - - public static final ImageDescriptor DESC_OBJS_JAR_WSRC = createManaged( - T_OBJ, IMG_OBJS_JAR_WSRC); - - public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC = createManaged( - T_OBJ, IMG_OBJS_EXTJAR_WSRC); - - public static final ImageDescriptor DESC_OBJS_ENV_VAR = createManaged( - T_OBJ, IMG_OBJS_ENV_VAR); - - public static final ImageDescriptor DESC_OBJS_MISSING_ENV_VAR = createManaged( - T_OBJ, IMG_OBJS_MISSING_ENV_VAR); - - public static final ImageDescriptor DESC_OBJS_LIBRARY = createManaged( - T_OBJ, IMG_OBJS_LIBRARY); - - public static final ImageDescriptor DESC_OBJS_JAVADOCTAG = createManaged( - T_OBJ, IMG_OBJS_JAVADOCTAG); - - public static final ImageDescriptor DESC_OBJS_HTMLTAG = createManaged( - T_OBJ, IMG_OBJS_HTMLTAG); - - public static final ImageDescriptor DESC_OBJS_TEMPLATE = createManaged( - T_OBJ, IMG_OBJS_TEMPLATE); - - public static final ImageDescriptor DESC_OBJS_EXCEPTION = createManaged( - T_OBJ, IMG_OBJS_EXCEPTION); - - public static final ImageDescriptor DESC_OBJS_BREAKPOINT_INSTALLED = createManaged( - T_OBJ, IMG_OBJS_BREAKPOINT_INSTALLED); - - public static final ImageDescriptor DESC_OBJS_ERROR = createManaged(T_OBJ, - IMG_OBJS_ERROR); - - public static final ImageDescriptor DESC_OBJS_FIXABLE_PROBLEM = createManaged( - T_OBJ, IMG_OBJS_FIXABLE_PROBLEM); - - public static final ImageDescriptor DESC_OBJS_FIXABLE_ERROR = createManaged( - T_OBJ, IMG_OBJS_FIXABLE_ERROR); - - public static final ImageDescriptor DESC_OBJS_SNIPPET_EVALUATING = createManaged( - T_OBJ, IMG_OBJS_SNIPPET_EVALUATING); - - public static final ImageDescriptor DESC_OBJS_DEFAULT_CHANGE = create( - T_OBJ, "change.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_COMPOSITE_CHANGE = create( - T_OBJ, "composite_change.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_CU_CHANGE = create(T_OBJ, - "cu_change.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_FILE_CHANGE = create(T_OBJ, - "file_change.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_TEXT_EDIT = create(T_OBJ, - "text_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB = create( - T_OBJ, "exclusion_filter_attrib.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_OUTPUT_FOLDER_ATTRIB = create( - T_OBJ, "output_folder_attrib.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_SOURCE_ATTACH_ATTRIB = create( - T_OBJ, "source_attach_attrib.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_JAVADOC_LOCATION_ATTRIB = create( - T_OBJ, "javadoc_location_attrib.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OBJS_REFACTORING_FATAL = createManaged( - T_OBJ, IMG_OBJS_REFACTORING_FATAL); - - public static final ImageDescriptor DESC_OBJS_REFACTORING_ERROR = createManaged( - T_OBJ, IMG_OBJS_REFACTORING_ERROR); - - public static final ImageDescriptor DESC_OBJS_REFACTORING_WARNING = createManaged( - T_OBJ, IMG_OBJS_REFACTORING_WARNING); - - public static final ImageDescriptor DESC_OBJS_REFACTORING_INFO = createManaged( - T_OBJ, IMG_OBJS_REFACTORING_INFO); - - public static final ImageDescriptor DESC_OBJS_NLS_TRANSLATE = createManaged( - T_OBJ, IMG_OBJS_NLS_TRANSLATE); - - public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE = createManaged( - T_OBJ, IMG_OBJS_NLS_NEVER_TRANSLATE); - - public static final ImageDescriptor DESC_OBJS_NLS_SKIP = createManaged( - T_OBJ, IMG_OBJS_NLS_SKIP); - - public static final ImageDescriptor DESC_OBJS_UNKNOWN = createManaged( - T_OBJ, IMG_OBJS_UNKNOWN); - - public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS = createManaged( - T_OBJ, IMG_OBJS_SEARCH_READACCESS); - - public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS = createManaged( - T_OBJ, IMG_OBJS_SEARCH_WRITEACCESS); - - public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE = createManaged( - T_OBJ, IMG_OBJS_SEARCH_OCCURRENCE); - - public static final ImageDescriptor DESC_OBJS_LOCAL_VARIABLE = create( - T_OBJ, "localvariable_obj.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_STATIC = create(T_OVR, - "static_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_FINAL = create(T_OVR, - "final_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_ABSTRACT = create(T_OVR, - "abstract_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_SYNCH = create(T_OVR, - "synch_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_RUN = create(T_OVR, - "run_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_WARNING = create(T_OVR, - "warning_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_ERROR = create(T_OVR, - "error_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_OVERRIDES = create(T_OVR, - "over_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_IMPLEMENTS = create(T_OVR, - "implm_co.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_CONSTRUCTOR = create(T_OVR, - "constr_ovr.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_OVR_FOCUS = create(T_OVR, - "focus_ovr.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWFIELD = create(T_WIZBAN, - "newfield_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWINT = create(T_WIZBAN, - "newint_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ = create(T_WIZBAN, - "newjprj_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR = create( - T_WIZBAN, "newsrcfldr_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWMETH = create(T_WIZBAN, - "newmeth_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWPACK = create(T_WIZBAN, - "newpack_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_NEWSCRAPPAGE = create( - T_WIZBAN, "newsbook_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_JAVA_LAUNCH = create( - T_WIZBAN, "java_app_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_JAVA_ATTACH = create( - T_WIZBAN, "java_attach_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR = create(T_WIZBAN, - "refactor_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIELD = create( - T_WIZBAN, "fieldrefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_METHOD = create( - T_WIZBAN, "methrefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_TYPE = create( - T_WIZBAN, "typerefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PACKAGE = create( - T_WIZBAN, "packrefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CODE = create( - T_WIZBAN, "coderefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CU = create( - T_WIZBAN, "compunitrefact_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PULL_UP = create( - T_WIZBAN, "pullup_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_JAR_PACKAGER = create( - T_WIZBAN, "jar_pack_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_JAVA_WORKINGSET = create( - T_WIZBAN, "java_workingset_wiz.gif");//$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_EXPORT_JAVADOC = create( - T_WIZBAN, "export_javadoc_wiz.gif");//$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_EXTERNALIZE_STRINGS = create( - T_WIZBAN, "extstr_wiz.gif");//$NON-NLS-1$ - - public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY = create( - T_WIZBAN, "addlibrary_wiz.gif");//$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_DISPLAYSNIPPET = create( - T_CTOOL, "disp_sbook.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_RUNSNIPPET = create(T_CTOOL, - "run_sbook.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_INSPSNIPPET = create(T_CTOOL, - "insp_sbook.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_PACKSNIPPET = create(T_CTOOL, - "pack_sbook.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_TERMSNIPPET = create(T_CTOOL, - "term_sbook.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_SHOW_EMPTY_PKG = create( - T_CTOOL, "show_empty_pkg.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_SHOW_SEGMENTS = create( - T_CTOOL, "segment_edit.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_GOTO_NEXT_ERROR = create( - T_CTOOL, "next_error_nav.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_GOTO_PREV_ERROR = create( - T_CTOOL, "prev_error_nav.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_OPENTYPE = create(T_CTOOL, - "opentype.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWPROJECT = create(T_CTOOL, - "newjprj_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWPACKAGE = create(T_CTOOL, - "newpack_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWCLASS = create(T_CTOOL, - "newclass_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWINTERFACE = create( - T_CTOOL, "newint_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWSNIPPET = create(T_CTOOL, - "newsbook_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_NEWPACKROOT = create(T_CTOOL, - "newpackfolder_wiz.gif"); //$NON-NLS-1$ - - public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER = create( - T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$ - - // Keys for correction proposal. We have to put the image into the registry - // since "code assist" doesn't - // have a life cycle. So no change to dispose icons. - - public static final String IMG_CORRECTION_CHANGE = NAME_PREFIX - + "correction_change.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_MOVE = NAME_PREFIX - + "correction_move.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_RENAME = NAME_PREFIX - + "correction_rename.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_DELETE_IMPORT = NAME_PREFIX - + "correction_delete_import.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_LOCAL = NAME_PREFIX - + "localvariable_obj.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_REMOVE = NAME_PREFIX - + "remove_correction.gif"; //$NON-NLS-1$ - - public static final String IMG_CORRECTION_ADD = NAME_PREFIX - + "add_correction.gif"; //$NON-NLS-1$ - - static { - createManaged(T_OBJ, IMG_CORRECTION_CHANGE); - createManaged(T_OBJ, IMG_CORRECTION_MOVE); - createManaged(T_OBJ, IMG_CORRECTION_RENAME); - createManaged(T_OBJ, IMG_CORRECTION_DELETE_IMPORT); - createManaged(T_OBJ, IMG_CORRECTION_LOCAL); - createManaged(T_OBJ, IMG_CORRECTION_REMOVE); - createManaged(T_OBJ, IMG_CORRECTION_ADD); - } - - /** - * Returns the image managed under the given key in this registry. - * - * @param key - * the image's key - * @return the image managed under the given key - */ - public static Image get(String key) { - return getImageRegistry().get(key); - } - - /** - * Returns the image descriptor for the given key in this registry. Might be - * called in a non-UI thread. - * - * @param key - * the image's key - * @return the image descriptor for the given key - */ - public static ImageDescriptor getDescriptor(String key) { - if (fgImageRegistry == null) { - return (ImageDescriptor) fgAvoidSWTErrorMap.get(key); - } - return getImageRegistry().getDescriptor(key); - } - - /** - * Sets the three image descriptors for enabled, disabled, and hovered to an - * action. The actions are retrieved from the *tool16 folders. - */ - public static void setToolImageDescriptors(IAction action, String iconName) { - setImageDescriptors(action, "tool16", iconName); - } - - /** - * Sets the three image descriptors for enabled, disabled, and hovered to an - * action. The actions are retrieved from the *lcl16 folders. - */ - public static void setLocalImageDescriptors(IAction action, String iconName) { - setImageDescriptors(action, "lcl16", iconName); - } - - /* - * Helper method to access the image registry from the JavaPlugin class. - */ - /* package */static ImageRegistry getImageRegistry() { - if (fgImageRegistry == null) { - fgImageRegistry = new ImageRegistry(); - for (Iterator iter = fgAvoidSWTErrorMap.keySet().iterator(); iter - .hasNext();) { - String key = (String) iter.next(); - fgImageRegistry.put(key, (ImageDescriptor) fgAvoidSWTErrorMap - .get(key)); - } - fgAvoidSWTErrorMap = null; - } - return fgImageRegistry; - } - - // ---- Helper methods to access icons on the file system - // -------------------------------------- - - protected static void setImageDescriptors(IAction action, String type, - String relPath) { - - try { - ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( - "d" + type, relPath)); - if (id != null) - action.setDisabledImageDescriptor(id); - } catch (MalformedURLException e) { - } - - try { - ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( - "c" + type, relPath)); - if (id != null) - action.setHoverImageDescriptor(id); - } catch (MalformedURLException e) { - } - - action.setImageDescriptor(create("e" + type, relPath)); - } - - private static ImageDescriptor createManaged(String prefix, String name) { - try { - ImageDescriptor result = ImageDescriptor - .createFromURL(makeIconFileURL(prefix, name - .substring(NAME_PREFIX_LENGTH))); - if (fgAvoidSWTErrorMap == null) { - fgAvoidSWTErrorMap = new HashMap(); - } - fgAvoidSWTErrorMap.put(name, result); - if (fgImageRegistry != null) { - WebUI - .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ - } - return result; - } catch (MalformedURLException e) { - return ImageDescriptor.getMissingImageDescriptor(); - } - } - -// private static ImageDescriptor createManaged(String prefix, String name, -// String key) { -// try { -// ImageDescriptor result = ImageDescriptor -// .createFromURL(makeIconFileURL(prefix, name -// .substring(NAME_PREFIX_LENGTH))); -// if (fgAvoidSWTErrorMap == null) { -// fgAvoidSWTErrorMap = new HashMap(); -// } -// fgAvoidSWTErrorMap.put(key, result); -// if (fgImageRegistry != null) { -// WebUI -// .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ -// } -// return result; -// } catch (MalformedURLException e) { -// return ImageDescriptor.getMissingImageDescriptor(); -// } -// } - - protected static ImageDescriptor create(String prefix, String name) { - try { - return ImageDescriptor.createFromURL(makeIconFileURL(prefix, name)); - } catch (MalformedURLException e) { - return ImageDescriptor.getMissingImageDescriptor(); - } - } - - protected static URL makeIconFileURL(String prefix, String name) - throws MalformedURLException { - if (fgIconBaseURL == null) - throw new MalformedURLException(); - - StringBuffer buffer = new StringBuffer(prefix); - buffer.append('/'); - buffer.append(name); - return new URL(fgIconBaseURL, buffer.toString()); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java deleted file mode 100644 index 1b3733a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.actions; - -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -//import net.sourceforge.phpdt.core.IPackageFragment; -//import net.sourceforge.phpdt.core.IPackageFragmentRoot; -//import net.sourceforge.phpdt.internal.corext.refactoring.util.ResourceUtil; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -//import net.sourceforge.phpeclipse.ui.WebUI; - -//import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectNature; -//import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Shell; - -/* - * http://dev.eclipse.org/bugs/show_bug.cgi?id=19104 - */ -public class ActionUtil { - - private ActionUtil() { - } - - // bug 31998 we will have to disable renaming of linked packages (and cus) -// public static boolean mustDisableJavaModelAction(Shell shell, Object element) { -// if (!(element instanceof IPackageFragment) -// && !(element instanceof IPackageFragmentRoot)) -// return false; -// -// IResource resource = ResourceUtil.getResource(element); -// if ((resource == null) || (!(resource instanceof IFolder)) -// || (!resource.isLinked())) -// return false; -// -// MessageDialog -// .openInformation( -// shell, -// ActionMessages.getString("ActionUtil.not_possible"), ActionMessages.getString("ActionUtil.no_linked")); //$NON-NLS-1$ //$NON-NLS-2$ -// return true; -// } - - public static boolean isProcessable(Shell shell, PHPEditor editor) { - if (editor == null) - return true; - IJavaElement input = SelectionConverter.getInput(editor); - // if a Java editor doesn't have an input of type Java element - // then it is for sure not on the build path - if (input == null) { - MessageDialog.openInformation(shell, ActionMessages - .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ - ActionMessages - .getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ - return false; - } - return isProcessable(shell, input); - } - - public static boolean isProcessable(Shell shell, Object element) { - if (!(element instanceof IJavaElement)) - return true; - - if (isOnBuildPath((IJavaElement) element)) - return true; - MessageDialog.openInformation(shell, ActionMessages - .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ - ActionMessages.getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ - return false; - } - - public static boolean isOnBuildPath(IJavaElement element) { - // fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051 - if (element.getElementType() == IJavaElement.JAVA_PROJECT) - return true; - IJavaProject project = element.getJavaProject(); - try { - // if (!project.isOnClasspath(element)) - // return false; - IProject resourceProject = project.getProject(); - if (resourceProject == null) - return false; - IProjectNature nature = resourceProject - .getNature(/*WebUI*/PHPeclipsePlugin.PHP_NATURE_ID); - // We have a Java project - if (nature != null) - return true; - } catch (CoreException e) { - } - return false; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java deleted file mode 100644 index dfa6874..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java +++ /dev/null @@ -1,564 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.actions; - -import java.util.ResourceBundle; - -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; -import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; -import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager; -import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager.UndoSpec; -import net.sourceforge.phpdt.internal.ui.text.phpdoc.JavaDocAutoIndentStrategy; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.IRewriteTarget; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.widgets.Display; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorExtension3; -import org.eclipse.ui.texteditor.TextEditorAction; - -/** - * Indents a line or range of lines in a Java document to its correct position. - * No complete AST must be present, the indentation is computed using - * heuristics. The algorith used is fast for single lines, but does not store - * any information and therefore not so efficient for large line ranges. - * - * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner - * @see net.sourceforge.phpdt.internal.ui.text.JavaIndenter - * @since 3.0 - */ -public class IndentAction extends TextEditorAction { - - /** The caret offset after an indent operation. */ - private int fCaretOffset; - - /** - * Whether this is the action invoked by TAB. When true, - * indentation behaves differently to accomodate normal TAB operation. - */ - private final boolean fIsTabAction; - - /** - * Creates a new instance. - * - * @param bundle - * the resource bundle - * @param prefix - * the prefix to use for keys in bundle - * @param editor - * the text editor - * @param isTabAction - * whether the action should insert tabs if over the indentation - */ - public IndentAction(ResourceBundle bundle, String prefix, - ITextEditor editor, boolean isTabAction) { - super(bundle, prefix, editor); - fIsTabAction = isTabAction; - } - - /* - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - // update has been called by the framework - if (!isEnabled() || !validateEditorInputState()) - return; - - ITextSelection selection = getSelection(); - final IDocument document = getDocument(); - - if (document != null) { - - final int offset = selection.getOffset(); - final int length = selection.getLength(); - final Position end = new Position(offset + length); - final int firstLine, nLines; - fCaretOffset = -1; - - try { - document.addPosition(end); - firstLine = document.getLineOfOffset(offset); - // check for marginal (zero-length) lines - int minusOne = length == 0 ? 0 : 1; - nLines = document.getLineOfOffset(offset + length - minusOne) - - firstLine + 1; - } catch (BadLocationException e) { - // will only happen on concurrent modification - WebUI.log(new Status(IStatus.ERROR, WebUI - .getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$ - return; - } - - Runnable runnable = new Runnable() { - public void run() { - IRewriteTarget target = (IRewriteTarget) getTextEditor() - .getAdapter(IRewriteTarget.class); - if (target != null) { - target.beginCompoundChange(); - target.setRedraw(false); - } - - try { - JavaHeuristicScanner scanner = new JavaHeuristicScanner( - document); - JavaIndenter indenter = new JavaIndenter(document, - scanner); - boolean hasChanged = false; - for (int i = 0; i < nLines; i++) { - hasChanged |= indentLine(document, firstLine + i, - offset, indenter, scanner); - } - - // update caret position: move to new position when - // indenting just one line - // keep selection when indenting multiple - int newOffset, newLength; - if (fIsTabAction) { - newOffset = fCaretOffset; - newLength = 0; - } else if (nLines > 1) { - newOffset = offset; - newLength = end.getOffset() - offset; - } else { - newOffset = fCaretOffset; - newLength = 0; - } - - // always reset the selection if anything was replaced - // but not when we had a singleline nontab invocation - if (newOffset != -1 - && (hasChanged || newOffset != offset || newLength != length)) - selectAndReveal(newOffset, newLength); - - document.removePosition(end); - } catch (BadLocationException e) { - // will only happen on concurrent modification - WebUI.log(new Status(IStatus.ERROR, - WebUI.getPluginId(), IStatus.OK, - "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$ - - } finally { - - if (target != null) { - target.endCompoundChange(); - target.setRedraw(true); - } - } - } - }; - - if (nLines > 50) { - Display display = getTextEditor().getEditorSite() - .getWorkbenchWindow().getShell().getDisplay(); - BusyIndicator.showWhile(display, runnable); - } else - runnable.run(); - - } - } - - /** - * Selects the given range on the editor. - * - * @param newOffset - * the selection offset - * @param newLength - * the selection range - */ - private void selectAndReveal(int newOffset, int newLength) { - Assert.isTrue(newOffset >= 0); - Assert.isTrue(newLength >= 0); - ITextEditor editor = getTextEditor(); - if (editor instanceof PHPEditor) { - ISourceViewer viewer = ((PHPEditor) editor).getViewer(); - if (viewer != null) - viewer.setSelectedRange(newOffset, newLength); - } else - // this is too intrusive, but will never get called anyway - getTextEditor().selectAndReveal(newOffset, newLength); - - } - - /** - * Indents a single line using the java heuristic scanner. Javadoc and - * multiline comments are indented as specified by the - * JavaDocAutoIndentStrategy. - * - * @param document - * the document - * @param line - * the line to be indented - * @param caret - * the caret position - * @param indenter - * the java indenter - * @param scanner - * the heuristic scanner - * @return true if document was modified, - * false otherwise - * @throws BadLocationException - * if the document got changed concurrently - */ - private boolean indentLine(IDocument document, int line, int caret, - JavaIndenter indenter, JavaHeuristicScanner scanner) - throws BadLocationException { - IRegion currentLine = document.getLineInformation(line); - int offset = currentLine.getOffset(); - int wsStart = offset; // where we start searching for non-WS; after - // the "//" in single line comments - - String indent = null; - if (offset < document.getLength()) { - ITypedRegion partition = TextUtilities.getPartition(document, - IPHPPartitions.PHP_PARTITIONING, offset, true); - String type = partition.getType(); - if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) - || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { - - // TODO this is a hack - // what I want to do - // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, - // offset); - // return; - - int start = 0; - if (line > 0) { - - IRegion previousLine = document - .getLineInformation(line - 1); - start = previousLine.getOffset() + previousLine.getLength(); - } - - DocumentCommand command = new DocumentCommand() { - }; - command.text = "\n"; //$NON-NLS-1$ - command.offset = start; - new JavaDocAutoIndentStrategy(IPHPPartitions.PHP_PARTITIONING) - .customizeDocumentCommand(document, command); - int to = 1; - while (to < command.text.length() - && Character.isWhitespace(command.text.charAt(to))) - to++; - indent = command.text.substring(1, to); - -// omit Java style -// } else if (!fIsTabAction && partition.getOffset() == offset -// && type.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { -// -// // line comment starting at position 0 -> indent inside -// int slashes = 2; -// while (slashes < document.getLength() - 1 -// && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$ -// slashes += 2; -// -// wsStart = offset + slashes; -// -// StringBuffer computed = indenter.computeIndentation(offset); -// int tabSize = PHPeclipsePlugin -// .getDefault() -// .getPreferenceStore() -// .getInt( -// AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); -// while (slashes > 0 && computed.length() > 0) { -// char c = computed.charAt(0); -// if (c == '\t') -// if (slashes > tabSize) -// slashes -= tabSize; -// else -// break; -// else if (c == ' ') -// slashes--; -// else -// break; -// -// computed.deleteCharAt(0); -// } -// -// indent = document.get(offset, wsStart - offset) + computed; - - } - } - - // standard java indentation - if (indent == null) { - StringBuffer computed = indenter.computeIndentation(offset); - if (computed != null) - indent = computed.toString(); - else - //indent = new String(); - return true; // prevent affecting html part - } - - // change document: - // get current white space - int lineLength = currentLine.getLength(); - int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart, - offset + lineLength); - if (end == JavaHeuristicScanner.NOT_FOUND) - end = offset + lineLength; - int length = end - offset; - String currentIndent = document.get(offset, length); - - // if we are right before the text start / line end, and already after - // the insertion point - // then just insert a tab. - if (fIsTabAction && caret == end - && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { - String tab = getTabEquivalent(); - document.replace(caret, 0, tab); - fCaretOffset = caret + tab.length(); - return true; - } - - // set the caret offset so it can be used when setting the selection - if (caret >= offset && caret <= end) - fCaretOffset = offset + indent.length(); - else - fCaretOffset = -1; - - // only change the document if it is a real change - if (!indent.equals(currentIndent)) { - String deletedText = document.get(offset, length); - document.replace(offset, length, indent); - - if (fIsTabAction - && indent.length() > currentIndent.length() - && WebUI.getDefault().getPreferenceStore() - .getBoolean( - PreferenceConstants.EDITOR_SMART_BACKSPACE)) { - ITextEditor editor = getTextEditor(); - if (editor != null) { - final SmartBackspaceManager manager = (SmartBackspaceManager) editor - .getAdapter(SmartBackspaceManager.class); - if (manager != null) { - try { - // restore smart portion - ReplaceEdit smart = new ReplaceEdit(offset, indent - .length(), deletedText); - - final UndoSpec spec = new UndoSpec(offset - + indent.length(), new Region(caret, 0), - new TextEdit[] { smart }, 2, null); - manager.register(spec); - } catch (MalformedTreeException e) { - // log & ignore - WebUI.log(new Status(IStatus.ERROR, - WebUI.getPluginId(), IStatus.OK, - "Illegal smart backspace action", e)); //$NON-NLS-1$ - } - } - } - } - - return true; - } else - return false; - } - - /** - * Returns the size in characters of a string. All characters count one, - * tabs count the editor's preference for the tab display - * - * @param indent - * the string to be measured. - * @return - */ - private int whiteSpaceLength(String indent) { - if (indent == null) - return 0; - else { - int size = 0; - int l = indent.length(); - int tabSize = WebUI.getDefault().getPreferenceStore().getInt( - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - - for (int i = 0; i < l; i++) - size += indent.charAt(i) == '\t' ? tabSize : 1; - return size; - } - } - - /** - * Returns a tab equivalent, either as a tab character or as spaces, - * depending on the editor and formatter preferences. - * - * @return a string representing one tab in the editor, never - * null - */ - private String getTabEquivalent() { - String tab; - if (WebUI.getDefault().getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { - int size = JavaCore.getPlugin().getPluginPreferences().getInt( - DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < size; i++) - buf.append(' '); - tab = buf.toString(); - } else - tab = "\t"; //$NON-NLS-1$ - - return tab; - } - - /** - * Returns the editor's selection provider. - * - * @return the editor's selection provider or null - */ - private ISelectionProvider getSelectionProvider() { - ITextEditor editor = getTextEditor(); - if (editor != null) { - return editor.getSelectionProvider(); - } - return null; - } - - /* - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - super.update(); - - if (isEnabled()) - if (fIsTabAction) - setEnabled(canModifyEditor() && isSmartMode() - && isValidSelection()); - else - setEnabled(canModifyEditor() && !getSelection().isEmpty()); - } - - /** - * Returns if the current selection is valid, i.e. whether it is empty and - * the caret in the whitespace at the start of a line, or covers multiple - * lines. - * - * @return true if the selection is valid for an indent - * operation - */ - private boolean isValidSelection() { - ITextSelection selection = getSelection(); - if (selection.isEmpty()) - return false; - - int offset = selection.getOffset(); - int length = selection.getLength(); - - IDocument document = getDocument(); - if (document == null) - return false; - - try { - IRegion firstLine = document.getLineInformationOfOffset(offset); - int lineOffset = firstLine.getOffset(); - - // either the selection has to be empty and the caret in the WS at - // the line start - // or the selection has to extend over multiple lines - if (length == 0) - return document.get(lineOffset, offset - lineOffset).trim() - .length() == 0; - else - // return lineOffset + firstLine.getLength() < offset + length; - return false; // only enable for empty selections for now - - } catch (BadLocationException e) { - } - - return false; - } - - /** - * Returns the smart preference state. - * - * @return true if smart mode is on, false - * otherwise - */ - private boolean isSmartMode() { - ITextEditor editor = getTextEditor(); - - if (editor instanceof ITextEditorExtension3) - return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; - - return false; - } - - /** - * Returns the document currently displayed in the editor, or - * null if none can be obtained. - * - * @return the current document or null - */ - private IDocument getDocument() { - - ITextEditor editor = getTextEditor(); - if (editor != null) { - - IDocumentProvider provider = editor.getDocumentProvider(); - IEditorInput input = editor.getEditorInput(); - if (provider != null && input != null) - return provider.getDocument(input); - - } - return null; - } - - /** - * Returns the selection on the editor or an invalid selection if none can - * be obtained. Returns never null. - * - * @return the current selection, never null - */ - private ITextSelection getSelection() { - ISelectionProvider provider = getSelectionProvider(); - if (provider != null) { - - ISelection selection = provider.getSelection(); - if (selection instanceof ITextSelection) - return (ITextSelection) selection; - } - - // null object - return TextSelection.emptySelection(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java deleted file mode 100644 index 21f7c26..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java +++ /dev/null @@ -1,263 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.actions; - -//import java.util.Iterator; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -//import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaModelException; -//import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IWorkbenchPart; - -public class SelectionConverter { - - private static final IJavaElement[] EMPTY_RESULT = new IJavaElement[0]; - - private SelectionConverter() { - // no instance - } - - /** - * Converts the selection provided by the given part into a structured - * selection. The following conversion rules are used: - *
    - *
  • part instanceof PHPEditor: returns a structured - * selection using code resolve to convert the editor's text selection.
  • - *
  • part instanceof IWorkbenchPart: returns the part's - * selection if it is a structured selection.
  • - *
  • default: returns an empty structured selection.
  • - *
- */ - public static IStructuredSelection getStructuredSelection( - IWorkbenchPart part) throws JavaModelException { - if (part instanceof PHPEditor) - return new StructuredSelection(codeResolve((PHPEditor) part)); - ISelectionProvider provider = part.getSite().getSelectionProvider(); - if (provider != null) { - ISelection selection = provider.getSelection(); - if (selection instanceof IStructuredSelection) - return (IStructuredSelection) selection; - } - return StructuredSelection.EMPTY; - } - - /** - * Converts the given structured selection into an array of Java elements. - * An empty array is returned if one of the elements stored in the - * structured selection is not of tupe IJavaElement - */ -// public static IJavaElement[] getElements(IStructuredSelection selection) { -// if (!selection.isEmpty()) { -// IJavaElement[] result = new IJavaElement[selection.size()]; -// int i = 0; -// for (Iterator iter = selection.iterator(); iter.hasNext(); i++) { -// Object element = (Object) iter.next(); -// if (!(element instanceof IJavaElement)) -// return EMPTY_RESULT; -// result[i] = (IJavaElement) element; -// } -// return result; -// } -// return EMPTY_RESULT; -// } - - public static boolean canOperateOn(PHPEditor editor) { - if (editor == null) - return false; - return getInput(editor) != null; - - } - - /** - * Converts the text selection provided by the given editor into an array of - * Java elements. If the selection doesn't cover a Java element and the - * selection's length is greater than 0 the methods returns the editor's - * input element. - */ - public static IJavaElement[] codeResolveOrInput(PHPEditor editor) - throws JavaModelException { - IJavaElement input = getInput(editor); - ITextSelection selection = (ITextSelection) editor - .getSelectionProvider().getSelection(); - IJavaElement[] result = codeResolve(input, selection); - if (result.length == 0) { - result = new IJavaElement[] { input }; - } - return result; - } - -// public static IJavaElement[] codeResolveOrInputHandled(PHPEditor editor, -// Shell shell, String title) { -// try { -// return codeResolveOrInput(editor); -// } catch (JavaModelException e) { -// ExceptionHandler.handle(e, shell, title, ActionMessages -// .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ -// } -// return null; -// } - - /** - * Converts the text selection provided by the given editor a Java element - * by asking the user if code reolve returned more than one result. If the - * selection doesn't cover a Java element and the selection's length is - * greater than 0 the methods returns the editor's input element. - */ - public static IJavaElement codeResolveOrInput(PHPEditor editor, - Shell shell, String title, String message) - throws JavaModelException { - IJavaElement[] elements = codeResolveOrInput(editor); - if (elements == null || elements.length == 0) - return null; - IJavaElement candidate = elements[0]; - if (elements.length > 1) { - candidate = OpenActionUtil.selectJavaElement(elements, shell, - title, message); - } - return candidate; - } - -// public static IJavaElement codeResolveOrInputHandled(PHPEditor editor, -// Shell shell, String title, String message) { -// try { -// return codeResolveOrInput(editor, shell, title, message); -// } catch (JavaModelException e) { -// ExceptionHandler.handle(e, shell, title, ActionMessages -// .getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$ -// } -// return null; -// } - - public static IJavaElement[] codeResolve(PHPEditor editor) - throws JavaModelException { - return codeResolve(getInput(editor), (ITextSelection) editor - .getSelectionProvider().getSelection()); - } - - /** - * Converts the text selection provided by the given editor a Java element - * by asking the user if code reolve returned more than one result. If the - * selection doesn't cover a Java element null is returned. - */ -// public static IJavaElement codeResolve(PHPEditor editor, Shell shell, -// String title, String message) throws JavaModelException { -// IJavaElement[] elements = codeResolve(editor); -// if (elements == null || elements.length == 0) -// return null; -// IJavaElement candidate = elements[0]; -// if (elements.length > 1) { -// candidate = OpenActionUtil.selectJavaElement(elements, shell, -// title, message); -// } -// return candidate; -// } - -// public static IJavaElement[] codeResolveHandled(PHPEditor editor, -// Shell shell, String title) { -// try { -// return codeResolve(editor); -// } catch (JavaModelException e) { -// ExceptionHandler.handle(e, shell, title, ActionMessages -// .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ -// } -// return null; -// } - - public static IJavaElement getElementAtOffset(PHPEditor editor) - throws JavaModelException { - return getElementAtOffset(getInput(editor), (ITextSelection) editor - .getSelectionProvider().getSelection()); - } - -// public static IType getTypeAtOffset(PHPEditor editor) -// throws JavaModelException { -// IJavaElement element = SelectionConverter.getElementAtOffset(editor); -// IType type = (IType) element.getAncestor(IJavaElement.TYPE); -// if (type == null) { -// ICompilationUnit unit = SelectionConverter -// .getInputAsCompilationUnit(editor); -// if (unit != null) -// type = unit.findPrimaryType(); -// } -// return type; -// } - - public static IJavaElement getInput(PHPEditor editor) { - if (editor == null) - return null; - IEditorInput input = editor.getEditorInput(); - // if (input instanceof IClassFileEditorInput) - // return ((IClassFileEditorInput)input).getClassFile(); - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - return manager.getWorkingCopy(input); - } - -// public static ICompilationUnit getInputAsCompilationUnit(PHPEditor editor) { -// Object editorInput = SelectionConverter.getInput(editor); -// if (editorInput instanceof ICompilationUnit) -// return (ICompilationUnit) editorInput; -// else -// return null; -// } - - private static IJavaElement[] codeResolve(IJavaElement input, - ITextSelection selection) throws JavaModelException { - // if (input instanceof ICodeAssist) { - // IJavaElement[] elements= - // ((ICodeAssist)input).codeSelect(selection.getOffset(), - // selection.getLength()); - // if (elements != null && elements.length > 0) - // return elements; - // } - return EMPTY_RESULT; - } - - private static IJavaElement getElementAtOffset(IJavaElement input, - ITextSelection selection) throws JavaModelException { - if (input instanceof ICompilationUnit) { - ICompilationUnit cunit = (ICompilationUnit) input; - if (cunit.isWorkingCopy()) { - synchronized (cunit) { - cunit.reconcile(); - } - } - IJavaElement ref = cunit.getElementAt(selection.getOffset()); - if (ref == null) - return input; - else - return ref; - } - // else if (input instanceof IClassFile) { - // IJavaElement ref= - // ((IClassFile)input).getElementAt(selection.getOffset()); - // if (ref == null) - // return input; - // else - // return ref; - // } - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java deleted file mode 100644 index 31b6fc9..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.actions; - -import java.lang.reflect.InvocationTargetException; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.jface.operation.IRunnableWithProgress; - -/** - * An IRunnableWithProgress that adapts and - * IWorkspaceRunnable so that is can be executed inside - * IRunnableContext. OperationCanceledException - * thrown by the apapted runnabled are cought and rethrown as a - * InterruptedException. - */ -public class WorkbenchRunnableAdapter implements IRunnableWithProgress { - - private IWorkspaceRunnable fWorkspaceRunnable; - - public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable) { - fWorkspaceRunnable = runnable; - } - - /* - * @see IRunnableWithProgress#run(IProgressMonitor) - */ - public void run(IProgressMonitor monitor) throws InvocationTargetException, - InterruptedException { - try { - PHPeclipsePlugin.run(fWorkspaceRunnable, monitor); - } catch (OperationCanceledException e) { - throw new InterruptedException(e.getMessage()); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java deleted file mode 100644 index 7985495..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.dialogs; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; - -/** - * A settable IStatus. Can be an error, warning, info or ok. For error, info and - * warning states, a message describes the problem. - */ -public class StatusInfo implements IStatus { - - private String fStatusMessage; - - private int fSeverity; - - /** - * Creates a status set to OK (no message) - */ - public StatusInfo() { - this(OK, null); - } - - /** - * Creates a status . - * - * @param severity - * The status severity: ERROR, WARNING, INFO and OK. - * @param message - * The message of the status. Applies only for ERROR, WARNING and - * INFO. - */ - public StatusInfo(int severity, String message) { - fStatusMessage = message; - fSeverity = severity; - } - - /** - * Returns if the status' severity is OK. - */ - public boolean isOK() { - return fSeverity == IStatus.OK; - } - - /** - * Returns if the status' severity is WARNING. - */ - public boolean isWarning() { - return fSeverity == IStatus.WARNING; - } - - /** - * Returns if the status' severity is INFO. - */ - public boolean isInfo() { - return fSeverity == IStatus.INFO; - } - - /** - * Returns if the status' severity is ERROR. - */ - public boolean isError() { - return fSeverity == IStatus.ERROR; - } - - /** - * @see IStatus#getMessage - */ - public String getMessage() { - return fStatusMessage; - } - - /** - * Sets the status to ERROR. - * - * @param The - * error message (can be empty, but not null) - */ - public void setError(String errorMessage) { - Assert.isNotNull(errorMessage); - fStatusMessage = errorMessage; - fSeverity = IStatus.ERROR; - } - - /** - * Sets the status to WARNING. - * - * @param The - * warning message (can be empty, but not null) - */ - public void setWarning(String warningMessage) { - Assert.isNotNull(warningMessage); - fStatusMessage = warningMessage; - fSeverity = IStatus.WARNING; - } - - /** - * Sets the status to INFO. - * - * @param The - * info message (can be empty, but not null) - */ - public void setInfo(String infoMessage) { - Assert.isNotNull(infoMessage); - fStatusMessage = infoMessage; - fSeverity = IStatus.INFO; - } - - /** - * Sets the status to OK. - */ - public void setOK() { - fStatusMessage = null; - fSeverity = IStatus.OK; - } - - /* - * @see IStatus#matches(int) - */ - public boolean matches(int severityMask) { - return (fSeverity & severityMask) != 0; - } - - /** - * Returns always false. - * - * @see IStatus#isMultiStatus() - */ - public boolean isMultiStatus() { - return false; - } - - /* - * @see IStatus#getSeverity() - */ - public int getSeverity() { - return fSeverity; - } - - /* - * @see IStatus#getPlugin() - */ - public String getPlugin() { - return WebUI.PLUGIN_ID; - } - - /** - * Returns always null. - * - * @see IStatus#getException() - */ - public Throwable getException() { - return null; - } - - /** - * Returns always the error severity. - * - * @see IStatus#getCode() - */ - public int getCode() { - return fSeverity; - } - - /** - * Returns always null. - * - * @see IStatus#getChildren() - */ - public IStatus[] getChildren() { - return new IStatus[0]; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java deleted file mode 100644 index 49ea330..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.dnd; - -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.dnd.ByteArrayTransfer; -import org.eclipse.swt.dnd.TransferData; - -public class LocalSelectionTransfer extends ByteArrayTransfer { - - // First attempt to create a UUID for the type name to make sure that - // different Eclipse applications use different "types" of - // LocalSelectionTransfer - private static final String TYPE_NAME = "local-selection-transfer-format" + (new Long(System.currentTimeMillis())).toString(); //$NON-NLS-1$; - - private static final int TYPEID = registerType(TYPE_NAME); - - private static final LocalSelectionTransfer INSTANCE = new LocalSelectionTransfer(); - - private ISelection fSelection; - - private int fSelectionSetTime; - - private LocalSelectionTransfer() { - } - - /** - * Returns the singleton. - */ - public static LocalSelectionTransfer getInstance() { - return INSTANCE; - } - - /** - * Sets the transfer data for local use. - */ - public void setSelection(ISelection s) { - fSelection = s; - } - - /** - * Returns the local transfer data. - */ - public ISelection getSelection() { - return fSelection; - } - - public void javaToNative(Object object, TransferData transferData) { - // No encoding needed since this is a hardcoded string read and written - // in the same process. - // See nativeToJava below - byte[] check = TYPE_NAME.getBytes(); - super.javaToNative(check, transferData); - } - - public Object nativeToJava(TransferData transferData) { - Object result = super.nativeToJava(transferData); - if (isInvalidNativeType(result)) { - WebUI.log(IStatus.ERROR, PHPUIMessages - .getString("LocalSelectionTransfer.errorMessage")); //$NON-NLS-1$ - } - return fSelection; - } - - private boolean isInvalidNativeType(Object result) { - // No encoding needed since this is a hardcoded string read and written - // in the same process. - // See javaToNative above - return !(result instanceof byte[]) - || !TYPE_NAME.equals(new String((byte[]) result)); - } - - /** - * The type id used to identify this transfer. - */ - protected int[] getTypeIds() { - return new int[] { TYPEID }; - } - - protected String[] getTypeNames() { - return new String[] { TYPE_NAME }; - } - - public int getSelectionSetTime() { - return fSelectionSetTime; - } - - public void setSelectionSetTime(int time) { - fSelectionSetTime = time; - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java deleted file mode 100644 index e459418..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.dnd; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants; -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -import net.sourceforge.phpdt.internal.ui.util.SWTUtil; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.jface.dialogs.ErrorDialog; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DragSourceAdapter; -import org.eclipse.swt.dnd.DragSourceEvent; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.part.ResourceTransfer; - -/** - * A drag adapter that transfers the current selection as IResource. - * Only those elements in the selection are part of the transfer which can be - * converted into an IResource . - */ -public class ResourceTransferDragAdapter extends DragSourceAdapter implements - TransferDragSourceListener { - - private ISelectionProvider fProvider; - - private static final List EMPTY_LIST = new ArrayList(0); - - /** - * Creates a new ResourceTransferDragAdapter for the given selection - * provider. - * - * @param provider - * the selection provider to access the viewer's selection - */ - public ResourceTransferDragAdapter(ISelectionProvider provider) { - fProvider = provider; - Assert.isNotNull(fProvider); - } - - public Transfer getTransfer() { - return ResourceTransfer.getInstance(); - } - - public void dragStart(DragSourceEvent event) { - event.doit = convertSelection().size() > 0; - } - - public void dragSetData(DragSourceEvent event) { - List resources = convertSelection(); - event.data = (IResource[]) resources.toArray(new IResource[resources - .size()]); - } - - public void dragFinished(DragSourceEvent event) { - if (!event.doit) - return; - - if (event.detail == DND.DROP_MOVE) { - handleFinishedDropMove(event); - } - } - - private List convertSelection() { - ISelection s = fProvider.getSelection(); - if (!(s instanceof IStructuredSelection)) - return EMPTY_LIST; - IStructuredSelection selection = (IStructuredSelection) s; - List result = new ArrayList(selection.size()); - for (Iterator iter = selection.iterator(); iter.hasNext();) { - Object element = iter.next(); - if (element instanceof IAdaptable) { - IAdaptable adaptable = (IAdaptable) element; - IResource resource = (IResource) adaptable - .getAdapter(IResource.class); - if (resource != null) - result.add(resource); - } - } - return result; - } - - private void handleFinishedDropMove(DragSourceEvent event) { - MultiStatus status = new MultiStatus( - WebUI.getPluginId(), - IJavaStatusConstants.INTERNAL_ERROR, - PHPUIMessages - .getString("ResourceTransferDragAdapter.cannot_delete_resource"), //$NON-NLS-1$ - null); - List resources = convertSelection(); - for (Iterator iter = resources.iterator(); iter.hasNext();) { - IResource resource = (IResource) iter.next(); - try { - resource.delete(true, null); - } catch (CoreException e) { - status.add(e.getStatus()); - } - } - if (status.getChildren().length > 0) { - Shell parent = SWTUtil.getShell(event.widget); - ErrorDialog error = new ErrorDialog( - parent, - PHPUIMessages - .getString("ResourceTransferDragAdapter.moving_resource"), //$NON-NLS-1$ - PHPUIMessages - .getString("ResourceTransferDragAdapter.cannot_delete_files"), //$NON-NLS-1$ - status, IStatus.ERROR); - error.open(); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java deleted file mode 100644 index e25508d..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java +++ /dev/null @@ -1,311 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.filters; - -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SafeRunner; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.ui.IPluginContribution; -import org.eclipse.ui.activities.WorkbenchActivityHelper; - -/** - * Represents a custom filter which is provided by the - * "net.sourceforge.phpdt.ui.javaElementFilters" extension point. - * - * since 2.0 - */ -public class FilterDescriptor implements Comparable, IPluginContribution { - - private static String PATTERN_FILTER_ID_PREFIX = "_patternFilterId_"; //$NON-NLS-1$ - - private static final String EXTENSION_POINT_NAME = "phpElementFilters"; //$NON-NLS-1$ - - private static final String FILTER_TAG = "filter"; //$NON-NLS-1$ - - private static final String PATTERN_ATTRIBUTE = "pattern"; //$NON-NLS-1$ - - private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$ - - /** - * @deprecated as of 3.0 use {@link FilterDescriptor#TARGET_ID_ATTRIBUTE} - */ - private static final String VIEW_ID_ATTRIBUTE = "viewId"; //$NON-NLS-1$ - - private static final String TARGET_ID_ATTRIBUTE = "targetId"; //$NON-NLS-1$ - - private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$ - - private static final String NAME_ATTRIBUTE = "name"; //$NON-NLS-1$ - - private static final String ENABLED_ATTRIBUTE = "enabled"; //$NON-NLS-1$ - - private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ - - /** - * @deprecated use "enabled" instead - */ - private static final String SELECTED_ATTRIBUTE = "selected"; //$NON-NLS-1$ - - private static FilterDescriptor[] fgFilterDescriptors; - - private IConfigurationElement fElement; - - /** - * Returns all contributed Java element filters. - */ - public static FilterDescriptor[] getFilterDescriptors() { - if (fgFilterDescriptors == null) { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - IConfigurationElement[] elements = registry - .getConfigurationElementsFor(WebUI.PLUGIN_ID, - EXTENSION_POINT_NAME); - fgFilterDescriptors = createFilterDescriptors(elements); - } - return fgFilterDescriptors; - } - - /** - * Returns all Java element filters which are contributed to the given view. - */ - public static FilterDescriptor[] getFilterDescriptors(String targetId) { - FilterDescriptor[] filterDescs = FilterDescriptor - .getFilterDescriptors(); - List result = new ArrayList(filterDescs.length); - for (int i = 0; i < filterDescs.length; i++) { - String tid = filterDescs[i].getTargetId(); - if (WorkbenchActivityHelper.filterItem(filterDescs[i])) - continue; - if (tid == null || tid.equals(targetId)) - result.add(filterDescs[i]); - } - return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result - .size()]); - } - - /** - * Creates a new filter descriptor for the given configuration element. - */ - private FilterDescriptor(IConfigurationElement element) { - fElement = element; - // it is either a pattern filter or a custom filter - Assert - .isTrue( - isPatternFilter() ^ isCustomFilter(), - "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$ - Assert - .isNotNull( - getId(), - "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$ - Assert - .isNotNull( - getName(), - "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$ - } - - /** - * Creates a new ViewerFilter. This method is only valid for - * viewer filters. - */ - public ViewerFilter createViewerFilter() { - if (!isCustomFilter()) - return null; - - final ViewerFilter[] result = new ViewerFilter[1]; - String message = FilterMessages.getFormattedString( - "FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$ - ISafeRunnable code = new SafeRunnable(message) { - /* - * @see org.eclipse.core.runtime.ISafeRunnable#run() - */ - public void run() throws Exception { - result[0] = (ViewerFilter) fElement - .createExecutableExtension(CLASS_ATTRIBUTE); - } - - }; - SafeRunner.run(code); - return result[0]; - } - - // ---- XML Attribute accessors - // --------------------------------------------- - - /** - * Returns the filter's id. - *

- * This attribute is mandatory for custom filters. The ID for pattern - * filters is PATTERN_FILTER_ID_PREFIX plus the pattern itself. - *

- */ - public String getId() { - if (isPatternFilter()) { - String targetId = getTargetId(); - if (targetId == null) - return PATTERN_FILTER_ID_PREFIX + getPattern(); - else - return targetId + PATTERN_FILTER_ID_PREFIX + getPattern(); - } else - return fElement.getAttribute(ID_ATTRIBUTE); - } - - /** - * Returns the filter's name. - *

- * If the name of a pattern filter is missing then the pattern is used as - * its name. - *

- */ - public String getName() { - String name = fElement.getAttribute(NAME_ATTRIBUTE); - if (name == null && isPatternFilter()) - name = getPattern(); - return name; - } - - /** - * Returns the filter's pattern. - * - * @return the pattern string or null if it's not a pattern - * filter - */ - public String getPattern() { - return fElement.getAttribute(PATTERN_ATTRIBUTE); - } - - /** - * Returns the filter's viewId. - * - * @return the view ID or null if the filter is for all views - * @since 3.0 - */ - public String getTargetId() { - String tid = fElement.getAttribute(TARGET_ID_ATTRIBUTE); - - if (tid != null) - return tid; - - // Backwards compatibility code - return fElement.getAttribute(VIEW_ID_ATTRIBUTE); - - } - - /** - * Returns the filter's description. - * - * @return the description or null if no description is - * provided - */ - public String getDescription() { - String description = fElement.getAttribute(DESCRIPTION_ATTRIBUTE); - if (description == null) - description = ""; //$NON-NLS-1$ - return description; - } - - /** - * @return true if this filter is a custom filter. - */ - public boolean isPatternFilter() { - return getPattern() != null; - } - - /** - * @return true if this filter is a pattern filter. - */ - public boolean isCustomFilter() { - return fElement.getAttribute(CLASS_ATTRIBUTE) != null; - } - - /** - * Returns true if the filter is initially enabled. - * - * This attribute is optional and defaults to true. - */ - public boolean isEnabled() { - String strVal = fElement.getAttribute(ENABLED_ATTRIBUTE); - if (strVal == null) - // backward compatibility - strVal = fElement.getAttribute(SELECTED_ATTRIBUTE); - return strVal == null || Boolean.valueOf(strVal).booleanValue(); - } - - /* - * Implements a method from IComparable - */ - public int compareTo(Object o) { - if (o instanceof FilterDescriptor) - return Collator.getInstance().compare(getName(), - ((FilterDescriptor) o).getName()); - else - return Integer.MIN_VALUE; - } - - // ---- initialization --------------------------------------------------- - - /** - * Creates the filter descriptors. - */ - private static FilterDescriptor[] createFilterDescriptors( - IConfigurationElement[] elements) { - List result = new ArrayList(5); - Set descIds = new HashSet(5); - for (int i = 0; i < elements.length; i++) { - final IConfigurationElement element = elements[i]; - if (FILTER_TAG.equals(element.getName())) { - - final FilterDescriptor[] desc = new FilterDescriptor[1]; - SafeRunner - .run(new SafeRunnable( - FilterMessages - .getString("FilterDescriptor.filterDescriptionCreationError.message")) { //$NON-NLS-1$ - public void run() throws Exception { - desc[0] = new FilterDescriptor(element); - } - }); - - if (desc[0] != null && !descIds.contains(desc[0].getId())) { - result.add(desc[0]); - descIds.add(desc[0].getId()); - } - } - } - Collections.sort(result); - return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result - .size()]); - } - - public String getLocalId() { - return fElement.getAttribute(ID_ATTRIBUTE); - } - - public String getPluginId() { - return fElement.getDeclaringExtension().getNamespace(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java deleted file mode 100644 index 9f5bb6b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/** - * Abstract preference page which is used to wrap a - * {@link net.sourceforge.phpdt.internal.ui.preferences.IPreferenceConfigurationBlock}. - * - * @since 3.0 - */ -public abstract class AbstractConfigurationBlockPreferencePage extends - PreferencePage implements IWorkbenchPreferencePage { - - private IPreferenceConfigurationBlock fConfigurationBlock; - - private OverlayPreferenceStore fOverlayStore; - - /** - * Creates a new preference page. - */ - public AbstractConfigurationBlockPreferencePage() { - setDescription(); - setPreferenceStore(); - fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), - new OverlayPreferenceStore.OverlayKey[] {}); - fConfigurationBlock = createConfigurationBlock(fOverlayStore); - } - - protected abstract IPreferenceConfigurationBlock createConfigurationBlock( - OverlayPreferenceStore overlayPreferenceStore); - - protected abstract String getHelpId(); - - protected abstract void setDescription(); - - protected abstract void setPreferenceStore(); - - /* - * @see IWorkbenchPreferencePage#init() - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - getHelpId()); - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - - fOverlayStore.load(); - fOverlayStore.start(); - - fConfigurationBlock.createControl(parent); - - initialize(); - - Dialog.applyDialogFont(parent); - return parent; - } - - private void initialize() { - fConfigurationBlock.initialize(); - } - - /* - * @see PreferencePage#performOk() - */ - public boolean performOk() { - - fConfigurationBlock.performOk(); - - fOverlayStore.propagate(); - - WebUI.getDefault().savePluginPreferences(); - - return true; - } - - /* - * @see PreferencePage#performDefaults() - */ - public void performDefaults() { - - fOverlayStore.loadDefaults(); - fConfigurationBlock.performDefaults(); - - super.performDefaults(); - } - - /* - * @see DialogPage#dispose() - */ - public void dispose() { - - fConfigurationBlock.dispose(); - - if (fOverlayStore != null) { - fOverlayStore.stop(); - fOverlayStore = null; - } - - super.dispose(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java deleted file mode 100644 index dca1e1f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -/** - * Code Assist preference page. - *

- * Note: Must be public since it is referenced from plugin.xml - *

- * - * @since 3.0 - */ -public class CodeAssistPreferencePage extends - AbstractConfigurationBlockPreferencePage { - - /* - * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#getHelpId() - */ - protected String getHelpId() { - return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setDescription() - */ - protected void setDescription() { - // This page has no description - } - - /* - * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setPreferenceStore() - */ - protected void setPreferenceStore() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore) - */ - protected IPreferenceConfigurationBlock createConfigurationBlock( - OverlayPreferenceStore overlayPreferenceStore) { - return new CodeAssistConfigurationBlock(this, overlayPreferenceStore); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java deleted file mode 100644 index 263ef61..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java +++ /dev/null @@ -1,558 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Hashtable; - -import net.sourceforge.phpdt.core.ICodeFormatter; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.ToolFactory; -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.util.TabFolderLayout; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.SWT; -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.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.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -/* - * The page for setting code formatter options - */ -public class CodeFormatterPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - - // Preference store keys, see PHPCore.getOptions - private static final String PREF_NEWLINE_OPENING_BRACES = JavaCore.FORMATTER_NEWLINE_OPENING_BRACE; - - private static final String PREF_NEWLINE_CONTROL_STATEMENT = JavaCore.FORMATTER_NEWLINE_CONTROL; - - private static final String PREF_NEWLINE_CLEAR_ALL = JavaCore.FORMATTER_CLEAR_BLANK_LINES; - - // private static final String PREF_NEWLINE_ELSE_IF= - // PHPCore.FORMATTER_NEWLINE_ELSE_IF; - private static final String PREF_NEWLINE_EMPTY_BLOCK = JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK; - - private static final String PREF_LINE_SPLIT = JavaCore.FORMATTER_LINE_SPLIT; - - private static final String PREF_STYLE_COMPACT_ASSIGNEMENT = JavaCore.FORMATTER_COMPACT_ASSIGNMENT; - - private static final String PREF_STYLE_COMPACT_STRING_CONCATENATION = JavaCore.FORMATTER_COMPACT_STRING_CONCATENATION; - - private static final String PREF_STYLE_COMPACT_ARRAYS = JavaCore.FORMATTER_COMPACT_ARRAYS; - - private static final String PREF_TAB_CHAR = JavaCore.FORMATTER_TAB_CHAR; - - private static final String PREF_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; - - // values - private static final String INSERT = JavaCore.INSERT; - - private static final String DO_NOT_INSERT = JavaCore.DO_NOT_INSERT; - - private static final String COMPACT = JavaCore.COMPACT; - - private static final String NORMAL = JavaCore.NORMAL; - - private static final String TAB = JavaCore.TAB; - - private static final String SPACE = JavaCore.SPACE; - - private static final String CLEAR_ALL = JavaCore.CLEAR_ALL; - - private static final String PRESERVE_ONE = JavaCore.PRESERVE_ONE; - - private static String[] getAllKeys() { - return new String[] { PREF_NEWLINE_OPENING_BRACES, - PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, - // PREF_NEWLINE_ELSE_IF, - PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT, - PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_STYLE_COMPACT_STRING_CONCATENATION, - PREF_STYLE_COMPACT_ARRAYS, - PREF_TAB_CHAR, PREF_TAB_SIZE }; - } - - /** - * Gets the currently configured tab size - * - * @deprecated Inline to avoid reference to preference page - */ - public static int getTabSize() { - String string = (String) JavaCore.getOptions().get(PREF_TAB_SIZE); - return getPositiveIntValue(string, 4); - } - - /** - * Gets the current compating assignement configuration - * - * @deprecated Inline to avoid reference to preference page - */ - public static boolean isCompactingAssignment() { - return COMPACT.equals(JavaCore.getOptions().get( - PREF_STYLE_COMPACT_ASSIGNEMENT)); - } - - /** - * Gets the current compating assignement configuration - * - * @deprecated Inline to avoid reference to preference page - */ - public static boolean useSpaces() { - return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR)); - } - - private static int getPositiveIntValue(String string, int dflt) { - try { - int i = Integer.parseInt(string); - if (i >= 0) { - return i; - } - } catch (NumberFormatException e) { - } - return dflt; - } - - private static class ControlData { - private String fKey; - - private String[] fValues; - - public ControlData(String key, String[] values) { - fKey = key; - fValues = values; - } - - public String getKey() { - return fKey; - } - - public String getValue(boolean selection) { - int index = selection ? 0 : 1; - return fValues[index]; - } - - public String getValue(int index) { - return fValues[index]; - } - - public int getSelection(String value) { - for (int i = 0; i < fValues.length; i++) { - if (value.equals(fValues[i])) { - return i; - } - } - throw new IllegalArgumentException(); - } - } - - private Hashtable fWorkingValues; - - private ArrayList fCheckBoxes; - - private ArrayList fTextBoxes; - - private SelectionListener fButtonSelectionListener; - - private ModifyListener fTextModifyListener; - - private String fPreviewText; - - private IDocument fPreviewDocument; - - private Text fTabSizeTextBox; - - // private SourceViewer fSourceViewer; - - public CodeFormatterPreferencePage() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - setDescription(PHPUIMessages - .getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$ - - fWorkingValues = JavaCore.getOptions(); - fCheckBoxes = new ArrayList(); - fTextBoxes = new ArrayList(); - - fButtonSelectionListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - if (!e.widget.isDisposed()) { - controlChanged((Button) e.widget); - } - } - }; - - fTextModifyListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - if (!e.widget.isDisposed()) { - textChanged((Text) e.widget); - } - } - }; - - fPreviewDocument = new Document(); - fPreviewText = loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ - } - - /* - * @see IWorkbenchPreferencePage#init() - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - // WorkbenchHelp.setHelp(getControl(), - // IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE); - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - - GridLayout layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(layout); - - TabFolder folder = new TabFolder(composite, SWT.NONE); - folder.setLayout(new TabFolderLayout()); - folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - String[] insertNotInsert = new String[] { INSERT, DO_NOT_INSERT }; - - layout = new GridLayout(); - layout.numColumns = 2; - - Composite newlineComposite = new Composite(folder, SWT.NULL); - newlineComposite.setLayout(layout); - - String label = PHPUIMessages - .getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, - insertNotInsert); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, - insertNotInsert); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, - new String[] { CLEAR_ALL, PRESERVE_ONE }); - - // label= - // PHPUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); - // //$NON-NLS-1$ - // addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, - // insertNotInsert); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ - addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, - insertNotInsert); - - layout = new GridLayout(); - layout.numColumns = 2; - - Composite lineSplittingComposite = new Composite(folder, SWT.NULL); - lineSplittingComposite.setLayout(layout); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$ - addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT); - - layout = new GridLayout(); - layout.numColumns = 2; - - Composite styleComposite = new Composite(folder, SWT.NULL); - styleComposite.setLayout(layout); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, - new String[] { COMPACT, NORMAL }); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.style_compact_string_concatenation.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_STRING_CONCATENATION, - new String[] { COMPACT, NORMAL }); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.style_compact_arrays.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ARRAYS, - new String[] { COMPACT, NORMAL }); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ - addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, - SPACE }); - - label = PHPUIMessages - .getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ - fTabSizeTextBox = addTextField(styleComposite, label, PREF_TAB_SIZE); - - TabItem item = new TabItem(folder, SWT.NONE); - item.setText(PHPUIMessages - .getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ - item.setControl(newlineComposite); - - item = new TabItem(folder, SWT.NONE); - item - .setText(PHPUIMessages - .getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ - item.setControl(lineSplittingComposite); - - item = new TabItem(folder, SWT.NONE); - item.setText(PHPUIMessages - .getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ - item.setControl(styleComposite); - - // fSourceViewer= createPreview(parent); - - updatePreview(); - - return composite; - } - - // private SourceViewer createPreview(Composite parent) { - // SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | - // SWT.H_SCROLL | SWT.BORDER); - // JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); - // previewViewer.configure(new PHPSourceViewerConfiguration(tools, null)); - // previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); - // previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) - // fWorkingValues.get(PREF_TAB_SIZE), 0)); - // previewViewer.setEditable(false); - // previewViewer.setDocument(fPreviewDocument); - // Control control= previewViewer.getControl(); - // GridData gdata= new GridData(GridData.FILL_BOTH); - // gdata.widthHint= convertWidthInCharsToPixels(30); - // gdata.heightHint= convertHeightInCharsToPixels(5); - // control.setLayoutData(gdata); - // return previewViewer; - // } - - private Button addCheckBox(Composite parent, String label, String key, - String[] values) { - ControlData data = new ControlData(key, values); - - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan = 2; - - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - checkBox.setData(data); - checkBox.setLayoutData(gd); - - String currValue = (String) fWorkingValues.get(key); - checkBox.setSelection(data.getSelection(currValue) == 0); - checkBox.addSelectionListener(fButtonSelectionListener); - - fCheckBoxes.add(checkBox); - return checkBox; - } - - private Text addTextField(Composite parent, String label, String key) { - Label labelControl = new Label(parent, SWT.NONE); - labelControl.setText(label); - labelControl.setLayoutData(new GridData()); - - Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); - textBox.setData(key); - textBox.setLayoutData(new GridData()); - - String currValue = (String) fWorkingValues.get(key); - textBox.setText(String.valueOf(getPositiveIntValue(currValue, 1))); - textBox.setTextLimit(3); - textBox.addModifyListener(fTextModifyListener); - - GridData gd = new GridData(); - gd.widthHint = convertWidthInCharsToPixels(5); - textBox.setLayoutData(gd); - - fTextBoxes.add(textBox); - return textBox; - } - - private void controlChanged(Button button) { - ControlData data = (ControlData) button.getData(); - boolean selection = button.getSelection(); - String newValue = data.getValue(selection); - fWorkingValues.put(data.getKey(), newValue); - updatePreview(); - - if (PREF_TAB_CHAR.equals(data.getKey())) { - updateStatus(new StatusInfo()); - if (selection) { - fTabSizeTextBox.setText((String) fWorkingValues - .get(PREF_TAB_SIZE)); - } - } - } - - private void textChanged(Text textControl) { - String key = (String) textControl.getData(); - String number = textControl.getText(); - IStatus status = validatePositiveNumber(number); - if (!status.matches(IStatus.ERROR)) { - fWorkingValues.put(key, number); - } - // if (PREF_TAB_SIZE.equals(key)) { - // fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(number, - // 0)); - // } - updateStatus(status); - updatePreview(); - } - - /* - * @see IPreferencePage#performOk() - */ - public boolean performOk() { - String[] allKeys = getAllKeys(); - // preserve other options - // store in JCore - Hashtable actualOptions = JavaCore.getOptions(); - for (int i = 0; i < allKeys.length; i++) { - String key = allKeys[i]; - String val = (String) fWorkingValues.get(key); - actualOptions.put(key, val); - } - JavaCore.setOptions(actualOptions); - WebUI.getDefault().savePluginPreferences(); - return super.performOk(); - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fWorkingValues = JavaCore.getDefaultOptions(); - updateControls(); - super.performDefaults(); - } - - private String loadPreviewFile(String filename) { - String separator = System.getProperty("line.separator"); //$NON-NLS-1$ - StringBuffer btxt = new StringBuffer(512); - BufferedReader rin = null; - try { - rin = new BufferedReader(new InputStreamReader(getClass() - .getResourceAsStream(filename))); - String line; - while ((line = rin.readLine()) != null) { - btxt.append(line); - btxt.append(separator); - } - } catch (IOException io) { - WebUI.log(io); - } finally { - if (rin != null) { - try { - rin.close(); - } catch (IOException e) { - } - } - } - return btxt.toString(); - } - - private void updatePreview() { - ICodeFormatter formatter = ToolFactory - .createDefaultCodeFormatter(fWorkingValues); - fPreviewDocument.set(formatter.format(fPreviewText, 0, null, "\n")); //$NON-NLS-1$ - } - - private void updateControls() { - // update the UI - for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { - Button curr = (Button) fCheckBoxes.get(i); - ControlData data = (ControlData) curr.getData(); - - String currValue = (String) fWorkingValues.get(data.getKey()); - curr.setSelection(data.getSelection(currValue) == 0); - } - for (int i = fTextBoxes.size() - 1; i >= 0; i--) { - Text curr = (Text) fTextBoxes.get(i); - String key = (String) curr.getData(); - String currValue = (String) fWorkingValues.get(key); - curr.setText(currValue); - } - } - - private IStatus validatePositiveNumber(String number) { - StatusInfo status = new StatusInfo(); - if (number.length() == 0) { - status.setError(PHPUIMessages - .getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$ - } else { - try { - int value = Integer.parseInt(number); - if (value < 0) { - status - .setError(PHPUIMessages - .getFormattedString( - "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } - } catch (NumberFormatException e) { - status.setError(PHPUIMessages.getFormattedString( - "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } - } - return status; - } - - private void updateStatus(IStatus status) { - if (!status.matches(IStatus.ERROR)) { - // look if there are more severe errors - for (int i = 0; i < fTextBoxes.size(); i++) { - Text curr = (Text) fTextBoxes.get(i); - if (!(curr == fTabSizeTextBox && usesTabs())) { - IStatus currStatus = validatePositiveNumber(curr.getText()); - status = StatusUtil.getMoreSevere(currStatus, status); - } - } - } - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } - - private boolean usesTabs() { - return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR)); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java deleted file mode 100644 index 1625b05..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java +++ /dev/null @@ -1,587 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; -import net.sourceforge.phpdt.internal.ui.util.PixelConverter; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ITreeListAdapter; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.TreeListDialogField; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData; -import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter; -import org.eclipse.jface.text.templates.persistence.TemplateStore; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.Image; -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.FileDialog; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; - -/** - */ -public class CodeTemplateBlock { - - private class CodeTemplateAdapter implements ITreeListAdapter, - IDialogFieldListener { - - private final Object[] NO_CHILDREN = new Object[0]; - - public void customButtonPressed(TreeListDialogField field, int index) { - doButtonPressed(index, field.getSelectedElements()); - } - - public void selectionChanged(TreeListDialogField field) { - List selected = field.getSelectedElements(); - field.enableButton(IDX_EDIT, canEdit(selected)); - field.enableButton(IDX_EXPORT, !selected.isEmpty()); - - updateSourceViewerInput(selected); - } - - public void doubleClicked(TreeListDialogField field) { - List selected = field.getSelectedElements(); - if (canEdit(selected)) { - doButtonPressed(IDX_EDIT, selected); - } - } - - public Object[] getChildren(TreeListDialogField field, Object element) { - if (element == COMMENT_NODE || element == CODE_NODE) { - return getTemplateOfCategory(element == COMMENT_NODE); - } - return NO_CHILDREN; - } - - public Object getParent(TreeListDialogField field, Object element) { - if (element instanceof TemplatePersistenceData) { - TemplatePersistenceData data = (TemplatePersistenceData) element; - if (data.getTemplate().getName().endsWith( - CodeTemplateContextType.COMMENT_SUFFIX)) { - return COMMENT_NODE; - } - return CODE_NODE; - } - return null; - } - - public boolean hasChildren(TreeListDialogField field, Object element) { - return (element == COMMENT_NODE || element == CODE_NODE); - } - - public void dialogFieldChanged(DialogField field) { - } - - public void keyPressed(TreeListDialogField field, KeyEvent event) { - } - - } - - private static class CodeTemplateLabelProvider extends LabelProvider { - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - return null; - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element == COMMENT_NODE || element == CODE_NODE) { - return (String) element; - } - TemplatePersistenceData data = (TemplatePersistenceData) element; - Template template = data.getTemplate(); - String name = template.getName(); - if (CodeTemplateContextType.CATCHBLOCK.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.METHODSTUB.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.CONSTRUCTORSTUB.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.GETTERSTUB.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.SETTERSTUB.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.NEWTYPE.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.TYPECOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.FIELDCOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.fieldcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.METHODCOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.OVERRIDECOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.GETTERCOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ - } else if (CodeTemplateContextType.SETTERCOMMENT.equals(name)) { - return PreferencesMessages - .getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ - } - return template.getDescription(); - } - - } - - private final static int IDX_EDIT = 0; - - private final static int IDX_IMPORT = 2; - - private final static int IDX_EXPORT = 3; - - private final static int IDX_EXPORTALL = 4; - - protected final static Object COMMENT_NODE = PreferencesMessages - .getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ - - protected final static Object CODE_NODE = PreferencesMessages - .getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ - - private static final String PREF_JAVADOC_STUBS = PreferenceConstants.CODEGEN_ADD_COMMENTS; - - private TreeListDialogField fCodeTemplateTree; - - private SelectionButtonDialogField fCreateJavaDocComments; - - protected TemplateStore fTemplates; - - private PixelConverter fPixelConverter; - - private SourceViewer fPatternViewer; - - private Control fSWTWidget; - - private TemplateVariableProcessor fTemplateProcessor; - - public CodeTemplateBlock() { - - fTemplates = WebUI.getDefault().getCodeTemplateStore(); - fTemplateProcessor = new TemplateVariableProcessor(); - - CodeTemplateAdapter adapter = new CodeTemplateAdapter(); - - String[] buttonLabels = new String[] { - /* IDX_EDIT */PreferencesMessages - .getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ - /* */null, - /* IDX_IMPORT */PreferencesMessages - .getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ - /* IDX_EXPORT */PreferencesMessages - .getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ - /* IDX_EXPORTALL */PreferencesMessages - .getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ - - }; - fCodeTemplateTree = new TreeListDialogField(adapter, buttonLabels, - new CodeTemplateLabelProvider()); - fCodeTemplateTree.setDialogFieldListener(adapter); - fCodeTemplateTree.setLabelText(PreferencesMessages - .getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ - - fCodeTemplateTree.enableButton(IDX_EXPORT, false); - fCodeTemplateTree.enableButton(IDX_EDIT, false); - - fCodeTemplateTree.addElement(COMMENT_NODE); - fCodeTemplateTree.addElement(CODE_NODE); - - fCreateJavaDocComments = new SelectionButtonDialogField(SWT.CHECK - | SWT.WRAP); - fCreateJavaDocComments.setLabelText(PreferencesMessages - .getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ - fCreateJavaDocComments.setSelection(PreferenceConstants - .getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); - - fCodeTemplateTree.selectFirstElement(); - } - - protected Control createContents(Composite parent) { - fPixelConverter = new PixelConverter(parent); - fSWTWidget = parent; - - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - composite.setLayout(layout); - - fCodeTemplateTree.doFillIntoGrid(composite, 3); - LayoutUtil - .setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); - LayoutUtil - .setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); - - fPatternViewer = createViewer(composite, 2); - - fCreateJavaDocComments.doFillIntoGrid(composite, 2); - - DialogField label = new DialogField(); - label.setLabelText(PreferencesMessages - .getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ - label.doFillIntoGrid(composite, 2); - - return composite; - - } - - private Shell getShell() { - if (fSWTWidget != null) { - return fSWTWidget.getShell(); - } - return WebUI.getActiveWorkbenchShell(); - } - - private SourceViewer createViewer(Composite parent, int nColumns) { - Label label = new Label(parent, SWT.NONE); - label.setText(PreferencesMessages - .getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ - GridData data = new GridData(); - data.horizontalSpan = nColumns; - label.setLayoutData(data); - - IDocument document = new Document(); - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - IPreferenceStore store = WebUI.getDefault() - .getCombinedPreferenceStore(); - SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, - SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); - TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( - tools.getColorManager(), store, null, fTemplateProcessor); - viewer.configure(configuration); - viewer.setEditable(false); - viewer.setDocument(document); - - Font font = JFaceResources - .getFont(PreferenceConstants.EDITOR_TEXT_FONT); - viewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(viewer, configuration, store); - - Control control = viewer.getControl(); - data = new GridData(GridData.HORIZONTAL_ALIGN_FILL - | GridData.FILL_VERTICAL); - data.horizontalSpan = nColumns; - data.heightHint = fPixelConverter.convertHeightInCharsToPixels(5); - control.setLayoutData(data); - - return viewer; - } - - protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) { - ArrayList res = new ArrayList(); - TemplatePersistenceData[] templates = fTemplates.getTemplateData(false); - for (int i = 0; i < templates.length; i++) { - TemplatePersistenceData curr = templates[i]; - if (isComment == curr.getTemplate().getName().endsWith( - CodeTemplateContextType.COMMENT_SUFFIX)) { - res.add(curr); - } - } - return (TemplatePersistenceData[]) res - .toArray(new TemplatePersistenceData[res.size()]); - } - - protected static boolean canEdit(List selected) { - return selected.size() == 1 - && (selected.get(0) instanceof TemplatePersistenceData); - } - - protected void updateSourceViewerInput(List selection) { - if (fPatternViewer == null - || fPatternViewer.getTextWidget().isDisposed()) { - return; - } - if (selection.size() == 1 - && selection.get(0) instanceof TemplatePersistenceData) { - TemplatePersistenceData data = (TemplatePersistenceData) selection - .get(0); - Template template = data.getTemplate(); - TemplateContextType type = WebUI.getDefault() - .getCodeTemplateContextRegistry().getContextType( - template.getContextTypeId()); - fTemplateProcessor.setContextType(type); - fPatternViewer.getDocument().set(template.getPattern()); - } else { - fPatternViewer.getDocument().set(""); //$NON-NLS-1$ - } - } - - protected void doButtonPressed(int buttonIndex, List selected) { - if (buttonIndex == IDX_EDIT) { - edit((TemplatePersistenceData) selected.get(0)); - } else if (buttonIndex == IDX_EXPORT) { - export(selected); - } else if (buttonIndex == IDX_EXPORTALL) { - exportAll(); - } else if (buttonIndex == IDX_IMPORT) { - import_(); - } - } - - private void edit(TemplatePersistenceData data) { - Template newTemplate = new Template(data.getTemplate()); - EditTemplateDialog dialog = new EditTemplateDialog(getShell(), - newTemplate, true, false, WebUI.getDefault() - .getCodeTemplateContextRegistry()); - if (dialog.open() == Window.OK) { - // changed - data.setTemplate(newTemplate); - fCodeTemplateTree.refresh(data); - fCodeTemplateTree.selectElements(new StructuredSelection(data)); - } - } - - private void import_() { - FileDialog dialog = new FileDialog(getShell()); - dialog.setText(PreferencesMessages - .getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] { PreferencesMessages - .getString("CodeTemplateBlock.import.extension") }); //$NON-NLS-1$ - String path = dialog.open(); - - if (path == null) - return; - - try { - TemplateReaderWriter reader = new TemplateReaderWriter(); - File file = new File(path); - if (file.exists()) { - InputStream input = new BufferedInputStream( - new FileInputStream(file)); - TemplatePersistenceData[] datas = reader.read(input, null); - for (int i = 0; i < datas.length; i++) { - updateTemplate(datas[i]); - } - } - - fCodeTemplateTree.refresh(); - updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); - - } catch (FileNotFoundException e) { - openReadErrorDialog(e); - } catch (IOException e) { - openReadErrorDialog(e); - } - - } - - private void updateTemplate(TemplatePersistenceData data) { - TemplatePersistenceData[] datas = fTemplates.getTemplateData(true); - for (int i = 0; i < datas.length; i++) { - String id = datas[i].getId(); - if (id != null && id.equals(data.getId())) { - datas[i].setTemplate(data.getTemplate()); - break; - } - } - } - - private void exportAll() { - export(fTemplates.getTemplateData(false)); - } - - private void export(List selected) { - List datas = new ArrayList(); - for (int i = 0; i < selected.size(); i++) { - Object curr = selected.get(i); - if (curr instanceof TemplatePersistenceData) { - datas.add(curr); - } else { - TemplatePersistenceData[] cat = getTemplateOfCategory(curr == COMMENT_NODE); - datas.addAll(Arrays.asList(cat)); - } - } - export((TemplatePersistenceData[]) datas - .toArray(new TemplatePersistenceData[datas.size()])); - } - - private void export(TemplatePersistenceData[] templates) { - FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); - dialog - .setText(PreferencesMessages - .getFormattedString( - "CodeTemplateBlock.export.title", String.valueOf(templates.length))); //$NON-NLS-1$ - dialog.setFilterExtensions(new String[] { PreferencesMessages - .getString("CodeTemplateBlock.export.extension") }); //$NON-NLS-1$ - dialog.setFileName(PreferencesMessages - .getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ - String path = dialog.open(); - - if (path == null) - return; - - File file = new File(path); - - if (file.isHidden()) { - String title = PreferencesMessages - .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ - String message = PreferencesMessages - .getFormattedString( - "CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - return; - } - - if (file.exists() && !file.canWrite()) { - String title = PreferencesMessages - .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ - String message = PreferencesMessages - .getFormattedString( - "CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - return; - } - - if (!file.exists() || confirmOverwrite(file)) { - try { - OutputStream output = new BufferedOutputStream( - new FileOutputStream(file)); - TemplateReaderWriter writer = new TemplateReaderWriter(); - writer.save(templates, output); - } catch (IOException e) { - openWriteErrorDialog(e); - } - } - - } - - private boolean confirmOverwrite(File file) { - return MessageDialog - .openQuestion( - getShell(), - PreferencesMessages - .getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ - PreferencesMessages - .getFormattedString( - "CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ - } - - public void performDefaults() { - IPreferenceStore prefs = WebUI.getDefault() - .getPreferenceStore(); - fCreateJavaDocComments.setSelection(prefs - .getDefaultBoolean(PREF_JAVADOC_STUBS)); - - fTemplates.restoreDefaults(); - - // refresh - fCodeTemplateTree.refresh(); - updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); - } - - public boolean performOk(boolean enabled) { - IPreferenceStore prefs = PreferenceConstants.getPreferenceStore(); - prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); - WebUI.getDefault().savePluginPreferences(); - - try { - fTemplates.save(); - } catch (IOException e) { - WebUI.log(e); - openWriteErrorDialog(e); - } - return true; - } - - public void performCancel() { - try { - fTemplates.load(); - } catch (IOException e) { - openReadErrorDialog(e); - } - } - - private void openReadErrorDialog(Exception e) { - String title = PreferencesMessages - .getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ - - String message = e.getLocalizedMessage(); - if (message != null) - message = PreferencesMessages.getFormattedString( - "CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ - else - message = PreferencesMessages - .getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } - - private void openWriteErrorDialog(Exception e) { - String title = PreferencesMessages - .getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ - String message = PreferencesMessages - .getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java deleted file mode 100644 index baab7d9..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/* - * The page to configure the code formatter options. - */ -public class CodeTemplatePreferencePage extends PreferencePage implements - IWorkbenchPreferencePage, IStatusChangeListener { - - private CodeTemplateBlock fCodeTemplateConfigurationBlock; - - public CodeTemplatePreferencePage() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - // setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); - // //$NON-NLS-1$ - - // only used when page is shown programatically - setTitle(PreferencesMessages - .getString("CodeTemplatesPreferencePage.title")); //$NON-NLS-1$ - - fCodeTemplateConfigurationBlock = new CodeTemplateBlock(); - } - - /* - * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE); - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - Control composite = fCodeTemplateConfigurationBlock - .createContents(parent); - Dialog.applyDialogFont(composite); - return composite; - } - - /* - * @see IPreferencePage#performOk() - */ - public boolean performOk() { - if (!fCodeTemplateConfigurationBlock.performOk(true)) { - return false; - } - return super.performOk(); - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fCodeTemplateConfigurationBlock.performDefaults(); - super.performDefaults(); - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) - */ - public void statusChanged(IStatus status) { - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.IPreferencePage#performCancel() - */ - public boolean performCancel() { - fCodeTemplateConfigurationBlock.performCancel(); - - return super.performCancel(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java deleted file mode 100644 index 5137ae2..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/* - * The page to configure the compiler options. - */ -public class CompilerPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage, IStatusChangeListener { - - private CompilerConfigurationBlock fConfigurationBlock; - - public CompilerPreferencePage() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - setDescription(PreferencesMessages - .getString("CompilerPreferencePage.description")); //$NON-NLS-1$ - - // only used when page is shown programatically - setTitle(PreferencesMessages.getString("CompilerPreferencePage.title")); //$NON-NLS-1$ - - fConfigurationBlock = new CompilerConfigurationBlock(this, null); - } - - /* - * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - Control result = fConfigurationBlock.createContents(parent); - Dialog.applyDialogFont(result); - return result; - } - - /* - * @see IPreferencePage#performOk() - */ - public boolean performOk() { - if (!fConfigurationBlock.performOk(true)) { - return false; - } - return super.performOk(); - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fConfigurationBlock.performDefaults(); - super.performDefaults(); - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) - */ - public void statusChanged(IStatus status) { - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java deleted file mode 100644 index e0b3d24..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java +++ /dev/null @@ -1,638 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusDialog; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; -import net.sourceforge.phpdt.internal.ui.util.SWTUtil; -import net.sourceforge.phpdt.ui.IContextMenuConstants; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextListener; -import org.eclipse.jface.text.ITextOperationTarget; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.TextEvent; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.text.templates.ContextTypeRegistry; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -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.events.VerifyEvent; -import org.eclipse.swt.graphics.Font; -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.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.Widget; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.IUpdate; - -/** - * Dialog to edit a template. - */ -public class EditTemplateDialog extends StatusDialog { - - private static class TextViewerAction extends Action implements IUpdate { - - private int fOperationCode = -1; - - private ITextOperationTarget fOperationTarget; - - /** - * Creates a new action. - * - * @param viewer - * the viewer - * @param operationCode - * the opcode - */ - public TextViewerAction(ITextViewer viewer, int operationCode) { - fOperationCode = operationCode; - fOperationTarget = viewer.getTextOperationTarget(); - update(); - } - - /** - * Updates the enabled state of the action. Fires a property change if - * the enabled state changes. - * - * @see Action#firePropertyChange(String, Object, Object) - */ - public void update() { - - boolean wasEnabled = isEnabled(); - boolean isEnabled = (fOperationTarget != null && fOperationTarget - .canDoOperation(fOperationCode)); - setEnabled(isEnabled); - - if (wasEnabled != isEnabled) { - firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE - : Boolean.FALSE, isEnabled ? Boolean.TRUE - : Boolean.FALSE); - } - } - - /** - * @see Action#run() - */ - public void run() { - if (fOperationCode != -1 && fOperationTarget != null) { - fOperationTarget.doOperation(fOperationCode); - } - } - } - - private final Template fTemplate; - - private Text fNameText; - - private Text fDescriptionText; - - private Combo fContextCombo; - - private SourceViewer fPatternEditor; - - private Button fInsertVariableButton; - - private boolean fIsNameModifiable; - - private StatusInfo fValidationStatus; - - private boolean fSuppressError = true; // #4354 - - private Map fGlobalActions = new HashMap(10); - - private List fSelectionActions = new ArrayList(3); - - private String[][] fContextTypes; - - private ContextTypeRegistry fContextTypeRegistry; - - private final TemplateVariableProcessor fTemplateProcessor = new TemplateVariableProcessor(); - - /** - * Creates a new dialog. - * - * @param parent - * the shell parent of the dialog - * @param template - * the template to edit - * @param edit - * whether this is a new template or an existing being edited - * @param isNameModifiable - * whether the name of the template may be modified - * @param registry - * the context type registry to use - */ - public EditTemplateDialog(Shell parent, Template template, boolean edit, - boolean isNameModifiable, ContextTypeRegistry registry) { - super(parent); - - setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); - - String title = edit ? PreferencesMessages - .getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ - : PreferencesMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ - setTitle(title); - - fTemplate = template; - fIsNameModifiable = isNameModifiable; - - // XXX workaround for bug 63313 - disabling prefix until fixed. - // String delim= new Document().getLegalLineDelimiters()[0]; - - List contexts = new ArrayList(); - for (Iterator it = registry.contextTypes(); it.hasNext();) { - TemplateContextType type = (TemplateContextType) it.next(); - // if (type.getId().equals("javadoc")) //$NON-NLS-1$ - // contexts.add(new String[] { type.getId(), type.getName(), "/**" + - // delim }); //$NON-NLS-1$ - // else - contexts.add(new String[] { type.getId(), type.getName(), "" }); //$NON-NLS-1$ - } - fContextTypes = (String[][]) contexts.toArray(new String[contexts - .size()][]); - - fValidationStatus = new StatusInfo(); - - fContextTypeRegistry = registry; - - TemplateContextType type = fContextTypeRegistry.getContextType(template - .getContextTypeId()); - fTemplateProcessor.setContextType(type); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.dialogs.StatusDialog#create() - */ - public void create() { - super.create(); - // update initial ok button to be disabled for new templates - boolean valid = fNameText == null - || fNameText.getText().trim().length() != 0; - if (!valid) { - StatusInfo status = new StatusInfo(); - status.setError(PreferencesMessages - .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ - updateButtonsEnableState(status); - } - } - - /* - * @see Dialog#createDialogArea(Composite) - */ - protected Control createDialogArea(Composite ancestor) { - Composite parent = new Composite(ancestor, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - parent.setLayout(layout); - parent.setLayoutData(new GridData(GridData.FILL_BOTH)); - - ModifyListener listener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - doTextWidgetChanged(e.widget); - } - }; - - if (fIsNameModifiable) { - createLabel(parent, PreferencesMessages - .getString("EditTemplateDialog.name")); //$NON-NLS-1$ - - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - layout = new GridLayout(); - layout.numColumns = 3; - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - fNameText = createText(composite); - fNameText.addFocusListener(new FocusListener() { - - public void focusGained(FocusEvent e) { - } - - public void focusLost(FocusEvent e) { - if (fSuppressError) { - fSuppressError = false; - updateButtons(); - } - } - }); - - createLabel(composite, PreferencesMessages - .getString("EditTemplateDialog.context")); //$NON-NLS-1$ - fContextCombo = new Combo(composite, SWT.READ_ONLY); - - for (int i = 0; i < fContextTypes.length; i++) { - fContextCombo.add(fContextTypes[i][1]); - } - - fContextCombo.addModifyListener(listener); - } - - createLabel(parent, PreferencesMessages - .getString("EditTemplateDialog.description")); //$NON-NLS-1$ - - int descFlags = fIsNameModifiable ? SWT.BORDER : SWT.BORDER - | SWT.READ_ONLY; - fDescriptionText = new Text(parent, descFlags); - fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - fDescriptionText.addModifyListener(listener); - - Label patternLabel = createLabel(parent, PreferencesMessages - .getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ - patternLabel.setLayoutData(new GridData( - GridData.VERTICAL_ALIGN_BEGINNING)); - fPatternEditor = createEditor(parent); - - Label filler = new Label(parent, SWT.NONE); - filler.setLayoutData(new GridData()); - - Composite composite = new Composite(parent, SWT.NONE); - layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - composite.setLayoutData(new GridData()); - - fInsertVariableButton = new Button(composite, SWT.NONE); - fInsertVariableButton - .setLayoutData(getButtonGridData(fInsertVariableButton)); - fInsertVariableButton.setText(PreferencesMessages - .getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ - fInsertVariableButton.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - fPatternEditor.getTextWidget().setFocus(); - fPatternEditor - .doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - - fDescriptionText.setText(fTemplate.getDescription()); - if (fIsNameModifiable) { - fNameText.setText(fTemplate.getName()); - fNameText.addModifyListener(listener); - fContextCombo.select(getIndex(fTemplate.getContextTypeId())); - } else { - fPatternEditor.getControl().setFocus(); - } - initializeActions(); - - applyDialogFont(parent); - return composite; - } - - protected void doTextWidgetChanged(Widget w) { - if (w == fNameText) { - fSuppressError = false; - String name = fNameText.getText(); - fTemplate.setName(name); - updateButtons(); - } else if (w == fContextCombo) { - String name = fContextCombo.getText(); - String contextId = getContextId(name); - fTemplate.setContextTypeId(contextId); - fTemplateProcessor.setContextType(fContextTypeRegistry - .getContextType(contextId)); - } else if (w == fDescriptionText) { - String desc = fDescriptionText.getText(); - fTemplate.setDescription(desc); - } - } - - private String getContextId(String name) { - if (name == null) - return name; - - for (int i = 0; i < fContextTypes.length; i++) { - if (name.equals(fContextTypes[i][1])) { - return fContextTypes[i][0]; - } - } - return name; - } - - protected void doSourceChanged(IDocument document) { - String text = document.get(); - String prefix = getPrefix(); - fTemplate.setPattern(text.substring(prefix.length(), text.length())); - fValidationStatus.setOK(); - TemplateContextType contextType = fContextTypeRegistry - .getContextType(fTemplate.getContextTypeId()); - if (contextType != null) { - try { - contextType.validate(text); - } catch (TemplateException e) { - fValidationStatus.setError(e.getLocalizedMessage()); - } - } - - updateUndoAction(); - updateButtons(); - } - - private static GridData getButtonGridData(Button button) { - GridData data = new GridData(GridData.FILL_HORIZONTAL); - data.heightHint = SWTUtil.getButtonHeightHint(button); - - return data; - } - - private static Label createLabel(Composite parent, String name) { - Label label = new Label(parent, SWT.NULL); - label.setText(name); - label.setLayoutData(new GridData()); - - return label; - } - - private static Text createText(Composite parent) { - Text text = new Text(parent, SWT.BORDER); - text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - return text; - } - - private SourceViewer createEditor(Composite parent) { - String prefix = getPrefix(); - IDocument document = new Document(prefix + fTemplate.getPattern()); - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - IPreferenceStore store = WebUI.getDefault() - .getCombinedPreferenceStore(); - SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, - SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); - TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( - tools.getColorManager(), store, null, fTemplateProcessor); - viewer.configure(configuration); - viewer.setEditable(true); - // XXX workaround for bug 63313 - disabling prefix until fixed. - // viewer.setDocument(document, prefix.length(), document.getLength() - - // prefix.length()); - viewer.setDocument(document); - - Font font = JFaceResources - .getFont(PreferenceConstants.EDITOR_TEXT_FONT); - viewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(viewer, configuration, store); - - int nLines = document.getNumberOfLines(); - if (nLines < 5) { - nLines = 5; - } else if (nLines > 12) { - nLines = 12; - } - - Control control = viewer.getControl(); - GridData data = new GridData(GridData.FILL_BOTH); - data.widthHint = convertWidthInCharsToPixels(80); - data.heightHint = convertHeightInCharsToPixels(nLines); - control.setLayoutData(data); - - viewer.addTextListener(new ITextListener() { - public void textChanged(TextEvent event) { - if (event.getDocumentEvent() != null) - doSourceChanged(event.getDocumentEvent().getDocument()); - } - }); - - viewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - updateSelectionDependentActions(); - } - }); - - viewer.prependVerifyKeyListener(new VerifyKeyListener() { - public void verifyKey(VerifyEvent event) { - handleVerifyKeyPressed(event); - } - }); - - return viewer; - } - - private String getPrefix() { - String prefix; - int idx = getIndex(fTemplate.getContextTypeId()); - if (idx != -1) - prefix = fContextTypes[idx][2]; - else - prefix = ""; //$NON-NLS-1$ - - return prefix; - } - - private void handleVerifyKeyPressed(VerifyEvent event) { - if (!event.doit) - return; - - if (event.stateMask != SWT.MOD1) - return; - - switch (event.character) { - case ' ': - fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); - event.doit = false; - break; - - // CTRL-Z - case 'z' - 'a' + 1: - fPatternEditor.doOperation(ITextOperationTarget.UNDO); - event.doit = false; - break; - } - } - - private void initializeActions() { - TextViewerAction action = new TextViewerAction(fPatternEditor, - SourceViewer.UNDO); - action - .setText(PreferencesMessages - .getString("EditTemplateDialog.undo")); //$NON-NLS-1$ - fGlobalActions.put(ITextEditorActionConstants.UNDO, action); - - action = new TextViewerAction(fPatternEditor, SourceViewer.CUT); - action.setText(PreferencesMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ - fGlobalActions.put(ITextEditorActionConstants.CUT, action); - - action = new TextViewerAction(fPatternEditor, SourceViewer.COPY); - action - .setText(PreferencesMessages - .getString("EditTemplateDialog.copy")); //$NON-NLS-1$ - fGlobalActions.put(ITextEditorActionConstants.COPY, action); - - action = new TextViewerAction(fPatternEditor, SourceViewer.PASTE); - action.setText(PreferencesMessages - .getString("EditTemplateDialog.paste")); //$NON-NLS-1$ - fGlobalActions.put(ITextEditorActionConstants.PASTE, action); - - action = new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); - action.setText(PreferencesMessages - .getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ - fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); - - action = new TextViewerAction(fPatternEditor, - SourceViewer.CONTENTASSIST_PROPOSALS); - action.setText(PreferencesMessages - .getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ - fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ - - fSelectionActions.add(ITextEditorActionConstants.CUT); - fSelectionActions.add(ITextEditorActionConstants.COPY); - fSelectionActions.add(ITextEditorActionConstants.PASTE); - - // create context menu - MenuManager manager = new MenuManager(null, null); - manager.setRemoveAllWhenShown(true); - manager.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager mgr) { - fillContextMenu(mgr); - } - }); - - StyledText text = fPatternEditor.getTextWidget(); - Menu menu = manager.createContextMenu(text); - text.setMenu(menu); - } - - private void fillContextMenu(IMenuManager menu) { - menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, - (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); - - menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, - (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, - (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, - (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, - (IAction) fGlobalActions - .get(ITextEditorActionConstants.SELECT_ALL)); - - menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); - menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, - (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ - } - - protected void updateSelectionDependentActions() { - Iterator iterator = fSelectionActions.iterator(); - while (iterator.hasNext()) - updateAction((String) iterator.next()); - } - - protected void updateUndoAction() { - IAction action = (IAction) fGlobalActions - .get(ITextEditorActionConstants.UNDO); - if (action instanceof IUpdate) - ((IUpdate) action).update(); - } - - protected void updateAction(String actionId) { - IAction action = (IAction) fGlobalActions.get(actionId); - if (action instanceof IUpdate) - ((IUpdate) action).update(); - } - - private int getIndex(String contextid) { - - if (contextid == null) - return -1; - - for (int i = 0; i < fContextTypes.length; i++) { - if (contextid.equals(fContextTypes[i][0])) { - return i; - } - } - return -1; - } - - protected void okPressed() { - super.okPressed(); - } - - private void updateButtons() { - StatusInfo status; - - boolean valid = fNameText == null - || fNameText.getText().trim().length() != 0; - if (!valid) { - status = new StatusInfo(); - if (!fSuppressError) { - status.setError(PreferencesMessages - .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ - } - } else { - status = fValidationStatus; - } - updateStatus(status); - } - - /* - * @see org.eclipse.jface.window.Window#configureShell(Shell) - */ - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, - IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java deleted file mode 100644 index 5890cd0..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/** - * Preference page for spell checking preferences. - * - * @since 3.0 - */ -public class EditorPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage, IStatusChangeListener { - - /** The spelling configuration block */ - private final EditorConfigurationBlock fBlock = new EditorConfigurationBlock( - this, null); - - /** - * Creates a new spelling preference page. - */ - public EditorPreferencePage() { - - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - setDescription(PreferencesMessages - .getString("EditorPreferencePage.description")); //$NON-NLS-1$ - setTitle(PreferencesMessages.getString("EditorPreferencePage.title")); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) - */ - protected Control createContents(final Composite parent) { - - final Control control = fBlock.createContents(parent); - Dialog.applyDialogFont(control); - - return control; - } - - /* - * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(final Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - /* - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(final IWorkbench workbench) { - // Do nothing - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - protected void performDefaults() { - fBlock.performDefaults(); - - super.performDefaults(); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - - if (!fBlock.performOk(true)) - return false; - - return super.performOk(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) - */ - public void statusChanged(final IStatus status) { - setValid(!status.matches(IStatus.ERROR)); - - StatusUtil.applyToStatusLine(this, status); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java deleted file mode 100644 index 1085be6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderDescriptor; -import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry; -import net.sourceforge.phpdt.internal.ui.util.PixelConverter; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.viewers.ComboViewer; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StackLayout; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FillLayout; -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.Control; -import org.eclipse.swt.widgets.Label; - -/** - * Configures Java Editor folding preferences. - * - * @since 3.0 - */ -class FoldingConfigurationBlock { - - private static class ErrorPreferences implements - IJavaFoldingPreferenceBlock { - private String fMessage; - - protected ErrorPreferences(String message) { - fMessage = message; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) - */ - public Control createControl(Composite composite) { - Composite inner = new Composite(composite, SWT.NONE); - inner.setLayout(new FillLayout(SWT.VERTICAL)); - - Label label = new Label(inner, SWT.CENTER); - label.setText(fMessage); - - return inner; - } - - public void initialize() { - } - - public void performOk() { - } - - public void performDefaults() { - } - - public void dispose() { - } - - } - - /** The overlay preference store. */ - private final OverlayPreferenceStore fStore; - - /* The controls */ - private Combo fProviderCombo; - - private Button fFoldingCheckbox; - - private ComboViewer fProviderViewer; - - private Map fProviderDescriptors; - - private Composite fGroup; - - private Map fProviderPreferences; - - private Map fProviderControls; - - private StackLayout fStackLayout; - - public FoldingConfigurationBlock(OverlayPreferenceStore store) { - Assert.isNotNull(store); - fStore = store; - fStore.addKeys(createOverlayStoreKeys()); - fProviderDescriptors = createListModel(); - fProviderPreferences = new HashMap(); - fProviderControls = new HashMap(); - } - - private Map createListModel() { - JavaFoldingStructureProviderRegistry reg = WebUI - .getDefault().getFoldingStructureProviderRegistry(); - reg.reloadExtensions(); - JavaFoldingStructureProviderDescriptor[] descs = reg - .getFoldingProviderDescriptors(); - Map map = new HashMap(); - for (int i = 0; i < descs.length; i++) { - map.put(descs[i].getId(), descs[i]); - } - return map; - } - - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - - ArrayList overlayKeys = new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_ENABLED)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_FOLDING_PROVIDER)); - - OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys - .size()]; - overlayKeys.toArray(keys); - return keys; - } - - /** - * Creates page for folding preferences. - * - * @param parent - * the parent composite - * @return the control for the preference page - */ - Control createControl(Composite parent) { - - Composite composite = new Composite(parent, SWT.NULL); - // assume parent page uses griddata - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_CENTER - | GridData.VERTICAL_ALIGN_FILL); - composite.setLayoutData(gd); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - PixelConverter pc = new PixelConverter(composite); - layout.verticalSpacing = pc.convertHeightInCharsToPixels(1) / 2; - composite.setLayout(layout); - - /* check box for new editors */ - fFoldingCheckbox = new Button(composite, SWT.CHECK); - fFoldingCheckbox.setText(PreferencesMessages - .getString("FoldingConfigurationBlock.enable")); //$NON-NLS-1$ - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING - | GridData.VERTICAL_ALIGN_BEGINNING); - fFoldingCheckbox.setLayoutData(gd); - fFoldingCheckbox.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean enabled = fFoldingCheckbox.getSelection(); - fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, - enabled); - updateCheckboxDependencies(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - - Label label = new Label(composite, SWT.CENTER); - gd = new GridData(GridData.FILL_HORIZONTAL - | GridData.VERTICAL_ALIGN_BEGINNING); - label.setLayoutData(gd); - - /* list */ - Composite comboComp = new Composite(composite, SWT.NONE); - gd = new GridData(GridData.FILL_HORIZONTAL - | GridData.VERTICAL_ALIGN_BEGINNING); - GridLayout gridLayout = new GridLayout(2, false); - gridLayout.marginWidth = 0; - comboComp.setLayout(gridLayout); - - Label comboLabel = new Label(comboComp, SWT.CENTER); - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING - | GridData.VERTICAL_ALIGN_CENTER); - comboLabel.setLayoutData(gd); - comboLabel.setText(PreferencesMessages - .getString("FoldingConfigurationBlock.combo_caption")); //$NON-NLS-1$ - - label = new Label(composite, SWT.CENTER); - gd = new GridData(GridData.FILL_HORIZONTAL - | GridData.VERTICAL_ALIGN_BEGINNING); - label.setLayoutData(gd); - - fProviderCombo = new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN); - gd = new GridData(GridData.HORIZONTAL_ALIGN_END - | GridData.VERTICAL_ALIGN_CENTER); - fProviderCombo.setLayoutData(gd); - - /* list viewer */ - fProviderViewer = new ComboViewer(fProviderCombo); - fProviderViewer.setContentProvider(new IStructuredContentProvider() { - - /* - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - public void dispose() { - } - - /* - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, - * java.lang.Object, java.lang.Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, - Object newInput) { - } - - /* - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - return fProviderDescriptors.values().toArray(); - } - }); - fProviderViewer.setLabelProvider(new LabelProvider() { - /* - * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - return null; - } - - /* - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - return ((JavaFoldingStructureProviderDescriptor) element) - .getName(); - } - }); - fProviderViewer - .addSelectionChangedListener(new ISelectionChangedListener() { - - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection sel = (IStructuredSelection) event - .getSelection(); - if (!sel.isEmpty()) { - fStore - .setValue( - PreferenceConstants.EDITOR_FOLDING_PROVIDER, - ((JavaFoldingStructureProviderDescriptor) sel - .getFirstElement()).getId()); - updateListDependencies(); - } - } - }); - fProviderViewer.setInput(fProviderDescriptors); - fProviderViewer.refresh(); - - Composite groupComp = new Composite(composite, SWT.NONE); - gd = new GridData(GridData.FILL_BOTH); - gd.horizontalSpan = 2; - groupComp.setLayoutData(gd); - gridLayout = new GridLayout(1, false); - gridLayout.marginWidth = 0; - groupComp.setLayout(gridLayout); - - /* contributed provider preferences. */ - fGroup = new Composite(groupComp, SWT.NONE); - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING - | GridData.VERTICAL_ALIGN_BEGINNING); - fGroup.setLayoutData(gd); - fStackLayout = new StackLayout(); - fGroup.setLayout(fStackLayout); - - return composite; - } - - private void updateCheckboxDependencies() { - } - - void updateListDependencies() { - String id = fStore - .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - JavaFoldingStructureProviderDescriptor desc = (JavaFoldingStructureProviderDescriptor) fProviderDescriptors - .get(id); - IJavaFoldingPreferenceBlock prefs; - - if (desc == null) { - // safety in case there is no such descriptor - String message = PreferencesMessages - .getString("FoldingConfigurationBlock.error.not_exist"); //$NON-NLS-1$ - WebUI.log(new Status(IStatus.WARNING, WebUI - .getPluginId(), IStatus.OK, message, null)); - prefs = new ErrorPreferences(message); - } else { - prefs = (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id); - if (prefs == null) { - try { - prefs = desc.createPreferences(); - fProviderPreferences.put(id, prefs); - } catch (CoreException e) { - WebUI.log(e); - prefs = new ErrorPreferences(e.getLocalizedMessage()); - } - } - } - - Control control = (Control) fProviderControls.get(id); - if (control == null) { - control = prefs.createControl(fGroup); - if (control == null) { - String message = PreferencesMessages - .getString("FoldingConfigurationBlock.info.no_preferences"); //$NON-NLS-1$ - control = new ErrorPreferences(message).createControl(fGroup); - } else { - fProviderControls.put(id, control); - } - } - fStackLayout.topControl = control; - control.pack(); - fGroup.layout(); - fGroup.getParent().layout(); - - prefs.initialize(); - } - - void initialize() { - restoreFromPreferences(); - } - - void performOk() { - for (Iterator it = fProviderPreferences.values().iterator(); it - .hasNext();) { - IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it - .next(); - prefs.performOk(); - } - } - - void performDefaults() { - restoreFromPreferences(); - for (Iterator it = fProviderPreferences.values().iterator(); it - .hasNext();) { - IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it - .next(); - prefs.performDefaults(); - } - } - - void dispose() { - for (Iterator it = fProviderPreferences.values().iterator(); it - .hasNext();) { - IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it - .next(); - prefs.dispose(); - } - } - - private void restoreFromPreferences() { - boolean enabled = fStore - .getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); - fFoldingCheckbox.setSelection(enabled); - updateCheckboxDependencies(); - - String id = fStore - .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - Object provider = fProviderDescriptors.get(id); - if (provider != null) { - fProviderViewer.setSelection(new StructuredSelection(provider), - true); - updateListDependencies(); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java deleted file mode 100644 index 5422511..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java +++ /dev/null @@ -1,482 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.HashMap; -import java.util.StringTokenizer; - -import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; -import net.sourceforge.phpdt.internal.ui.util.PixelConverter; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -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.graphics.Point; -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.List; -import org.eclipse.swt.widgets.Text; - -/** - * Configures Java Editor hover preferences. - * - * @since 2.1 - */ -class JavaEditorHoverConfigurationBlock { - - private static final String DELIMITER = PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.delimiter"); //$NON-NLS-1$ - - // Data structure to hold the values which are edited by the user - private static class HoverConfig { - - private String fModifierString; - - private boolean fIsEnabled; - - private int fStateMask; - - private HoverConfig(String modifier, int stateMask, boolean enabled) { - fModifierString = modifier; - fIsEnabled = enabled; - fStateMask = stateMask; - } - } - - private IPreferenceStore fStore; - - private HoverConfig[] fHoverConfigs; - - private Text fModifierEditor; - - private Button fEnableField; - - private List fHoverList; - - private Text fDescription; - - private Button fShowHoverAffordanceCheckbox; - - private JavaEditorPreferencePage fMainPreferencePage; - - private StatusInfo fStatus; - - public JavaEditorHoverConfigurationBlock( - JavaEditorPreferencePage mainPreferencePage, IPreferenceStore store) { - Assert.isNotNull(mainPreferencePage); - Assert.isNotNull(store); - fMainPreferencePage = mainPreferencePage; - fStore = store; - } - - /** - * Creates page for hover preferences. - */ - public Control createControl(Composite parent) { - - PixelConverter pixelConverter = new PixelConverter(parent); - - Composite hoverComposite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - hoverComposite.setLayout(layout); - GridData gd = new GridData(GridData.GRAB_HORIZONTAL - | GridData.VERTICAL_ALIGN_FILL); - hoverComposite.setLayoutData(gd); - - Label label = new Label(hoverComposite, SWT.NONE); - label - .setText(PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.hoverPreferences")); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - gd.horizontalSpan = 2; - label.setLayoutData(gd); - gd = new GridData(GridData.GRAB_HORIZONTAL - | GridData.VERTICAL_ALIGN_FILL); - - // Hover list - fHoverList = new List(hoverComposite, SWT.SINGLE | SWT.V_SCROLL - | SWT.BORDER); - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING - | GridData.FILL_HORIZONTAL); - int listHeight = 10 * fHoverList.getItemHeight(); - gd.heightHint = listHeight; - fHoverList.setLayoutData(gd); - fHoverList.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - handleHoverListSelection(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - - Composite stylesComposite = new Composite(hoverComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.heightHint = listHeight + (2 * fHoverList.getBorderWidth()); - stylesComposite.setLayoutData(gd); - - // Enabled checkbox - fEnableField = new Button(stylesComposite, SWT.CHECK); - fEnableField.setText(PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.enabled")); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - gd.horizontalSpan = 2; - fEnableField.setLayoutData(gd); - fEnableField.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - int i = fHoverList.getSelectionIndex(); - boolean state = fEnableField.getSelection(); - fModifierEditor.setEnabled(state); - fHoverConfigs[i].fIsEnabled = state; - handleModifierModified(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - - // Text field for modifier string - label = new Label(stylesComposite, SWT.LEFT); - label.setText(PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.keyModifier")); //$NON-NLS-1$ - fModifierEditor = new Text(stylesComposite, SWT.BORDER); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - fModifierEditor.setLayoutData(gd); - - fModifierEditor.addKeyListener(new KeyListener() { - private boolean isModifierCandidate; - - public void keyPressed(KeyEvent e) { - isModifierCandidate = e.keyCode > 0 && e.character == 0 - && e.stateMask == 0; - } - - public void keyReleased(KeyEvent e) { - if (isModifierCandidate && e.stateMask > 0 - && e.stateMask == e.stateMask && e.character == 0) {// && - // e.time - // -time - // < - // 1000) - // { - String text = fModifierEditor.getText(); - Point selection = fModifierEditor.getSelection(); - int i = selection.x - 1; - while (i > -1 && Character.isWhitespace(text.charAt(i))) { - i--; - } - boolean needsPrefixDelimiter = i > -1 - && !String.valueOf(text.charAt(i)) - .equals(DELIMITER); - - i = selection.y; - while (i < text.length() - && Character.isWhitespace(text.charAt(i))) { - i++; - } - boolean needsPostfixDelimiter = i < text.length() - && !String.valueOf(text.charAt(i)) - .equals(DELIMITER); - - String insertString; - - if (needsPrefixDelimiter && needsPostfixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPrefixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifier", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPostfixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.insertModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ - else - insertString = Action.findModifierString(e.stateMask); - - if (insertString != null) - fModifierEditor.insert(insertString); - } - } - }); - - fModifierEditor.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - handleModifierModified(); - } - }); - - // Description - Label descriptionLabel = new Label(stylesComposite, SWT.LEFT); - descriptionLabel.setText(PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.description")); //$NON-NLS-1$ - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING); - gd.horizontalSpan = 2; - descriptionLabel.setLayoutData(gd); - fDescription = new Text(stylesComposite, SWT.LEFT | SWT.WRAP - | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); - gd = new GridData(GridData.FILL_BOTH); - gd.horizontalSpan = 2; - fDescription.setLayoutData(gd); - - // Vertical filler - Label filler = new Label(hoverComposite, SWT.LEFT); - gd = new GridData(GridData.BEGINNING | GridData.VERTICAL_ALIGN_FILL); - gd.heightHint = pixelConverter.convertHeightInCharsToPixels(1) / 3; - filler.setLayoutData(gd); - - // Affordance checkbox - fShowHoverAffordanceCheckbox = new Button(hoverComposite, SWT.CHECK); - fShowHoverAffordanceCheckbox.setText(PreferencesMessages - .getString("JavaEditorHoverConfigurationBlock.showAffordance")); //$NON-NLS-1$ - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = 0; - gd.horizontalSpan = 2; - fShowHoverAffordanceCheckbox.setLayoutData(gd); - - initialize(); - - Dialog.applyDialogFont(hoverComposite); - return hoverComposite; - } - - private JavaEditorTextHoverDescriptor[] getContributedHovers() { - return WebUI.getDefault() - .getJavaEditorTextHoverDescriptors(); - } - - void initialize() { - JavaEditorTextHoverDescriptor[] hoverDescs = getContributedHovers(); - fHoverConfigs = new HoverConfig[hoverDescs.length]; - for (int i = 0; i < hoverDescs.length; i++) { - fHoverConfigs[i] = new HoverConfig(hoverDescs[i] - .getModifierString(), hoverDescs[i].getStateMask(), - hoverDescs[i].isEnabled()); - fHoverList.add(hoverDescs[i].getLabel()); - } - initializeFields(); - } - - void initializeFields() { - fHoverList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fHoverList != null && !fHoverList.isDisposed()) { - fHoverList.select(0); - handleHoverListSelection(); - } - } - }); - fShowHoverAffordanceCheckbox - .setSelection(fStore - .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); - } - - void performOk() { - StringBuffer buf = new StringBuffer(); - StringBuffer maskBuf = new StringBuffer(); - for (int i = 0; i < fHoverConfigs.length; i++) { - buf.append(getContributedHovers()[i].getId()); - buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - if (!fHoverConfigs[i].fIsEnabled) - buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG); - String modifier = fHoverConfigs[i].fModifierString; - if (modifier == null || modifier.length() == 0) - modifier = JavaEditorTextHoverDescriptor.NO_MODIFIER; - buf.append(modifier); - buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - - maskBuf.append(getContributedHovers()[i].getId()); - maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - maskBuf.append(fHoverConfigs[i].fStateMask); - maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - } - fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf - .toString()); - fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, - maskBuf.toString()); - - fStore.setValue(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, - fShowHoverAffordanceCheckbox.getSelection()); - - WebUI.getDefault().resetJavaEditorTextHoverDescriptors(); - } - - void performDefaults() { - restoreFromPreferences(); - initializeFields(); - } - - private void restoreFromPreferences() { - - fShowHoverAffordanceCheckbox - .setSelection(fStore - .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); - - String compiledTextHoverModifiers = fStore - .getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); - - StringTokenizer tokenizer = new StringTokenizer( - compiledTextHoverModifiers, - JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - HashMap idToModifier = new HashMap(tokenizer.countTokens() / 2); - - while (tokenizer.hasMoreTokens()) { - String id = tokenizer.nextToken(); - if (tokenizer.hasMoreTokens()) - idToModifier.put(id, tokenizer.nextToken()); - } - - String compiledTextHoverModifierMasks = WebUI.getDefault() - .getPreferenceStore().getString( - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); - - tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, - JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); - HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); - - while (tokenizer.hasMoreTokens()) { - String id = tokenizer.nextToken(); - if (tokenizer.hasMoreTokens()) - idToModifierMask.put(id, tokenizer.nextToken()); - } - - for (int i = 0; i < fHoverConfigs.length; i++) { - String modifierString = (String) idToModifier - .get(getContributedHovers()[i].getId()); - boolean enabled = true; - if (modifierString == null) - modifierString = JavaEditorTextHoverDescriptor.DISABLED_TAG; - - if (modifierString - .startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) { - enabled = false; - modifierString = modifierString.substring(1); - } - - if (modifierString - .equals(JavaEditorTextHoverDescriptor.NO_MODIFIER)) - modifierString = ""; //$NON-NLS-1$ - - fHoverConfigs[i].fModifierString = modifierString; - fHoverConfigs[i].fIsEnabled = enabled; - fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor - .computeStateMask(modifierString); - - if (fHoverConfigs[i].fStateMask == -1) { - try { - fHoverConfigs[i].fStateMask = Integer - .parseInt((String) idToModifierMask - .get(getContributedHovers()[i].getId())); - } catch (NumberFormatException ex) { - fHoverConfigs[i].fStateMask = -1; - } - } - } - } - - private void handleModifierModified() { - int i = fHoverList.getSelectionIndex(); - String modifiers = fModifierEditor.getText(); - fHoverConfigs[i].fModifierString = modifiers; - fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor - .computeStateMask(modifiers); - if (fHoverConfigs[i].fIsEnabled && fHoverConfigs[i].fStateMask == -1) - fStatus = new StatusInfo( - IStatus.ERROR, - PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.modifierIsNotValid", fHoverConfigs[i].fModifierString)); //$NON-NLS-1$ - else - fStatus = new StatusInfo(); - updateStatus(); - } - - private void handleHoverListSelection() { - int i = fHoverList.getSelectionIndex(); - boolean enabled = fHoverConfigs[i].fIsEnabled; - fEnableField.setSelection(enabled); - fModifierEditor.setEnabled(enabled); - fModifierEditor.setText(fHoverConfigs[i].fModifierString); - String description = getContributedHovers()[i].getDescription(); - if (description == null) - description = ""; //$NON-NLS-1$ - fDescription.setText(description); - } - - IStatus getStatus() { - if (fStatus == null) - fStatus = new StatusInfo(); - return fStatus; - } - - private void updateStatus() { - int i = 0; - HashMap stateMasks = new HashMap(fHoverConfigs.length); - while (fStatus.isOK() && i < fHoverConfigs.length) { - if (fHoverConfigs[i].fIsEnabled) { - String label = getContributedHovers()[i].getLabel(); - Integer stateMask = new Integer(fHoverConfigs[i].fStateMask); - if (fHoverConfigs[i].fStateMask == -1) - fStatus = new StatusInfo( - IStatus.ERROR, - PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover", new String[] { fHoverConfigs[i].fModifierString, label })); //$NON-NLS-1$ - else if (stateMasks.containsKey(stateMask)) - fStatus = new StatusInfo( - IStatus.ERROR, - PreferencesMessages - .getFormattedString( - "JavaEditorHoverConfigurationBlock.duplicateModifier", new String[] { label, (String) stateMasks.get(stateMask) })); //$NON-NLS-1$ - else - stateMasks.put(stateMask, label); - } - i++; - } - - if (fStatus.isOK()) - fMainPreferencePage.updateStatus(fStatus); - else { - fMainPreferencePage.setValid(false); - StatusUtil.applyToStatusLine(fMainPreferencePage, fStatus); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java deleted file mode 100644 index d1a88f9..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java +++ /dev/null @@ -1,2050 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -//import java.text.Collator; -import java.util.ArrayList; -//import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -//import java.util.SortedSet; -import java.util.StringTokenizer; -//import java.util.TreeSet; - -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter; -import net.sourceforge.phpdt.internal.ui.util.TabFolderLayout; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.EditorUtility; -import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; -import net.sourceforge.phpeclipse.preferences.ColorEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -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.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.RowLayout; -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.Event; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Link; -import org.eclipse.swt.widgets.List; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.PreferencesUtil; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; - - -/** - * The page for setting the editor options. - */ -public class JavaEditorPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - private static final String BOLD = PreferenceConstants.EDITOR_BOLD_SUFFIX; - - private static final String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; - - private static final String DELIMITER = PreferencesMessages - .getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ - - /** The keys of the overlay store. */ - public final OverlayPreferenceStore.OverlayKey[] fKeys; - - private final String[][] fSyntaxColorListModel = new String[][] { - { - PreferencesMessages - .getString("JavaEditorPreferencePage.multiLineComment"), - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.singleLineComment"), - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.tags"), - PreferenceConstants.EDITOR_PHP_TAG_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.keywords"), - PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, - { - PreferencesMessages - .getString("JavaEditorPreferencePage.functionNames"), - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.variables"), - PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.variables_dollar"), - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.constants"), - PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR }, - //$NON-NLS-1$ - { PreferencesMessages.getString("JavaEditorPreferencePage.types"), - PreferenceConstants.EDITOR_PHP_TYPE_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.strings_dq"), - PreferenceConstants.EDITOR_STRING_COLOR_DQ }, - { - PreferencesMessages - .getString("JavaEditorPreferencePage.strings_sq"), - PreferenceConstants.EDITOR_STRING_COLOR_SQ }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.operators"), - PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.returnKeyword"), - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR }, - { PreferencesMessages.getString("JavaEditorPreferencePage.braces"), - PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.phpDocKeywords"), - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.phpDocHtmlTags"), - PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.phpDocLinks"), - PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.phpDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ - }; - - private final String[][] fAppearanceColorListModel = new String[][] { - { - PreferencesMessages - .getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), - PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.currentLineHighlighColor"), - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.printMarginColor2"), - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.findScopeColor2"), - PreferenceConstants.EDITOR_FIND_SCOPE_COLOR }, - //$NON-NLS-1$ - { - PreferencesMessages - .getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR }, //$NON-NLS-1$ - }; - - // private final String[][] fAnnotationColorListModel; - - // private final String[][] fAnnotationDecorationListModel = new String[][]{ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"), - // AnnotationPreference.STYLE_NONE}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"), - // AnnotationPreference.STYLE_SQUIGGLIES}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"), - // AnnotationPreference.STYLE_UNDERLINE}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"), - // AnnotationPreference.STYLE_BOX}, - // //$NON-NLS-1$ - // { - // PreferencesMessages - // .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"), - // AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$ - // }; - private OverlayPreferenceStore fOverlayStore; - - private JavaTextTools fJavaTextTools; - - private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; - - private FoldingConfigurationBlock fFoldingConfigurationBlock; - - private Map fColorButtons = new HashMap(); - - private Map fCheckBoxes = new HashMap(); - - private SelectionListener fCheckBoxListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - Button button = (Button) e.widget; - fOverlayStore.setValue((String) fCheckBoxes.get(button), button - .getSelection()); - } - }; - - private Map fTextFields = new HashMap(); - - private ModifyListener fTextFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - Text text = (Text) e.widget; - fOverlayStore.setValue((String) fTextFields.get(text), text - .getText()); - } - }; - - private ArrayList fNumberFields = new ArrayList(); - - private ModifyListener fNumberFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - numberFieldChanged((Text) e.widget); - } - }; - - private List fSyntaxColorList; - - private List fAppearanceColorList; - - // private List fContentAssistColorList; - //private List fAnnotationList; - - private ColorEditor fSyntaxForegroundColorEditor; - - private ColorEditor fAppearanceColorEditor; - - //private ColorEditor fAnnotationForegroundColorEditor; - - //private ColorEditor fContentAssistColorEditor; - - private ColorEditor fBackgroundColorEditor; - - private Button fBackgroundDefaultRadioButton; - - private Button fBackgroundCustomRadioButton; - - private Button fBackgroundColorButton; - - private Button fBoldCheckBox; - - // private Button fAddJavaDocTagsButton; - - private Button fEscapeStringsButtonDQ; - - private Button fEscapeStringsButtonSQ; - - // private Button fGuessMethodArgumentsButton; - private SourceViewer fPreviewViewer; - - private Color fBackgroundColor; - - //private Control fAutoInsertDelayText; - - //private Control fAutoInsertJavaTriggerText; - - //private Control fAutoInsertJavaDocTriggerText; - - //private Label fAutoInsertDelayLabel; - - //private Label fAutoInsertJavaTriggerLabel; - - //private Label fAutoInsertJavaDocTriggerLabel; - - //private Button; - - //private Combo fDecorationStyleCombo; - - //private Button fHighlightInTextCheckBox; - - //private Button fShowInOverviewRulerCheckBox; - - //private Button fShowInVerticalRulerCheckBox; - - private Text fBrowserLikeLinksKeyModifierText; - - private Button fBrowserLikeLinksCheckBox; - - private StatusInfo fBrowserLikeLinksKeyModifierStatus; - - // private Button fCompletionInsertsRadioButton; - // private Button fCompletionOverwritesRadioButton; - // private Button fStickyOccurrencesButton; - /** - * Creates a new preference page. - */ - public JavaEditorPreferencePage() { - setDescription(PreferencesMessages - .getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - MarkerAnnotationPreferences markerAnnotationPreferences = new MarkerAnnotationPreferences(); - fKeys = createOverlayStoreKeys(markerAnnotationPreferences); - fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), fKeys); - // fAnnotationColorListModel = - // createAnnotationTypeListModel(markerAnnotationPreferences); - } - - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys( - MarkerAnnotationPreferences preferences) { - ArrayList overlayKeys = new ArrayList(); - Iterator e = preferences.getAnnotationPreferences().iterator(); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_FOREGROUND_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BACKGROUND_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.INT, - PreferenceConstants.EDITOR_TAB_WIDTH)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_TAG_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_TAG_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_TYPE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_TYPE_BOLD)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_STRING_COLOR_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_STRING_BOLD_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_STRING_COLOR_SQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_STRING_BOLD_SQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_TASK_TAG_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_TASK_TAG_BOLD)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING_DQ, - // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_OPERATOR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_MATCHING_BRACKETS)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.INT, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_MARK_OCCURRENCES)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_LINK_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CORRECTION_INDICATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SPACES_FOR_TABS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_AUTOACTIVATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.INT, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_AUTOINSERT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_ADDIMPORT)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SMART_PASTE)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP)); - // overlayKeys - // .add(new OverlayPreferenceStore.OverlayKey( - // OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_CLOSE_BRACES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_WRAP_WORDS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SMART_HOME_END)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); - while (e.hasNext()) { - AnnotationPreference info = (AnnotationPreference) e.next(); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, info - .getColorPreferenceKey())); - overlayKeys - .add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, info - .getTextPreferenceKey())); - if (info.getHighlightPreferenceKey() != null) - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, info - .getHighlightPreferenceKey())); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, info - .getOverviewRulerPreferenceKey())); - if (info.getVerticalRulerPreferenceKey() != null) - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, info - .getVerticalRulerPreferenceKey())); - if (info.getTextStylePreferenceKey() != null) - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.STRING, info - .getTextStylePreferenceKey())); - } - OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys - .size()]; - overlayKeys.toArray(keys); - return keys; - } /* - * @see IWorkbenchPreferencePage#init() - */ - - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - private void handleSyntaxColorListSelection() { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - fSyntaxForegroundColorEditor.setColorValue(rgb); - fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); - } - - private void handleAppearanceColorListSelection() { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - fAppearanceColorEditor.setColorValue(rgb); - } - - // private void handleAnnotationListSelection() { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][1]; - // RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - // fAnnotationForegroundColorEditor.setColorValue(rgb); - // key = fAnnotationColorListModel[i][2]; - // boolean showInText = fOverlayStore.getBoolean(key); - // fShowInTextCheckBox.setSelection(showInText); - // key = fAnnotationColorListModel[i][6]; - // if (key != null) { - // fDecorationStyleCombo.setEnabled(showInText); - // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { - // String value = fOverlayStore.getString(key); - // if (fAnnotationDecorationListModel[j][1].equals(value)) { - // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]); - // break; - // } - // } - // } else { - // fDecorationStyleCombo.setEnabled(false); - // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // - // set - // // selection - // // to - // // squigglies - // // if - // // the - // // key - // // is - // // not - // // there - // // (legacy - // // support) - // } - // key = fAnnotationColorListModel[i][3]; - // fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // key = fAnnotationColorListModel[i][4]; - // if (key != null) { - // fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // fHighlightInTextCheckBox.setEnabled(true); - // } else - // fHighlightInTextCheckBox.setEnabled(false); - // key = fAnnotationColorListModel[i][5]; - // if (key != null) { - // fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); - // fShowInVerticalRulerCheckBox.setEnabled(true); - // } else { - // fShowInVerticalRulerCheckBox.setSelection(true); - // fShowInVerticalRulerCheckBox.setEnabled(false); - // } - // } - private Control createSyntaxPage(Composite parent) { - Composite colorComposite = new Composite(parent, SWT.NULL); - colorComposite.setLayout(new GridLayout()); - Group backgroundComposite = new Group(colorComposite, - SWT.SHADOW_ETCHED_IN); - backgroundComposite.setLayout(new RowLayout()); - backgroundComposite.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ - SelectionListener backgroundSelectionListener = new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean custom = fBackgroundCustomRadioButton.getSelection(); - fBackgroundColorButton.setEnabled(custom); - fOverlayStore.setValue( - PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, - !custom); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }; - fBackgroundDefaultRadioButton = new Button(backgroundComposite, - SWT.RADIO | SWT.LEFT); - fBackgroundDefaultRadioButton.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ - fBackgroundDefaultRadioButton - .addSelectionListener(backgroundSelectionListener); - fBackgroundCustomRadioButton = new Button(backgroundComposite, - SWT.RADIO | SWT.LEFT); - fBackgroundCustomRadioButton.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ - fBackgroundCustomRadioButton - .addSelectionListener(backgroundSelectionListener); - fBackgroundColorEditor = new ColorEditor(backgroundComposite); - fBackgroundColorButton = fBackgroundColorEditor.getButton(); - Label label = new Label(colorComposite, SWT.LEFT); - label.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Composite editorComposite = new Composite(colorComposite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - editorComposite.setLayoutData(gd); - fSyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL - | SWT.BORDER); - gd = new GridData(GridData.FILL_BOTH); - gd.heightHint = convertHeightInCharsToPixels(5); - fSyntaxColorList.setLayoutData(gd); - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - label = new Label(stylesComposite, SWT.LEFT); - label.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - fSyntaxForegroundColorEditor = new ColorEditor(stylesComposite); - Button foregroundColorButton = fSyntaxForegroundColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - foregroundColorButton.setLayoutData(gd); - fBoldCheckBox = new Button(stylesComposite, SWT.CHECK); - fBoldCheckBox.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - gd.horizontalSpan = 2; - fBoldCheckBox.setLayoutData(gd); - label = new Label(colorComposite, SWT.LEFT); - label.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Control previewer = createPreviewer(colorComposite); - gd = new GridData(GridData.FILL_BOTH); - gd.widthHint = convertWidthInCharsToPixels(20); - gd.heightHint = convertHeightInCharsToPixels(5); - previewer.setLayoutData(gd); - fSyntaxColorList.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - handleSyntaxColorListSelection(); - } - }); - foregroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - PreferenceConverter.setValue(fOverlayStore, key, - fSyntaxForegroundColorEditor.getColorValue()); - } - }); - fBackgroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - PreferenceConverter.setValue(fOverlayStore, - PreferenceConstants.EDITOR_BACKGROUND_COLOR, - fBackgroundColorEditor.getColorValue()); - } - }); - fBoldCheckBox.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fSyntaxColorList.getSelectionIndex(); - String key = fSyntaxColorListModel[i][1]; - fOverlayStore - .setValue(key + BOLD, fBoldCheckBox.getSelection()); - } - }); - return colorComposite; - } - - private Control createPreviewer(Composite parent) { - Preferences coreStore = createTemporaryCorePreferenceStore(); - fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false); - IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); - IPreferenceStore store = new ChainedPreferenceStore( - new IPreferenceStore[] { - fOverlayStore, - new PreferencesAdapter( - createTemporaryCorePreferenceStore()), - generalTextStore }); - - fPreviewViewer = new JavaSourceViewer(parent, null, null, false, - SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - PHPSourceViewerConfiguration configuration = new PHPSourceViewerConfiguration( - tools.getColorManager(), store, null, - IPHPPartitions.PHP_PARTITIONING); - // PHPSourceViewerConfiguration configuration =new - // PHPSourceViewerConfiguration(fJavaTextTools, null, - // IPHPPartitions.PHP_PARTITIONING); - fPreviewViewer.configure(configuration); - - Font font = JFaceResources - .getFont(PreferenceConstants.EDITOR_TEXT_FONT); - fPreviewViewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); - fPreviewViewer.setEditable(false); - String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ - IDocument document = new Document(content); - fJavaTextTools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - fPreviewViewer.setDocument(document); - return fPreviewViewer.getControl(); - } - - private Preferences createTemporaryCorePreferenceStore() { - Preferences result = new Preferences(); - result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ - return result; - } - - private Control createAppearancePage(Composite parent) { - Composite appearanceComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - appearanceComposite.setLayout(layout); - - // Inserts a hyper-link to the General Editor preferences page - // TODO Can probably be removed post 1.5.0? - String label = PreferencesMessages - .getString("JavaEditorPreferencePage.appearanceTabLink"); - Link link = new Link(appearanceComposite, SWT.NONE); - GridData gridPosition = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gridPosition.horizontalSpan = 2; - link.setLayoutData(gridPosition); - - link.setText(label); - link.addListener(SWT.Selection, new Listener () { - public void handleEvent(Event event) { - String u = event.text; - PreferencesUtil.createPreferenceDialogOn(getShell(), u, null, null); - } - }); - String tooltip = PreferencesMessages - .getString("JavaEditorPreferencePage.appearanceTabTooltip"); - link.setToolTipText(tooltip); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ - addTextField(appearanceComposite, label, - PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ - addTextField( - appearanceComposite, - label, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, - 3, 0, true); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ - addCheckBox( - appearanceComposite, - label, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, - 0); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, - PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ - addCheckBox( - appearanceComposite, - label, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, - 0); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ - addCheckBox( - appearanceComposite, - label, - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, - 0); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.markOccurrences"); //$NON-NLS-1$ - // Button master= addCheckBox(appearanceComposite, label, - // PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ - label = PreferencesMessages - .getString("JavaEditorPreferencePage.stickyOccurrences"); //$NON-NLS-1$ - // fStickyOccurrencesButton= addCheckBox(appearanceComposite, label, - // PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ - // createDependency(master, fStickyOccurrencesButton); - Label l = new Label(appearanceComposite, SWT.LEFT); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - gd.heightHint = convertHeightInCharsToPixels(1) / 2; - l.setLayoutData(gd); - l = new Label(appearanceComposite, SWT.LEFT); - l.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - l.setLayoutData(gd); - Composite editorComposite = new Composite(appearanceComposite, SWT.NONE); - layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL - | GridData.FILL_VERTICAL); - gd.horizontalSpan = 2; - editorComposite.setLayoutData(gd); - fAppearanceColorList = new List(editorComposite, SWT.SINGLE - | SWT.V_SCROLL | SWT.BORDER); - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING - | GridData.FILL_HORIZONTAL); - gd.heightHint = convertHeightInCharsToPixels(8); - fAppearanceColorList.setLayoutData(gd); - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - l = new Label(stylesComposite, SWT.LEFT); - l.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - l.setLayoutData(gd); - fAppearanceColorEditor = new ColorEditor(stylesComposite); - Button foregroundColorButton = fAppearanceColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - foregroundColorButton.setLayoutData(gd); - fAppearanceColorList.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - handleAppearanceColorListSelection(); - } - }); - foregroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - PreferenceConverter.setValue(fOverlayStore, key, - fAppearanceColorEditor.getColorValue()); - } - }); - return appearanceComposite; - } - - // private Control createAnnotationsPage(Composite parent) { - // Composite composite = new Composite(parent, SWT.NULL); - // GridLayout layout = new GridLayout(); - // layout.numColumns = 2; - // composite.setLayout(layout); - // String text = PreferencesMessages - // .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); - // //$NON-NLS-1$ - // addCheckBox(composite, text, - // PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); - // text = PreferencesMessages - // .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ - // addCheckBox(composite, text, - // PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); - // addFiller(composite); - // Label label = new Label(composite, SWT.LEFT); - // label.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotationPresentationOptions")); - // //$NON-NLS-1$ - // GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - // gd.horizontalSpan = 2; - // label.setLayoutData(gd); - // Composite editorComposite = new Composite(composite, SWT.NONE); - // layout = new GridLayout(); - // layout.numColumns = 2; - // layout.marginHeight = 0; - // layout.marginWidth = 0; - // editorComposite.setLayout(layout); - // gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | - // GridData.FILL_VERTICAL); - // gd.horizontalSpan = 2; - // editorComposite.setLayoutData(gd); - // fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL - // | SWT.BORDER); - // gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING - // | GridData.FILL_HORIZONTAL); - // gd.heightHint = convertHeightInCharsToPixels(10); - // fAnnotationList.setLayoutData(gd); - // Composite optionsComposite = new Composite(editorComposite, SWT.NONE); - // layout = new GridLayout(); - // layout.marginHeight = 0; - // layout.marginWidth = 0; - // layout.numColumns = 2; - // optionsComposite.setLayout(layout); - // optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - // fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInTextCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInText")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInTextCheckBox.setLayoutData(gd); - // fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY); - // for (int i = 0; i < fAnnotationDecorationListModel.length; i++) - // fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]); - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // gd.horizontalIndent = 20; - // fDecorationStyleCombo.setLayoutData(gd); - // fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK); - // fHighlightInTextCheckBox.setText(PreferencesMessages - // .getString("TextEditorPreferencePage.annotations.highlightInText")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fHighlightInTextCheckBox.setLayoutData(gd); - // fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInOverviewRulerCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInOverviewRulerCheckBox.setLayoutData(gd); - // fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK); - // fShowInVerticalRulerCheckBox.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); - // //$NON-NLS-1$ - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // gd.horizontalSpan = 2; - // fShowInVerticalRulerCheckBox.setLayoutData(gd); - // label = new Label(optionsComposite, SWT.LEFT); - // label.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ - // gd = new GridData(); - // gd.horizontalAlignment = GridData.BEGINNING; - // label.setLayoutData(gd); - // fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite); - // Button foregroundColorButton = - // fAnnotationForegroundColorEditor.getButton(); - // gd = new GridData(GridData.FILL_HORIZONTAL); - // gd.horizontalAlignment = GridData.BEGINNING; - // foregroundColorButton.setLayoutData(gd); - // fAnnotationList.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // handleAnnotationListSelection(); - // } - // }); - // fShowInTextCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][2]; - // fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); - // String decorationKey = fAnnotationColorListModel[i][6]; - // fDecorationStyleCombo.setEnabled(decorationKey != null - // && fShowInTextCheckBox.getSelection()); - // } - // }); - // fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][4]; - // fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); - // } - // }); - // fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() - // { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][3]; - // fOverlayStore - // .setValue(key, fShowInOverviewRulerCheckBox.getSelection()); - // } - // }); - // fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() - // { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][5]; - // fOverlayStore - // .setValue(key, fShowInVerticalRulerCheckBox.getSelection()); - // } - // }); - // foregroundColorButton.addSelectionListener(new SelectionListener() { - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][1]; - // PreferenceConverter.setValue(fOverlayStore, key, - // fAnnotationForegroundColorEditor.getColorValue()); - // } - // }); - // fDecorationStyleCombo.addSelectionListener(new SelectionListener() { - // /** - // * {@inheritdoc} - // */ - // public void widgetDefaultSelected(SelectionEvent e) { - // // do nothing - // } - // /** - // * {@inheritdoc} - // */ - // public void widgetSelected(SelectionEvent e) { - // int i = fAnnotationList.getSelectionIndex(); - // String key = fAnnotationColorListModel[i][6]; - // if (key != null) { - // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { - // if (fAnnotationDecorationListModel[j][0] - // .equals(fDecorationStyleCombo.getText())) { - // fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]); - // break; - // } - // } - // } - // } - // }); - // return composite; - // } -// private String[][] createAnnotationTypeListModel( -// MarkerAnnotationPreferences preferences) { -// ArrayList listModelItems = new ArrayList(); -// SortedSet sortedPreferences = new TreeSet(new Comparator() { -// /* -// * @see java.util.Comparator#compare(java.lang.Object, -// * java.lang.Object) -// */ -// public int compare(Object o1, Object o2) { -// if (!(o2 instanceof AnnotationPreference)) -// return -1; -// if (!(o1 instanceof AnnotationPreference)) -// return 1; -// AnnotationPreference a1 = (AnnotationPreference) o1; -// AnnotationPreference a2 = (AnnotationPreference) o2; -// return Collator.getInstance().compare(a1.getPreferenceLabel(), -// a2.getPreferenceLabel()); -// } -// }); -// sortedPreferences.addAll(preferences.getAnnotationPreferences()); -// Iterator e = sortedPreferences.iterator(); -// while (e.hasNext()) { -// AnnotationPreference info = (AnnotationPreference) e.next(); -// listModelItems.add(new String[] { info.getPreferenceLabel(), -// info.getColorPreferenceKey(), info.getTextPreferenceKey(), -// info.getOverviewRulerPreferenceKey(), -// info.getHighlightPreferenceKey(), -// info.getVerticalRulerPreferenceKey(), -// info.getTextStylePreferenceKey() }); -// } -// String[][] items = new String[listModelItems.size()][]; -// listModelItems.toArray(items); -// return items; -// } - - private Control createTypingPage(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 1; - composite.setLayout(layout); - String label; - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.overwriteMode"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, - // PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); - // addFiller(composite); - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.smartHomeEnd"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, - // PreferenceConstants.EDITOR_SMART_HOME_END, 1); - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.subWordNavigation"); - // //$NON-NLS-1$ - // addCheckBox(composite, label, - // PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); - // addFiller(composite); - Group group = new Group(composite, SWT.NONE); - layout = new GridLayout(); - layout.numColumns = 2; - group.setLayout(layout); - group.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.wrapWords");//$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_WORDS, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.wrapStringsDQ");//$NON-NLS-1$ - Button button = addCheckBox(group, label, - PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.escapeStringsDQ");//$NON-NLS-1$ - fEscapeStringsButtonDQ = addCheckBox(group, label, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, 1); - createDependency(button, fEscapeStringsButtonDQ); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.wrapStringsSQ");//$NON-NLS-1$ - button = addCheckBox(group, label, - PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.escapeStringsSQ"); - //$NON-NLS-1$ - fEscapeStringsButtonSQ = addCheckBox(group, label, - PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, 1); - createDependency(button, fEscapeStringsButtonSQ); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.smartPaste"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.insertSpaceForTabs"); - //$NON-NLS-1$ - addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.closeStringsDQ"); - //$NON-NLS-1$ - addCheckBox(group, label, - PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, 1); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.closeStringsSQ"); - //$NON-NLS-1$ - addCheckBox(group, label, - PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.closeBrackets"); - //$NON-NLS-1$ - addCheckBox(group, label, - PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1); - - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.closeBraces"); - // //$NON-NLS-1$ - // addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, - // 1); - - label = PreferencesMessages - .getString("JavaEditorPreferencePage.closeJavaDocs"); - //$NON-NLS-1$ - button = addCheckBox(group, label, - PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); - label = PreferencesMessages - .getString("JavaEditorPreferencePage.formatJavaDocs"); - //$NON-NLS-1$ - button = addCheckBox(group, label, - PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); - - // - // label = PreferencesMessages - // .getString("JavaEditorPreferencePage.addJavaDocTags"); - // //$NON-NLS-1$ - // fAddJavaDocTagsButton = addCheckBox(group, label, - // PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); - // createDependency(button, fAddJavaDocTagsButton); - return composite; - } - -// private void addFiller(Composite composite) { -// Label filler = new Label(composite, SWT.LEFT); -// GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); -// gd.horizontalSpan = 2; -// gd.heightHint = convertHeightInCharsToPixels(1) / 2; -// filler.setLayoutData(gd); -// } - - private static void indent(Control control) { - GridData gridData = new GridData(); - gridData.horizontalIndent = 20; - control.setLayoutData(gridData); - } - - private static void createDependency(final Button master, - final Control slave) { - indent(slave); - master.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - slave.setEnabled(master.getSelection()); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - } - -// private void addCompletionRadioButtons(Composite contentAssistComposite) { -// Composite completionComposite = new Composite(contentAssistComposite, -// SWT.NONE); -// GridData ccgd = new GridData(); -// ccgd.horizontalSpan = 2; -// completionComposite.setLayoutData(ccgd); -// GridLayout ccgl = new GridLayout(); -// ccgl.marginWidth = 0; -// ccgl.numColumns = 2; -// completionComposite.setLayout(ccgl); -// // SelectionListener completionSelectionListener= new SelectionAdapter() -// // { -// // public void widgetSelected(SelectionEvent e) { -// // boolean insert= fCompletionInsertsRadioButton.getSelection(); -// // fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, -// // insert); -// // } -// // }; -// // -// // fCompletionInsertsRadioButton= new Button(completionComposite, -// // SWT.RADIO -// // | SWT.LEFT); -// // fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); -// // //$NON-NLS-1$ -// // fCompletionInsertsRadioButton.setLayoutData(new GridData()); -// // fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); -// // -// // fCompletionOverwritesRadioButton= new Button(completionComposite, -// // SWT.RADIO | SWT.LEFT); -// // fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); -// // //$NON-NLS-1$ -// // fCompletionOverwritesRadioButton.setLayoutData(new GridData()); -// // fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); -// } - - private Control createNavigationPage(Composite parent) { - Composite composite = new Composite(parent, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - String text = PreferencesMessages - .getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); - //$NON-NLS-1$ - fBrowserLikeLinksCheckBox = addCheckBox(composite, text, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); - fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean state = fBrowserLikeLinksCheckBox.getSelection(); - fBrowserLikeLinksKeyModifierText.setEnabled(state); - handleBrowserLikeLinksKeyModifierModified(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }); - // Text field for modifier string - text = PreferencesMessages - .getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); - //$NON-NLS-1$ - fBrowserLikeLinksKeyModifierText = addTextField(composite, text, - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, - 0, false); - fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); - - if (computeStateMask(fOverlayStore - .getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { - // Fix possible illegal modifier string - int stateMask = fOverlayStore - .getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); - if (stateMask == -1) - fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ - else - fBrowserLikeLinksKeyModifierText.setText(EditorUtility - .getModifierString(stateMask)); - } - fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { - private boolean isModifierCandidate; - - public void keyPressed(KeyEvent e) { - isModifierCandidate = e.keyCode > 0 && e.character == 0 - && e.stateMask == 0; - } - - public void keyReleased(KeyEvent e) { - if (isModifierCandidate && e.stateMask > 0 - && e.stateMask == e.stateMask && e.character == 0) {// && - // e.time - // -time - // < - // 1000) - // { - String modifierString = fBrowserLikeLinksKeyModifierText - .getText(); - Point selection = fBrowserLikeLinksKeyModifierText - .getSelection(); - int i = selection.x - 1; - while (i > -1 - && Character.isWhitespace(modifierString.charAt(i))) { - i--; - } - boolean needsPrefixDelimiter = i > -1 - && !String.valueOf(modifierString.charAt(i)) - .equals(DELIMITER); - - i = selection.y; - while (i < modifierString.length() - && Character.isWhitespace(modifierString.charAt(i))) { - i++; - } - boolean needsPostfixDelimiter = i < modifierString.length() - && !String.valueOf(modifierString.charAt(i)) - .equals(DELIMITER); - - String insertString; - - if (needsPrefixDelimiter && needsPostfixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", - new String[] { Action - .findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPrefixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", - new String[] { Action - .findModifierString(e.stateMask) }); //$NON-NLS-1$ - else if (needsPostfixDelimiter) - insertString = PreferencesMessages - .getFormattedString( - "JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", - new String[] { Action - .findModifierString(e.stateMask) }); //$NON-NLS-1$ - else - insertString = Action.findModifierString(e.stateMask); - - fBrowserLikeLinksKeyModifierText.insert(insertString); - } - } - }); - - fBrowserLikeLinksKeyModifierText - .addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - handleBrowserLikeLinksKeyModifierModified(); - } - }); - return composite; - } - - private void handleBrowserLikeLinksKeyModifierModified() { - String modifiers = fBrowserLikeLinksKeyModifierText.getText(); - int stateMask = computeStateMask(modifiers); - if (fBrowserLikeLinksCheckBox.getSelection() - && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { - if (stateMask == -1) - fBrowserLikeLinksKeyModifierStatus = new StatusInfo( - IStatus.ERROR, - PreferencesMessages - .getFormattedString( - "JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ - else - fBrowserLikeLinksKeyModifierStatus = new StatusInfo( - IStatus.ERROR, - PreferencesMessages - .getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); - //$NON-NLS-1$ - setValid(false); - StatusUtil.applyToStatusLine(this, - fBrowserLikeLinksKeyModifierStatus); - } else { - fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); - updateStatus(fBrowserLikeLinksKeyModifierStatus); - } - } - -// private IStatus getBrowserLikeLinksKeyModifierStatus() { -// if (fBrowserLikeLinksKeyModifierStatus == null) -// fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); -// return fBrowserLikeLinksKeyModifierStatus; -// } - - /** - * Computes the state mask for the given modifier string. - * - * @param modifiers - * the string with the modifiers, separated by '+', '-', ';', ',' - * or '.' - * @return the state mask or -1 if the input is invalid - */ - private int computeStateMask(String modifiers) { - if (modifiers == null) - return -1; - if (modifiers.length() == 0) - return SWT.NONE; - int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, - ",;.:+-* "); //$NON-NLS-1$ - while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility - .findLocalizedModifier(modifierTokenizer.nextToken()); - if (modifier == 0 || (stateMask & modifier) == modifier) - return -1; - stateMask = stateMask | modifier; - } - return stateMask; - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - initializeDefaultColors(); - fFoldingConfigurationBlock = new FoldingConfigurationBlock( - fOverlayStore); - fOverlayStore.load(); - fOverlayStore.start(); - TabFolder folder = new TabFolder(parent, SWT.NONE); - folder.setLayout(new TabFolderLayout()); - folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - TabItem item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ - item.setControl(createAppearancePage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ - item.setControl(createSyntaxPage(folder)); - - // item = new TabItem(folder, SWT.NONE); - // item.setText(PreferencesMessages - // .getString("JavaEditorPreferencePage.annotationsTab.title")); - // //$NON-NLS-1$ - // item.setControl(createAnnotationsPage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.typing.tabTitle")); - //$NON-NLS-1$ - item.setControl(createTypingPage(folder)); - - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.hoverTab.title")); - //$NON-NLS-1$ - fJavaEditorHoverConfigurationBlock = new JavaEditorHoverConfigurationBlock( - this, fOverlayStore); - item.setControl(fJavaEditorHoverConfigurationBlock - .createControl(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.navigationTab.title")); - // //$NON-NLS-1$ - item.setControl(createNavigationPage(folder)); - item = new TabItem(folder, SWT.NONE); - item.setText(PreferencesMessages - .getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ - item.setControl(fFoldingConfigurationBlock.createControl(folder)); - - initialize(); - Dialog.applyDialogFont(folder); - return folder; - } - - private void initialize() { - initializeFields(); - for (int i = 0; i < fSyntaxColorListModel.length; i++) - fSyntaxColorList.add(fSyntaxColorListModel[i][0]); - fSyntaxColorList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { - fSyntaxColorList.select(0); - handleSyntaxColorListSelection(); - } - } - }); - for (int i = 0; i < fAppearanceColorListModel.length; i++) - fAppearanceColorList.add(fAppearanceColorListModel[i][0]); - fAppearanceColorList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fAppearanceColorList != null - && !fAppearanceColorList.isDisposed()) { - fAppearanceColorList.select(0); - handleAppearanceColorListSelection(); - } - } - }); - // for (int i = 0; i < fAnnotationColorListModel.length; i++) - // fAnnotationList.add(fAnnotationColorListModel[i][0]); - // fAnnotationList.getDisplay().asyncExec(new Runnable() { - // public void run() { - // if (fAnnotationList != null && !fAnnotationList.isDisposed()) { - // fAnnotationList.select(0); - // handleAnnotationListSelection(); - // } - // } - // }); - // for (int i= 0; i < fContentAssistColorListModel.length; i++) - // fContentAssistColorList.add(fContentAssistColorListModel[i][0]); - // fContentAssistColorList.getDisplay().asyncExec(new Runnable() { - // public void run() { - // if (fContentAssistColorList != null && - // !fContentAssistColorList.isDisposed()) { - // fContentAssistColorList.select(0); - // handleContentAssistColorListSelection(); - // } - // } - // }); - fFoldingConfigurationBlock.initialize(); - } - - private void initializeFields() { - Iterator e = fColorButtons.keySet().iterator(); - while (e.hasNext()) { - ColorEditor c = (ColorEditor) e.next(); - String key = (String) fColorButtons.get(c); - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - c.setColorValue(rgb); - } - e = fCheckBoxes.keySet().iterator(); - while (e.hasNext()) { - Button b = (Button) e.next(); - String key = (String) fCheckBoxes.get(b); - b.setSelection(fOverlayStore.getBoolean(key)); - } - e = fTextFields.keySet().iterator(); - while (e.hasNext()) { - Text t = (Text) e.next(); - String key = (String) fTextFields.get(t); - t.setText(fOverlayStore.getString(key)); - } - RGB rgb = PreferenceConverter.getColor(fOverlayStore, - PreferenceConstants.EDITOR_BACKGROUND_COLOR); - fBackgroundColorEditor.setColorValue(rgb); - boolean default_ = fOverlayStore - .getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); - fBackgroundDefaultRadioButton.setSelection(default_); - fBackgroundCustomRadioButton.setSelection(!default_); - fBackgroundColorButton.setEnabled(!default_); -// boolean closeJavaDocs = fOverlayStore -// .getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); - // fAddJavaDocTagsButton.setEnabled(closeJavaDocs); - fEscapeStringsButtonDQ.setEnabled(fOverlayStore - .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); - fEscapeStringsButtonSQ.setEnabled(fOverlayStore - .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); - // boolean fillMethodArguments= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); - // fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); - // boolean completionInserts= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); - // fCompletionInsertsRadioButton.setSelection(completionInserts); - // fCompletionOverwritesRadioButton.setSelection(! completionInserts); - // - fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox - .getSelection()); - // boolean markOccurrences= - // fOverlayStore.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); - // fStickyOccurrencesButton.setEnabled(markOccurrences); - updateAutoactivationControls(); - } - - private void initializeDefaultColors() { - if (!getPreferenceStore().contains( - PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { - RGB rgb = getControl().getDisplay().getSystemColor( - SWT.COLOR_LIST_BACKGROUND).getRGB(); - PreferenceConverter.setDefault(fOverlayStore, - PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); - PreferenceConverter.setDefault(getPreferenceStore(), - PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); - } - if (!getPreferenceStore().contains( - PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { - RGB rgb = getControl().getDisplay().getSystemColor( - SWT.COLOR_LIST_FOREGROUND).getRGB(); - PreferenceConverter.setDefault(fOverlayStore, - PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); - PreferenceConverter.setDefault(getPreferenceStore(), - PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); - } - } - - private void updateAutoactivationControls() { - // boolean autoactivation= - // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); - // fAutoInsertDelayText.setEnabled(autoactivation); - // fAutoInsertDelayLabel.setEnabled(autoactivation); - // fAutoInsertJavaTriggerText.setEnabled(autoactivation); - // fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); - // - // fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); - // fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); - } - - /* - * @see PreferencePage#performOk() - */ - public boolean performOk() { - // fJavaEditorHoverConfigurationBlock.performOk(); - fFoldingConfigurationBlock.performOk(); - fOverlayStore - .setValue( - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, - computeStateMask(fBrowserLikeLinksKeyModifierText - .getText())); - fOverlayStore.propagate(); - WebUI.getDefault().savePluginPreferences(); - return true; - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fOverlayStore.loadDefaults(); - initializeFields(); - handleSyntaxColorListSelection(); - handleAppearanceColorListSelection(); - // handleAnnotationListSelection(); - // handleContentAssistColorListSelection(); - // fJavaEditorHoverConfigurationBlock.performDefaults(); - fFoldingConfigurationBlock.performDefaults(); - super.performDefaults(); - fPreviewViewer.invalidateTextPresentation(); - } - - /* - * @see DialogPage#dispose() - */ - public void dispose() { - fFoldingConfigurationBlock.dispose(); - - if (fJavaTextTools != null) { - fJavaTextTools.dispose(); - fJavaTextTools = null; - } - if (fOverlayStore != null) { - fOverlayStore.stop(); - fOverlayStore = null; - } - if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) - fBackgroundColor.dispose(); - super.dispose(); - } - - private Button addCheckBox(Composite parent, String label, String key, - int indentation) { - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - gd.horizontalSpan = 2; - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(fCheckBoxListener); - fCheckBoxes.put(checkBox, key); - return checkBox; - } - - private Text addTextField(Composite composite, String label, String key, - int textLimit, int indentation, boolean isNumber) { - return getTextControl(addLabelledTextField(composite, label, key, - textLimit, indentation, isNumber)); - } - -// private static Label getLabelControl(Control[] labelledTextField) { -// return (Label) labelledTextField[0]; -// } - - private static Text getTextControl(Control[] labelledTextField) { - return (Text) labelledTextField[1]; - } - - /** - * Returns an array of size 2: - first element is of type Label- - * second element is of type Text Use - * getLabelControl and getTextControl to get - * the 2 controls. - */ - private Control[] addLabelledTextField(Composite composite, String label, - String key, int textLimit, int indentation, boolean isNumber) { - Label labelControl = new Label(composite, SWT.NONE); - labelControl.setText(label); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - labelControl.setLayoutData(gd); - Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.widthHint = convertWidthInCharsToPixels(textLimit + 1); - textControl.setLayoutData(gd); - textControl.setTextLimit(textLimit); - fTextFields.put(textControl, key); - if (isNumber) { - fNumberFields.add(textControl); - textControl.setText("0"); - textControl.addModifyListener(fNumberFieldListener); - } else { - textControl.addModifyListener(fTextFieldListener); - } - return new Control[] { labelControl, textControl }; - } - - private String loadPreviewContentFromFile(String filename) { - String line; - String separator = System.getProperty("line.separator"); //$NON-NLS-1$ - StringBuffer buffer = new StringBuffer(512); - BufferedReader reader = null; - try { - reader = new BufferedReader(new InputStreamReader(getClass() - .getResourceAsStream(filename))); - while ((line = reader.readLine()) != null) { - buffer.append(line); - buffer.append(separator); - } - } catch (IOException io) { - WebUI.log(io); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - } - } - } - return buffer.toString(); - } - - private void numberFieldChanged(Text textControl) { - String number = textControl.getText(); - IStatus status = validatePositiveNumber(number); - if (!status.matches(IStatus.ERROR)) - fOverlayStore.setValue((String) fTextFields.get(textControl), - number); - updateStatus(status); - } - - private IStatus validatePositiveNumber(String number) { - StatusInfo status = new StatusInfo(); - if (number.length() == 0) { - status.setError(PreferencesMessages - .getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ - } else { - try { - int value = Integer.parseInt(number); - if (value < 0) - status.setError(PreferencesMessages.getFormattedString( - "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } catch (NumberFormatException e) { - status.setError(PreferencesMessages.getFormattedString( - "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ - } - } - return status; - } - - void updateStatus(IStatus status) { - if (!status.matches(IStatus.ERROR)) { - for (int i = 0; i < fNumberFields.size(); i++) { - Text text = (Text) fNumberFields.get(i); - IStatus s = validatePositiveNumber(text.getText()); - status = StatusUtil.getMoreSevere(s, status); - } - } - // status= - // StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), - // status); - // status= - // StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), - // status); - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java deleted file mode 100644 index 79c6d07..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.templates.TemplatePreferencePage; - -public class JavaTemplatePreferencePage extends TemplatePreferencePage - implements IWorkbenchPreferencePage { - - private TemplateVariableProcessor fTemplateProcessor; - - public JavaTemplatePreferencePage() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - setTemplateStore(WebUI.getDefault().getTemplateStore()); - setContextTypeRegistry(WebUI.getDefault() - .getTemplateContextRegistry()); - fTemplateProcessor = new TemplateVariableProcessor(); - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - boolean ok = super.performOk(); - - WebUI.getDefault().savePluginPreferences(); - - return ok; - } - - /* - * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#getFormatterPreferenceKey() - */ - protected String getFormatterPreferenceKey() { - return PreferenceConstants.TEMPLATES_USE_CODEFORMATTER; - } - - /* - * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createTemplateEditDialog(org.eclipse.jface.text.templates.Template, - * boolean, boolean) - */ - protected Dialog createTemplateEditDialog(Template template, boolean edit, - boolean isNameModifiable) { - return new EditTemplateDialog(getShell(), template, edit, - isNameModifiable, getContextTypeRegistry()); - } - - /* - * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createViewer(org.eclipse.swt.widgets.Composite) - */ - protected SourceViewer createViewer(Composite parent) { - GridData data = new GridData(); - IDocument document = new Document(); - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - IPreferenceStore store = WebUI.getDefault() - .getCombinedPreferenceStore(); - SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, - SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); - TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( - tools.getColorManager(), store, null, fTemplateProcessor); - viewer.configure(configuration); - viewer.setEditable(false); - viewer.setDocument(document); - - Font font = JFaceResources - .getFont(PreferenceConstants.EDITOR_TEXT_FONT); - viewer.getTextWidget().setFont(font); - new JavaSourcePreviewerUpdater(viewer, configuration, store); - - Control control = viewer.getControl(); - data = new GridData(GridData.HORIZONTAL_ALIGN_FILL - | GridData.FILL_VERTICAL); - control.setLayoutData(data); - - return viewer; - } - - /* - * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#updateViewerInput() - */ - protected void updateViewerInput() { - IStructuredSelection selection = (IStructuredSelection) getTableViewer() - .getSelection(); - SourceViewer viewer = getViewer(); - - if (selection.size() == 1 - && selection.getFirstElement() instanceof TemplatePersistenceData) { - TemplatePersistenceData data = (TemplatePersistenceData) selection - .getFirstElement(); - Template template = data.getTemplate(); - String contextId = template.getContextTypeId(); - TemplateContextType type = WebUI.getDefault() - .getTemplateContextRegistry().getContextType(contextId); - fTemplateProcessor.setContextType(type); - - IDocument doc = viewer.getDocument(); - - String start = null; - if ("javadoc".equals(contextId)) { //$NON-NLS-1$ - start = "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$ - } else - start = ""; //$NON-NLS-1$ - - doc.set(start + template.getPattern()); - int startLen = start.length(); - viewer.setDocument(doc, startLen, doc.getLength() - startLen); - - } else { - viewer.getDocument().set(""); //$NON-NLS-1$ - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java deleted file mode 100644 index 0cdcb6f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * 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 - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; - -/** - * The page for setting the editor options. - */ -public final class MarkOccurrencesPreferencePage extends - AbstractConfigurationBlockPreferencePage { - - /* - * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId() - */ - protected String getHelpId() { - return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE; - } - - /* - * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription() - */ - protected void setDescription() { - String description = PreferencesMessages - .getString("MarkOccurrencesConfigurationBlock.title"); - setDescription(description); - } - - /* - * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore() - */ - protected void setPreferenceStore() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - } - - protected Label createDescriptionLabel(Composite parent) { - return null; // no description for new look. - } - - /* - * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore) - */ - protected IPreferenceConfigurationBlock createConfigurationBlock( - OverlayPreferenceStore overlayPreferenceStore) { - return new MarkOccurrencesConfigurationBlock(overlayPreferenceStore); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java deleted file mode 100644 index 1bc2806..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java +++ /dev/null @@ -1,308 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.StringTokenizer; - -import net.sourceforge.phpdt.core.Flags; -import net.sourceforge.phpdt.internal.ui.util.SWTUtil; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField; -import net.sourceforge.phpdt.ui.JavaElementImageDescriptor; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.LabelProvider; -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.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -public class MembersOrderPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - - private static final String ALL_ENTRIES = "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$ - - private static final String PREF_OUTLINE_SORT_OPTION = PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; - - public static final String CONSTRUCTORS = "C"; //$NON-NLS-1$ - - public static final String FIELDS = "F"; //$NON-NLS-1$ - - public static final String METHODS = "M"; //$NON-NLS-1$ - - public static final String STATIC_METHODS = "SM"; //$NON-NLS-1$ - - public static final String STATIC_FIELDS = "SF"; //$NON-NLS-1$ - - public static final String INIT = "I"; //$NON-NLS-1$ - - public static final String STATIC_INIT = "SI"; //$NON-NLS-1$ - - public static final String TYPES = "T"; //$NON-NLS-1$ - - private ListDialogField fSortOrderList; - - private static List getSortOrderList(String string) { - StringTokenizer tokenizer = new StringTokenizer(string, ","); //$NON-NLS-1$ - List entries = new ArrayList(); - for (int i = 0; tokenizer.hasMoreTokens(); i++) { - String token = tokenizer.nextToken(); - entries.add(token); - } - return entries; - } - - private static boolean isValidEntries(List entries) { - StringTokenizer tokenizer = new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$ - int i = 0; - for (; tokenizer.hasMoreTokens(); i++) { - String token = tokenizer.nextToken(); - if (!entries.contains(token)) - return false; - } - return i == entries.size(); - } - - public MembersOrderPreferencePage() { - // set the preference store - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - - setDescription(PreferencesMessages - .getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$ - - String string = getPreferenceStore() - .getString(PREF_OUTLINE_SORT_OPTION); - - String upLabel = PreferencesMessages - .getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$ - String downLabel = PreferencesMessages - .getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$ - String[] buttonlabels = new String[] { upLabel, downLabel }; - - fSortOrderList = new ListDialogField(null, buttonlabels, - new MemberSortLabelProvider()); - fSortOrderList.setDownButtonIndex(1); - fSortOrderList.setUpButtonIndex(0); - - // validate entries stored in store, false get defaults - List entries = getSortOrderList(string); - if (!isValidEntries(entries)) { - string = WebUI.getDefault().getPreferenceStore() - .getDefaultString(PREF_OUTLINE_SORT_OPTION); - entries = getSortOrderList(string); - } - - fSortOrderList.setElements(entries); - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - // WorkbenchHelp.setHelp(getControl(), - // IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE); - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - - Composite composite = new Composite(parent, SWT.NONE); - - GridLayout layout = new GridLayout(); - layout.numColumns = 3; - layout.marginWidth = 0; - layout.marginHeight = 0; - composite.setLayout(layout); - - GridData data = new GridData(); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL_HORIZONTAL; - composite.setLayoutData(data); - - createSortOrderListDialogField(composite, 3); - Dialog.applyDialogFont(composite); - return composite; - } - - private void createSortOrderListDialogField(Composite composite, int span) { - fSortOrderList.doFillIntoGrid(composite, span); - - fSortOrderList.getLabelControl(null).dispose(); - - GridData data = (GridData) fSortOrderList.getListControl(null) - .getLayoutData(); - data.grabExcessHorizontalSpace = true; - data.verticalAlignment = 0; - data.heightHint = SWTUtil.getTableHeightHint(fSortOrderList - .getTableViewer().getTable(), 8); - } - - /* - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - protected void performDefaults() { - String string = getPreferenceStore().getDefaultString( - PREF_OUTLINE_SORT_OPTION); - fSortOrderList.setElements(getSortOrderList(string)); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - // reorders elements in the Outline based on selection - public boolean performOk() { - // update outline view - - // save preferences - IPreferenceStore store = getPreferenceStore(); - - StringBuffer buf = new StringBuffer(); - List curr = fSortOrderList.getElements(); - for (Iterator iter = curr.iterator(); iter.hasNext();) { - String s = (String) iter.next(); - buf.append(s); - buf.append(','); - } - store.setValue(PREF_OUTLINE_SORT_OPTION, buf.toString()); - WebUI.getDefault().savePluginPreferences(); - return true; - } - - private class MemberSortLabelProvider extends LabelProvider { - - public MemberSortLabelProvider() { - } - - /* - * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object) - */ - public String getText(Object element) { - - if (element instanceof String) { - String s = (String) element; - if (s.equals(FIELDS)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$ - } else if (s.equals(CONSTRUCTORS)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$ - } else if (s.equals(METHODS)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$ - } else if (s.equals(STATIC_FIELDS)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$ - } else if (s.equals(STATIC_METHODS)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$ - } else if (s.equals(INIT)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$ - } else if (s.equals(STATIC_INIT)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$ - } else if (s.equals(TYPES)) { - return PreferencesMessages - .getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$ - } - } - return ""; //$NON-NLS-1$ - } - - /* - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object) - */ - public Image getImage(Object element) { - // access to image registry - ImageDescriptorRegistry registry = WebUI - .getImageDescriptorRegistry(); - ImageDescriptor descriptor = null; - - if (element instanceof String) { - int visibility = Flags.AccPublic; - String s = (String) element; - if (s.equals(FIELDS)) { - // 0 will give the default field image - descriptor = JavaElementImageProvider - .getFieldImageDescriptor(false, visibility); - } else if (s.equals(CONSTRUCTORS)) { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, visibility); - // add a constructor adornment to the image descriptor - descriptor = new JavaElementImageDescriptor(descriptor, - JavaElementImageDescriptor.CONSTRUCTOR, - JavaElementImageProvider.SMALL_SIZE); - } else if (s.equals(METHODS)) { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, visibility); - } else if (s.equals(STATIC_FIELDS)) { - descriptor = JavaElementImageProvider - .getFieldImageDescriptor(false, visibility); - // add a constructor adornment to the image descriptor - descriptor = new JavaElementImageDescriptor(descriptor, - JavaElementImageDescriptor.STATIC, - JavaElementImageProvider.SMALL_SIZE); - } else if (s.equals(STATIC_METHODS)) { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, visibility); - // add a constructor adornment to the image descriptor - descriptor = new JavaElementImageDescriptor(descriptor, - JavaElementImageDescriptor.STATIC, - JavaElementImageProvider.SMALL_SIZE); - } else if (s.equals(INIT)) { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, visibility); - } else if (s.equals(STATIC_INIT)) { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, visibility); - descriptor = new JavaElementImageDescriptor(descriptor, - JavaElementImageDescriptor.STATIC, - JavaElementImageProvider.SMALL_SIZE); - } else if (s.equals(TYPES)) { - descriptor = JavaElementImageProvider - .getTypeImageDescriptor(false, true, - Flags.AccPublic); - } else { - descriptor = JavaElementImageProvider - .getMethodImageDescriptor(false, Flags.AccPublic); - } - return registry.get(descriptor); - } - return null; - } - - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java deleted file mode 100644 index 48263fd..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java +++ /dev/null @@ -1,585 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.Map.Entry; - -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.SWT; -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.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.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.Widget; - -/** - * Abstract options configuration block providing a general implementation for - * setting up an options configuration page. - * - * @since 2.1 - */ -public abstract class OptionsConfigurationBlock { - - protected static class ControlData { - private String fKey; - - private String[] fValues; - - public ControlData(String key, String[] values) { - fKey = key; - fValues = values; - } - - public String getKey() { - return fKey; - } - - public String getValue(boolean selection) { - int index = selection ? 0 : 1; - return fValues[index]; - } - - public String getValue(int index) { - return fValues[index]; - } - - public int getSelection(String value) { - if (value != null) { - for (int i = 0; i < fValues.length; i++) { - if (value.equals(fValues[i])) { - return i; - } - } - } - return fValues.length - 1; // assume the last option is the least - // severe - } - } - - protected Map fWorkingValues; - - protected ArrayList fCheckBoxes; - - protected ArrayList fComboBoxes; - - protected ArrayList fTextBoxes; - - protected HashMap fLabels; - - private SelectionListener fSelectionListener; - - private ModifyListener fTextModifyListener; - - protected IStatusChangeListener fContext; - - protected IJavaProject fProject; // project or null - - protected String[] fAllKeys; - - private Shell fShell; - - public OptionsConfigurationBlock(IStatusChangeListener context, - IJavaProject project, String[] allKeys) { - fContext = context; - fProject = project; - fAllKeys = allKeys; - - fWorkingValues = getOptions(true); - testIfOptionsComplete(fWorkingValues, allKeys); - - fCheckBoxes = new ArrayList(); - fComboBoxes = new ArrayList(); - fTextBoxes = new ArrayList(2); - fLabels = new HashMap(); - } - - private void testIfOptionsComplete(Map workingValues, String[] allKeys) { - for (int i = 0; i < allKeys.length; i++) { - if (workingValues.get(allKeys[i]) == null) { - WebUI - .logErrorMessage("preference option missing: " + allKeys[i] + " (" + this.getClass().getName() + ')'); //$NON-NLS-1$//$NON-NLS-2$ - } - } - } - - protected Map getOptions(boolean inheritJavaCoreOptions) { - if (fProject != null) { - return fProject.getOptions(inheritJavaCoreOptions); - } else { - return JavaCore.getOptions(); - } - } - - protected Map getDefaultOptions() { - return JavaCore.getDefaultOptions(); - } - - public final boolean hasProjectSpecificOptions() { - if (fProject != null) { - Map settings = fProject.getOptions(false); - String[] allKeys = fAllKeys; - for (int i = 0; i < allKeys.length; i++) { - if (settings.get(allKeys[i]) != null) { - return true; - } - } - } - return false; - } - - protected void setOptions(Map map) { - if (fProject != null) { - Map oldOptions = fProject.getOptions(false); - fProject.setOptions(map); - firePropertyChangeEvents(oldOptions, map); - } else { - JavaCore.setOptions((Hashtable) map); - } - } - - /** - * Computes the differences between the given old and new options and fires - * corresponding property change events on the Java plugin's mockup - * preference store. - * - * @param oldOptions - * The old options - * @param newOptions - * The new options - */ - private void firePropertyChangeEvents(Map oldOptions, Map newOptions) { - oldOptions = new HashMap(oldOptions); - Object source = fProject.getProject(); - MockupPreferenceStore store = WebUI.getDefault() - .getMockupPreferenceStore(); - Iterator iter = newOptions.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = (Entry) iter.next(); - - String name = (String) entry.getKey(); - Object oldValue = oldOptions.get(name); - Object newValue = entry.getValue(); - - if ((oldValue != null && !oldValue.equals(newValue)) - || (oldValue == null && newValue != null)) - store.firePropertyChangeEvent(source, name, oldValue, newValue); - oldOptions.remove(name); - } - - iter = oldOptions.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = (Entry) iter.next(); - store.firePropertyChangeEvent(source, (String) entry.getKey(), - entry.getValue(), null); - } - } - - protected Shell getShell() { - return fShell; - } - - protected void setShell(Shell shell) { - fShell = shell; - } - - protected abstract Control createContents(Composite parent); - - protected Button addCheckBox(Composite parent, String label, String key, - String[] values, int indent) { - ControlData data = new ControlData(key, values); - - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 3; - gd.horizontalIndent = indent; - - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - checkBox.setData(data); - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(getSelectionListener()); - - String currValue = (String) fWorkingValues.get(key); - checkBox.setSelection(data.getSelection(currValue) == 0); - - fCheckBoxes.add(checkBox); - - return checkBox; - } - - protected Combo addComboBox(Composite parent, String label, String key, - String[] values, String[] valueLabels, int indent) { - ControlData data = new ControlData(key, values); - - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indent; - - Label labelControl = new Label(parent, SWT.LEFT | SWT.WRAP); - labelControl.setText(label); - labelControl.setLayoutData(gd); - - Combo comboBox = new Combo(parent, SWT.READ_ONLY); - comboBox.setItems(valueLabels); - comboBox.setData(data); - comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); - comboBox.addSelectionListener(getSelectionListener()); - - fLabels.put(comboBox, labelControl); - - Label placeHolder = new Label(parent, SWT.NONE); - placeHolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - String currValue = (String) fWorkingValues.get(key); - comboBox.select(data.getSelection(currValue)); - - fComboBoxes.add(comboBox); - return comboBox; - } - -// protected void addInversedComboBox(Composite parent, String label, -// String key, String[] values, String[] valueLabels, int indent) { -// ControlData data = new ControlData(key, values); -// -// GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); -// gd.horizontalIndent = indent; -// gd.horizontalSpan = 3; -// -// Composite composite = new Composite(parent, SWT.NONE); -// GridLayout layout = new GridLayout(); -// layout.marginHeight = 0; -// layout.marginWidth = 0; -// layout.numColumns = 2; -// composite.setLayout(layout); -// composite.setLayoutData(gd); -// -// Combo comboBox = new Combo(composite, SWT.READ_ONLY); -// comboBox.setItems(valueLabels); -// comboBox.setData(data); -// comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); -// comboBox.addSelectionListener(getSelectionListener()); -// -// Label labelControl = new Label(composite, SWT.LEFT | SWT.WRAP); -// labelControl.setText(label); -// labelControl.setLayoutData(new GridData()); -// -// fLabels.put(comboBox, labelControl); -// -// String currValue = (String) fWorkingValues.get(key); -// comboBox.select(data.getSelection(currValue)); -// -// fComboBoxes.add(comboBox); -// } - - protected Text addTextField(Composite parent, String label, String key, - int indent, int widthHint) { - Label labelControl = new Label(parent, SWT.NONE); - labelControl.setText(label); - labelControl.setLayoutData(new GridData()); - - Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); - textBox.setData(key); - textBox.setLayoutData(new GridData()); - - fLabels.put(textBox, labelControl); - - String currValue = (String) fWorkingValues.get(key); - if (currValue != null) { - textBox.setText(currValue); - } - textBox.addModifyListener(getTextModifyListener()); - - GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - if (widthHint != 0) { - data.widthHint = widthHint; - } - data.horizontalIndent = indent; - data.horizontalSpan = 2; - textBox.setLayoutData(data); - - fTextBoxes.add(textBox); - return textBox; - } - - protected SelectionListener getSelectionListener() { - if (fSelectionListener == null) { - fSelectionListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - controlChanged(e.widget); - } - }; - } - return fSelectionListener; - } - - protected ModifyListener getTextModifyListener() { - if (fTextModifyListener == null) { - fTextModifyListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - textChanged((Text) e.widget); - } - }; - } - return fTextModifyListener; - } - - protected void controlChanged(Widget widget) { - ControlData data = (ControlData) widget.getData(); - String newValue = null; - if (widget instanceof Button) { - newValue = data.getValue(((Button) widget).getSelection()); - } else if (widget instanceof Combo) { - newValue = data.getValue(((Combo) widget).getSelectionIndex()); - } else { - return; - } - fWorkingValues.put(data.getKey(), newValue); - - validateSettings(data.getKey(), newValue); - } - - protected void textChanged(Text textControl) { - String key = (String) textControl.getData(); - String number = textControl.getText(); - fWorkingValues.put(key, number); - validateSettings(key, number); - } - -// protected boolean checkValue(String key, String value) { -// return value.equals(fWorkingValues.get(key)); -// } - - /* - * (non-javadoc) Update fields and validate. @param changedKey Key that - * changed, or null, if all changed. - */ - protected abstract void validateSettings(String changedKey, String newValue); - - protected String[] getTokens(String text, String separator) { - StringTokenizer tok = new StringTokenizer(text, separator); //$NON-NLS-1$ - int nTokens = tok.countTokens(); - String[] res = new String[nTokens]; - for (int i = 0; i < res.length; i++) { - res[i] = tok.nextToken().trim(); - } - return res; - } - - public boolean performOk(boolean enabled) { - String[] allKeys = fAllKeys; - Map actualOptions = getOptions(false); - - // preserve other options - boolean hasChanges = false; - for (int i = 0; i < allKeys.length; i++) { - String key = allKeys[i]; - String oldVal = (String) actualOptions.get(key); - String val = null; - if (enabled) { - val = (String) fWorkingValues.get(key); - if (val != null && !val.equals(oldVal)) { - hasChanges = true; - actualOptions.put(key, val); - } - } else { - if (oldVal != null) { - actualOptions.remove(key); - hasChanges = true; - } - } - } - - if (hasChanges) { - boolean doBuild = false; - String[] strings = getFullBuildDialogStrings(fProject == null); - if (strings != null) { - MessageDialog dialog = new MessageDialog(getShell(), - strings[0], null, strings[1], MessageDialog.QUESTION, - new String[] { IDialogConstants.YES_LABEL, - IDialogConstants.NO_LABEL, - IDialogConstants.CANCEL_LABEL }, 2); - int res = dialog.open(); - if (res == 0) { - doBuild = true; - } else if (res != 1) { - return false; // cancel pressed - } - } - setOptions(actualOptions); - if (doBuild) { - boolean res = doFullBuild(); - if (!res) { - return false; - } - } - } - return true; - } - - protected abstract String[] getFullBuildDialogStrings( - boolean workspaceSettings); - - protected boolean doFullBuild() { - - Job buildJob = new Job(PreferencesMessages - .getString("OptionsConfigurationBlock.job.title")) { //$NON-NLS-1$ - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) - */ - protected IStatus run(IProgressMonitor monitor) { - try { - if (fProject != null) { - monitor - .setTaskName(PreferencesMessages - .getFormattedString( - "OptionsConfigurationBlock.buildproject.taskname", fProject.getElementName())); //$NON-NLS-1$ - fProject.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, - new SubProgressMonitor(monitor, 1)); - WebUI.getWorkspace().build( - IncrementalProjectBuilder.INCREMENTAL_BUILD, - new SubProgressMonitor(monitor, 1)); - } else { - monitor - .setTaskName(PreferencesMessages - .getString("OptionsConfigurationBlock.buildall.taskname")); //$NON-NLS-1$ - WebUI.getWorkspace().build( - IncrementalProjectBuilder.FULL_BUILD, - new SubProgressMonitor(monitor, 2)); - } - } catch (CoreException e) { - return e.getStatus(); - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } finally { - monitor.done(); - } - return Status.OK_STATUS; - } - - public boolean belongsTo(Object family) { - return ResourcesPlugin.FAMILY_MANUAL_BUILD == family; - } - }; - - buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory() - .buildRule()); - buildJob.setUser(true); - buildJob.schedule(); - return true; - } - - public void performDefaults() { - fWorkingValues = getDefaultOptions(); - updateControls(); - validateSettings(null, null); - } - - protected void updateControls() { - // update the UI - for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { - updateCheckBox((Button) fCheckBoxes.get(i)); - } - for (int i = fComboBoxes.size() - 1; i >= 0; i--) { - updateCombo((Combo) fComboBoxes.get(i)); - } - for (int i = fTextBoxes.size() - 1; i >= 0; i--) { - updateText((Text) fTextBoxes.get(i)); - } - } - - protected void updateCombo(Combo curr) { - ControlData data = (ControlData) curr.getData(); - - String currValue = (String) fWorkingValues.get(data.getKey()); - curr.select(data.getSelection(currValue)); - } - - protected void updateCheckBox(Button curr) { - ControlData data = (ControlData) curr.getData(); - - String currValue = (String) fWorkingValues.get(data.getKey()); - curr.setSelection(data.getSelection(currValue) == 0); - } - - protected void updateText(Text curr) { - String key = (String) curr.getData(); - - String currValue = (String) fWorkingValues.get(key); - if (currValue != null) { - curr.setText(currValue); - } - } - -// protected Button getCheckBox(String key) { -// for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { -// Button curr = (Button) fCheckBoxes.get(i); -// ControlData data = (ControlData) curr.getData(); -// if (key.equals(data.getKey())) { -// return curr; -// } -// } -// return null; -// } - - protected Combo getComboBox(String key) { - for (int i = fComboBoxes.size() - 1; i >= 0; i--) { - Combo curr = (Combo) fComboBoxes.get(i); - ControlData data = (ControlData) curr.getData(); - if (key.equals(data.getKey())) { - return curr; - } - } - return null; - } - -// protected void setComboEnabled(String key, boolean enabled) { -// Combo combo = getComboBox(key); -// Label label = (Label) fLabels.get(combo); -// combo.setEnabled(enabled); -// label.setEnabled(enabled); -// } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java deleted file mode 100644 index 8f7010b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/** - * Preference page for spell checking preferences. - * - * @since 3.0 - */ -public class SpellingPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage, IStatusChangeListener { - - /** The spelling configuration block */ - private final SpellingConfigurationBlock fBlock = new SpellingConfigurationBlock( - this, null); - - /** - * Creates a new spelling preference page. - */ - public SpellingPreferencePage() { - - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - setDescription(PreferencesMessages - .getString("SpellingPreferencePage.description")); //$NON-NLS-1$ - setTitle(PreferencesMessages.getString("SpellingPreferencePage.title")); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) - */ - protected Control createContents(final Composite parent) { - - final Control control = fBlock.createContents(parent); - Dialog.applyDialogFont(control); - - return control; - } - - /* - * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(final Composite parent) { - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - /* - * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(final IWorkbench workbench) { - // Do nothing - } - - /* - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - protected void performDefaults() { - fBlock.performDefaults(); - - super.performDefaults(); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - - if (!fBlock.performOk(true)) - return false; - - return super.performOk(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) - */ - public void statusChanged(final IStatus status) { - setValid(!status.matches(IStatus.ERROR)); - - StatusUtil.applyToStatusLine(this, status); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java deleted file mode 100644 index 439288a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import java.util.Iterator; - -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; -import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.IColorManager; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.jface.text.templates.TemplateVariableResolver; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.ui.texteditor.ITextEditor; - -public class TemplateEditorSourceViewerConfiguration extends - PHPSourceViewerConfiguration { - - private static class TemplateVariableTextHover implements ITextHover { - - private TemplateVariableProcessor fProcessor; - - /** - * @param type - */ - public TemplateVariableTextHover(TemplateVariableProcessor processor) { - fProcessor = processor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, - * org.eclipse.jface.text.IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion subject) { - try { - IDocument doc = textViewer.getDocument(); - int offset = subject.getOffset(); - if (offset >= 2 && "${".equals(doc.get(offset - 2, 2))) { //$NON-NLS-1$ - String varName = doc.get(offset, subject.getLength()); - TemplateContextType contextType = fProcessor - .getContextType(); - if (contextType != null) { - Iterator iter = contextType.resolvers(); - while (iter.hasNext()) { - TemplateVariableResolver var = (TemplateVariableResolver) iter - .next(); - if (varName.equals(var.getType())) { - return var.getDescription(); - } - } - } - } - } catch (BadLocationException e) { - } - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - if (textViewer != null) { - return JavaWordFinder - .findWord(textViewer.getDocument(), offset); - } - return null; - } - - } - - private final TemplateVariableProcessor fProcessor; - - public TemplateEditorSourceViewerConfiguration(IColorManager colorManager, - IPreferenceStore store, ITextEditor editor, - TemplateVariableProcessor processor) { - super(colorManager, store, editor, IPHPPartitions.PHP_PARTITIONING); - fProcessor = processor; - } - - /* - * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) - */ - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - JavaTextTools textTools = WebUI.getDefault() - .getJavaTextTools(); - IColorManager manager = textTools.getColorManager(); - - ContentAssistant assistant = new ContentAssistant(); - assistant.setContentAssistProcessor(fProcessor, - IDocument.DEFAULT_CONTENT_TYPE); - // Register the same processor for strings and single line comments to - // get code completion at the start of those partitions. - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_STRING_DQ); - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_STRING_SQ); - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_STRING_HEREDOC); - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_SINGLELINE_COMMENT); - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_MULTILINE_COMMENT); - assistant.setContentAssistProcessor(fProcessor, - IPHPPartitions.PHP_PHPDOC_COMMENT); - - assistant.enableAutoInsert(store - .getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); - assistant.enableAutoActivation(store - .getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); - assistant.setAutoActivationDelay(store - .getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); - assistant - .setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); - assistant - .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); - assistant - .setInformationControlCreator(getInformationControlCreator(sourceViewer)); - - Color background = getColor(store, - PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); - assistant.setContextInformationPopupBackground(background); - assistant.setContextSelectorBackground(background); - assistant.setProposalSelectorBackground(background); - - Color foreground = getColor(store, - PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); - assistant.setContextInformationPopupForeground(foreground); - assistant.setContextSelectorForeground(foreground); - assistant.setProposalSelectorForeground(foreground); - - return assistant; - } - - private Color getColor(IPreferenceStore store, String key, - IColorManager manager) { - RGB rgb = PreferenceConverter.getColor(store, key); - return manager.getColor(rgb); - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) - * @since 2.1 - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, - String contentType, int stateMask) { - return new TemplateVariableTextHover(fProcessor); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java deleted file mode 100644 index 3667bdc..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.preferences; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; -import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; - -/* - * The page to configure the compiler options. - */ -public class TodoTaskPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage, IStatusChangeListener { - - public static final String ID = "net.sourceforge.phpdt.ui.preferences.TodoTaskPreferencePage"; //$NON-NLS-1$ - - private TodoTaskConfigurationBlock fConfigurationBlock; - - public TodoTaskPreferencePage() { - setPreferenceStore(WebUI.getDefault().getPreferenceStore()); - // setDescription(PreferencesMessages.getString("TodoTaskPreferencePage.description")); - // //$NON-NLS-1$ - - // only used when page is shown programatically - setTitle(PreferencesMessages.getString("TodoTaskPreferencePage.title")); //$NON-NLS-1$ - - fConfigurationBlock = new TodoTaskConfigurationBlock(this, null); - } - - /* - * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all - // preference pages - super.createControl(parent); - PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), - IJavaHelpContextIds.TODOTASK_PREFERENCE_PAGE); - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - Control result = fConfigurationBlock.createContents(parent); - Dialog.applyDialogFont(result); - return result; - } - - /* - * @see IPreferencePage#performOk() - */ - public boolean performOk() { - if (!fConfigurationBlock.performOk(true)) { - return false; - } - return super.performOk(); - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fConfigurationBlock.performDefaults(); - super.performDefaults(); - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) - */ - public void statusChanged(IStatus status) { - setValid(!status.matches(IStatus.ERROR)); - StatusUtil.applyToStatusLine(this, status); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java deleted file mode 100644 index 1b70289..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text; - -import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCompletionProcessor; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.IColorManager; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.HTMLCompletionProcessor; -import net.sourceforge.phpeclipse.phpeditor.php.PHPCompletionProcessor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; - -public class ContentAssistPreference { - - /** Preference key for content assist auto activation */ - private final static String AUTOACTIVATION = PreferenceConstants.CODEASSIST_AUTOACTIVATION; - - /** Preference key for content assist auto activation delay */ - private final static String AUTOACTIVATION_DELAY = PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY; - - /** Preference key for content assist proposal color */ - private final static String PROPOSALS_FOREGROUND = PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND; - - /** Preference key for content assist proposal color */ - private final static String PROPOSALS_BACKGROUND = PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND; - - /** Preference key for content assist parameters color */ - private final static String PARAMETERS_FOREGROUND = PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND; - - /** Preference key for content assist parameters color */ - private final static String PARAMETERS_BACKGROUND = PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND; - - /** Preference key for content assist completion replacement color */ - //private final static String COMPLETION_REPLACEMENT_FOREGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND; - - /** Preference key for content assist completion replacement color */ - //private final static String COMPLETION_REPLACEMENT_BACKGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND; - - /** Preference key for content assist auto insert */ - private final static String AUTOINSERT = PreferenceConstants.CODEASSIST_AUTOINSERT; - - /** Preference key for php content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_JAVA = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA; - - /** Preference key for phpdoc content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_JAVADOC = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC; - - /** Preference key for html content assist auto activation triggers */ - private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; - - /** Preference key for visibility of proposals */ - //private final static String SHOW_VISIBLE_PROPOSALS = PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS; - - /** Preference key for alphabetic ordering of proposals */ - private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; - - /** Preference key for case sensitivity of propsals */ - private final static String CASE_SENSITIVITY = PreferenceConstants.CODEASSIST_CASE_SENSITIVITY; - - /** Preference key for adding imports on code assist */ - //private final static String ADD_IMPORT = PreferenceConstants.CODEASSIST_ADDIMPORT; - - /** Preference key for inserting content assist */ - //private static final String INSERT_COMPLETION = PreferenceConstants.CODEASSIST_INSERT_COMPLETION; - - /** Preference key for filling argument names on method completion */ - //private static final String FILL_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES; - - /** Preference key for guessing argument names on method completion */ - //private static final String GUESS_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS; - - private static Color getColor(IPreferenceStore store, String key, - IColorManager manager) { - RGB rgb = PreferenceConverter.getColor(store, key); - return manager.getColor(rgb); - } - - private static Color getColor(IPreferenceStore store, String key) { - JavaTextTools textTools = WebUI.getDefault() - .getJavaTextTools(); - return getColor(store, key, textTools.getColorManager()); - } - - private static PHPCompletionProcessor getJavaProcessor( - ContentAssistant assistant) { - IContentAssistProcessor p = assistant - .getContentAssistProcessor(IPHPPartitions.PHP_PARTITIONING); - if (p instanceof PHPCompletionProcessor) - return (PHPCompletionProcessor) p; - return null; - } - - private static PHPDocCompletionProcessor getJavaDocProcessor( - ContentAssistant assistant) { - IContentAssistProcessor p = assistant - .getContentAssistProcessor(IPHPPartitions.PHP_PHPDOC_COMMENT); - if (p instanceof PHPDocCompletionProcessor) - return (PHPDocCompletionProcessor) p; - return null; - } - - private static HTMLCompletionProcessor getHTMLProcessor( - ContentAssistant assistant) { - IContentAssistProcessor p = assistant - .getContentAssistProcessor(IPHPPartitions.HTML); - if (p instanceof HTMLCompletionProcessor) - return (HTMLCompletionProcessor) p; - return null; - } - - private static void configureJavaProcessor(ContentAssistant assistant, - IPreferenceStore store) { - PHPCompletionProcessor pcp = getJavaProcessor(assistant); - if (pcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); - if (triggers != null) - pcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - boolean enabled; - // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); - // jcp.restrictProposalsToVisibility(enabled); - // - // enabled= store.getBoolean(CASE_SENSITIVITY); - // jcp.restrictProposalsToMatchingCases(enabled); - // - enabled = store.getBoolean(ORDER_PROPOSALS); - pcp.orderProposalsAlphabetically(enabled); - // - // enabled= store.getBoolean(ADD_IMPORT); - // jcp.allowAddingImports(enabled); - } - - private static void configureJavaDocProcessor(ContentAssistant assistant, - IPreferenceStore store) { - PHPDocCompletionProcessor pdcp = getJavaDocProcessor(assistant); - if (pdcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); - if (triggers != null) - pdcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - - boolean enabled = store.getBoolean(CASE_SENSITIVITY); - pdcp.restrictProposalsToMatchingCases(enabled); - - enabled = store.getBoolean(ORDER_PROPOSALS); - pdcp.orderProposalsAlphabetically(enabled); - } - - private static void configureHTMLProcessor(ContentAssistant assistant, - IPreferenceStore store) { - HTMLCompletionProcessor hcp = getHTMLProcessor(assistant); - if (hcp == null) - return; - - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - hcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - - boolean enabled; - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - - enabled = store.getBoolean(ORDER_PROPOSALS); - hcp.orderProposalsAlphabetically(enabled); - } - - /** - * Configure the given content assistant from the given store. - */ - public static void configure(ContentAssistant assistant, - IPreferenceStore store) { - - JavaTextTools textTools = WebUI.getDefault() - .getJavaTextTools(); - IColorManager manager = textTools.getColorManager(); - - boolean enabled = store.getBoolean(AUTOACTIVATION); - assistant.enableAutoActivation(enabled); - - int delay = store.getInt(AUTOACTIVATION_DELAY); - assistant.setAutoActivationDelay(delay); - - Color c = getColor(store, PROPOSALS_FOREGROUND, manager); - assistant.setProposalSelectorForeground(c); - - c = getColor(store, PROPOSALS_BACKGROUND, manager); - assistant.setProposalSelectorBackground(c); - - c = getColor(store, PARAMETERS_FOREGROUND, manager); - assistant.setContextInformationPopupForeground(c); - assistant.setContextSelectorForeground(c); - - c = getColor(store, PARAMETERS_BACKGROUND, manager); - assistant.setContextInformationPopupBackground(c); - assistant.setContextSelectorBackground(c); - - enabled = store.getBoolean(AUTOINSERT); - assistant.enableAutoInsert(enabled); - - configureJavaProcessor(assistant, store); - configureJavaDocProcessor(assistant, store); - configureHTMLProcessor(assistant, store); - } - - private static void changeJavaProcessor(ContentAssistant assistant, - IPreferenceStore store, String key) { - PHPCompletionProcessor jcp = getJavaProcessor(assistant); - if (jcp == null) - return; - - if (AUTOACTIVATION_TRIGGERS_JAVA.equals(key)) { - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); - if (triggers != null) - jcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - } - // else if (SHOW_VISIBLE_PROPOSALS.equals(key)) { - // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); - // jcp.restrictProposalsToVisibility(enabled); - // } else if (CASE_SENSITIVITY.equals(key)) { - // boolean enabled= store.getBoolean(CASE_SENSITIVITY); - // jcp.restrictProposalsToMatchingCases(enabled); } - else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jcp.orderProposalsAlphabetically(enable); - // } else if (ADD_IMPORT.equals(key)) { - // boolean enabled= store.getBoolean(ADD_IMPORT); - // jcp.allowAddingImports(enabled); - } - } - - private static void changeJavaDocProcessor(ContentAssistant assistant, - IPreferenceStore store, String key) { - PHPDocCompletionProcessor jdcp = getJavaDocProcessor(assistant); - if (jdcp == null) - return; - - if (AUTOACTIVATION_TRIGGERS_JAVADOC.equals(key)) { - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); - if (triggers != null) - jdcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - } else if (CASE_SENSITIVITY.equals(key)) { - boolean enabled = store.getBoolean(CASE_SENSITIVITY); - jdcp.restrictProposalsToMatchingCases(enabled); - } else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jdcp.orderProposalsAlphabetically(enable); - } - } - - private static void changeHTMLProcessor(ContentAssistant assistant, - IPreferenceStore store, String key) { - HTMLCompletionProcessor jdcp = getHTMLProcessor(assistant); - if (jdcp == null) - return; - - if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { - String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); - if (triggers != null) - jdcp.setCompletionProposalAutoActivationCharacters(triggers - .toCharArray()); - // } else if (CASE_SENSITIVITY.equals(key)) { - // boolean enabled = store.getBoolean(CASE_SENSITIVITY); - // jdcp.restrictProposalsToMatchingCases(enabled); - } else if (ORDER_PROPOSALS.equals(key)) { - boolean enable = store.getBoolean(ORDER_PROPOSALS); - jdcp.orderProposalsAlphabetically(enable); - } - } - - /** - * Changes the configuration of the given content assistant according to the - * given property change event and the given preference store. - */ - public static void changeConfiguration(ContentAssistant assistant, - IPreferenceStore store, PropertyChangeEvent event) { - - String p = event.getProperty(); - - if (AUTOACTIVATION.equals(p)) { - boolean enabled = store.getBoolean(AUTOACTIVATION); - assistant.enableAutoActivation(enabled); - } else if (AUTOACTIVATION_DELAY.equals(p)) { - int delay = store.getInt(AUTOACTIVATION_DELAY); - assistant.setAutoActivationDelay(delay); - } else if (PROPOSALS_FOREGROUND.equals(p)) { - Color c = getColor(store, PROPOSALS_FOREGROUND); - assistant.setProposalSelectorForeground(c); - } else if (PROPOSALS_BACKGROUND.equals(p)) { - Color c = getColor(store, PROPOSALS_BACKGROUND); - assistant.setProposalSelectorBackground(c); - } else if (PARAMETERS_FOREGROUND.equals(p)) { - Color c = getColor(store, PARAMETERS_FOREGROUND); - assistant.setContextInformationPopupForeground(c); - assistant.setContextSelectorForeground(c); - } else if (PARAMETERS_BACKGROUND.equals(p)) { - Color c = getColor(store, PARAMETERS_BACKGROUND); - assistant.setContextInformationPopupBackground(c); - assistant.setContextSelectorBackground(c); - } else if (AUTOINSERT.equals(p)) { - boolean enabled = store.getBoolean(AUTOINSERT); - assistant.enableAutoInsert(enabled); - } - - changeJavaProcessor(assistant, store, p); - changeJavaDocProcessor(assistant, store, p); - changeHTMLProcessor(assistant, store, p); - } - -// public static boolean fillArgumentsOnMethodCompletion(IPreferenceStore store) { -// return store.getBoolean(FILL_METHOD_ARGUMENTS); -// } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java deleted file mode 100644 index 4e6b8a7..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java +++ /dev/null @@ -1,196 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.text; - -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Iterator; - -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.widgets.Display; - -public class HTMLTextPresenter implements - DefaultInformationControl.IInformationPresenter { - - private static final String LINE_DELIM = System.getProperty( - "line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - - private int fCounter; - - private boolean fEnforceUpperLineLimit; - - public HTMLTextPresenter(boolean enforceUpperLineLimit) { - super(); - fEnforceUpperLineLimit = enforceUpperLineLimit; - } - -// public HTMLTextPresenter() { -// this(true); -// } - - protected Reader createReader(String hoverInfo, - TextPresentation presentation) { - return new HTML2TextReader(new StringReader(hoverInfo), presentation); - } - - protected void adaptTextPresentation(TextPresentation presentation, - int offset, int insertLength) { - - int yoursStart = offset; - int yoursEnd = offset + insertLength - 1; - yoursEnd = Math.max(yoursStart, yoursEnd); - - Iterator e = presentation.getAllStyleRangeIterator(); - while (e.hasNext()) { - - StyleRange range = (StyleRange) e.next(); - - int myStart = range.start; - int myEnd = range.start + range.length - 1; - myEnd = Math.max(myStart, myEnd); - - if (myEnd < yoursStart) - continue; - - if (myStart < yoursStart) - range.length += insertLength; - else - range.start += insertLength; - } - } - - private void append(StringBuffer buffer, String string, - TextPresentation presentation) { - - int length = string.length(); - buffer.append(string); - - if (presentation != null) - adaptTextPresentation(presentation, fCounter, length); - - fCounter += length; - } - - private String getIndent(String line) { - int length = line.length(); - - int i = 0; - while (i < length && Character.isWhitespace(line.charAt(i))) - ++i; - - return (i == length ? line : line.substring(0, i)) + " "; //$NON-NLS-1$ - } - - /* - * @see IHoverInformationPresenter#updatePresentation(Display display, - * String, TextPresentation, int, int) - */ - public String updatePresentation(Display display, String hoverInfo, - TextPresentation presentation, int maxWidth, int maxHeight) { - - if (hoverInfo == null) - return null; - - GC gc = new GC(display); - try { - - StringBuffer buffer = new StringBuffer(); - int maxNumberOfLines = Math.round(maxHeight - / gc.getFontMetrics().getHeight()); - - fCounter = 0; - LineBreakingReader reader = new LineBreakingReader(createReader( - hoverInfo, presentation), gc, maxWidth); - - boolean lastLineFormatted = false; - String lastLineIndent = null; - - String line = reader.readLine(); - boolean lineFormatted = reader.isFormattedLine(); - boolean firstLineProcessed = false; - - while (line != null) { - - if (fEnforceUpperLineLimit && maxNumberOfLines <= 0) - break; - - if (firstLineProcessed) { - if (!lastLineFormatted) - append(buffer, LINE_DELIM, null); - else { - append(buffer, LINE_DELIM, presentation); - if (lastLineIndent != null) - append(buffer, lastLineIndent, presentation); - } - } - - append(buffer, line, null); - firstLineProcessed = true; - - lastLineFormatted = lineFormatted; - if (!lineFormatted) - lastLineIndent = null; - else if (lastLineIndent == null) - lastLineIndent = getIndent(line); - - line = reader.readLine(); - lineFormatted = reader.isFormattedLine(); - - maxNumberOfLines--; - } - - if (line != null) { - append(buffer, LINE_DELIM, lineFormatted ? presentation : null); - append(buffer, PHPUIMessages - .getString("HTMLTextPresenter.ellipsis"), presentation); //$NON-NLS-1$ - } - - return trim(buffer, presentation); - - } catch (IOException e) { - - WebUI.log(e); - return null; - - } finally { - gc.dispose(); - } - } - - private String trim(StringBuffer buffer, TextPresentation presentation) { - - int length = buffer.length(); - - int end = length - 1; - while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) - --end; - - if (end == -1) - return ""; //$NON-NLS-1$ - - if (end < length - 1) - buffer.delete(end + 1, length); - else - end = length; - - int start = 0; - while (start < end && Character.isWhitespace(buffer.charAt(start))) - ++start; - - buffer.delete(0, start); - presentation.setResultWindow(new Region(start, buffer.length())); - return buffer.toString(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java deleted file mode 100644 index 77423a6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java +++ /dev/null @@ -1,152 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text; - -import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension; -import net.sourceforge.phpdt.internal.ui.text.java.JavaReconcilingStrategy; -import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Reconciling strategy for Java code. This is a composite strategy containing - * the regular java model reconciler and the comment spell checking strategy. - * - * @since 3.0 - */ -public class JavaCompositeReconcilingStrategy extends - CompositeReconcilingStrategy { - - private ITextEditor fEditor; - - private JavaReconcilingStrategy fJavaStrategy; - - /** - * Creates a new Java reconciling strategy. - * - * @param editor - * the editor of the strategy's reconciler - * @param documentPartitioning - * the document partitioning this strategy uses for configuration - */ - public JavaCompositeReconcilingStrategy(ITextEditor editor, - String documentPartitioning) { - fEditor = editor; - fJavaStrategy = new JavaReconcilingStrategy(editor); - setReconcilingStrategies(new IReconcilingStrategy[] { - fJavaStrategy, - new SpellReconcileStrategy(editor, documentPartitioning, - PreferenceConstants.getPreferenceStore()) }); - } - - /** - * Returns the problem requestor for the editor's input element. - * - * @return the problem requestor for the editor's input element - */ - private IProblemRequestorExtension getProblemRequestorExtension() { - IDocumentProvider p = fEditor.getDocumentProvider(); - if (p == null) { - try { - // work around for - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522 - p = WebUI.getDefault() - .getCompilationUnitDocumentProvider(); - } catch (NullPointerException npe) { - return null; - } - } - IAnnotationModel m = p.getAnnotationModel(fEditor.getEditorInput()); - if (m instanceof IProblemRequestorExtension) - return (IProblemRequestorExtension) m; - return null; - } - - /* - * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - IProblemRequestorExtension e = getProblemRequestorExtension(); - if (e != null) { - try { - e.beginReportingSequence(); - super.reconcile(dirtyRegion, subRegion); - } finally { - e.endReportingSequence(); - } - } else { - super.reconcile(dirtyRegion, subRegion); - } - } - - /* - * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion) - */ - public void reconcile(IRegion partition) { - IProblemRequestorExtension e = getProblemRequestorExtension(); - if (e != null) { - try { - e.beginReportingSequence(); - super.reconcile(partition); - } finally { - e.endReportingSequence(); - } - } else { - super.reconcile(partition); - } - } - - /** - * Tells this strategy whether to inform its listeners. - * - * @param notify - * true if listeners should be notified - */ - public void notifyListeners(boolean notify) { - fJavaStrategy.notifyListeners(notify); - } - - /* - * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#initialReconcile() - */ - public void initialReconcile() { - IProblemRequestorExtension e = getProblemRequestorExtension(); - if (e != null) { - try { - e.beginReportingSequence(); - super.initialReconcile(); - } finally { - e.endReportingSequence(); - } - } else { - super.initialReconcile(); - } - } - - /** - * Called before reconciling is started. - * - * @since 3.0 - */ - public void aboutToBeReconciled() { - fJavaStrategy.aboutToBeReconciled(); - - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java deleted file mode 100644 index 0a1c9a2..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java +++ /dev/null @@ -1,1521 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text; - -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.Plugin; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; - -/** - * Uses the {@link net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner}to - * get the indentation level for a certain position in a document. - * - *

- * An instance holds some internal position in the document and is therefore not - * threadsafe. - *

- * - * @since 3.0 - */ -public class JavaIndenter { - - /** The document being scanned. */ - private IDocument fDocument; - - /** The indentation accumulated by findPreviousIndenationUnit. */ - private int fIndent; - - /** - * The absolute (character-counted) indentation offset for special cases - * (method defs, array initializers) - */ - private int fAlign; - - /** The stateful scanposition for the indentation methods. */ - private int fPosition; - - /** The previous position. */ - private int fPreviousPos; - - /** The most recent token. */ - private int fToken; - - /** The line of fPosition. */ - private int fLine; - - /** - * The scanner we will use to scan the document. It has to be installed on - * the same document as the one we get. - */ - private JavaHeuristicScanner fScanner; - - /** - * Creates a new instance. - * - * @param document - * the document to scan - * @param scanner - * the {@link JavaHeuristicScanner} to be used for scanning the - * document. It must be installed on the same - * IDocument. - */ - public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) { - Assert.isNotNull(document); - Assert.isNotNull(scanner); - fDocument = document; - fScanner = scanner; - } - - /** - * Computes the indentation at the reference point of position. - * - * @param offset - * the offset in the document - * @return a String which reflects the indentation at the line in which the - * reference position to offset resides, or - * null if it cannot be determined - */ -// public StringBuffer getReferenceIndentation(int offset) { -// return getReferenceIndentation(offset, false); -// } - - /** - * Computes the indentation at the reference point of position. - * - * @param offset - * the offset in the document - * @param assumeOpeningBrace - * true if an opening brace should be assumed - * @return a String which reflects the indentation at the line in which the - * reference position to offset resides, or - * null if it cannot be determined - */ - private StringBuffer getReferenceIndentation(int offset, - boolean assumeOpeningBrace) { - - int unit; - if (assumeOpeningBrace) - unit = findReferencePosition(offset, Symbols.TokenLBRACE); - else - unit = findReferencePosition(offset, peekChar(offset)); - - // if we were unable to find anything, return null - if (unit == JavaHeuristicScanner.NOT_FOUND) - return null; - - return getLeadingWhitespace(unit); - - } - - /** - * Computes the indentation at offset. - * - * @param offset - * the offset in the document - * @return a String which reflects the correct indentation for the line in - * which offset resides, or null if it cannot be - * determined - */ - public StringBuffer computeIndentation(int offset) { - return computeIndentation(offset, false); - } - - /** - * Computes the indentation at offset. - * - * @param offset - * the offset in the document - * @param assumeOpeningBrace - * true if an opening brace should be assumed - * @return a String which reflects the correct indentation for the line in - * which offset resides, or null if it cannot be - * determined - */ - public StringBuffer computeIndentation(int offset, - boolean assumeOpeningBrace) { - - StringBuffer indent = getReferenceIndentation(offset, - assumeOpeningBrace); - - // handle special alignment - if (fAlign != JavaHeuristicScanner.NOT_FOUND) { - try { - // a special case has been detected. - IRegion line = fDocument.getLineInformationOfOffset(fAlign); - int lineOffset = line.getOffset(); - return createIndent(lineOffset, fAlign); - } catch (BadLocationException e) { - return null; - } - } - - if (indent == null) - return null; - - // add additional indent - //indent.append(createIndent(fIndent)); - indent.insert(0, createIndent(fIndent)); - if (fIndent < 0) - unindent(indent); - - return indent; - } - - /** - * Returns the indentation of the line at offset as a - * StringBuffer. If the offset is not valid, the empty - * string is returned. - * - * @param offset - * the offset in the document - * @return the indentation (leading whitespace) of the line in which - * offset is located - */ - private StringBuffer getLeadingWhitespace(int offset) { - StringBuffer indent = new StringBuffer(); - try { - IRegion line = fDocument.getLineInformationOfOffset(offset); - int lineOffset = line.getOffset(); - int nonWS = fScanner.findNonWhitespaceForwardInAnyPartition( - lineOffset, lineOffset + line.getLength()); - indent.append(fDocument.get(lineOffset, nonWS - lineOffset)); - return indent; - } catch (BadLocationException e) { - return indent; - } - } - - /** - * Reduces indentation in indent by one indentation unit. - * - * @param indent - * the indentation to be modified - */ - private void unindent(StringBuffer indent) { - CharSequence oneIndent = createIndent(); - int i = indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$ - if (i != -1) { - indent.delete(i, i + oneIndent.length()); - } - } - - /** - * Creates an indentation string of the length indent - start + 1, - * consisting of the content in fDocument in the range - * [start, indent), with every character replaced by a space except for - * tabs, which are kept as such. - * - *

- * Every run of the number of spaces that make up a tab are replaced by a - * tab character. - *

- * - * @return the indentation corresponding to the document content specified - * by start and indent - */ - private StringBuffer createIndent(int start, int indent) { - final int tabLen = prefTabLength(); - StringBuffer ret = new StringBuffer(); - try { - int spaces = 0; - while (start < indent) { - - char ch = fDocument.getChar(start); - if (ch == '\t') { - ret.append('\t'); - spaces = 0; - } else if (tabLen == -1) { - ret.append(' '); - } else { - spaces++; - if (spaces == tabLen) { - ret.append('\t'); - spaces = 0; - } - } - - start++; - } - // remainder - if (spaces == tabLen) - ret.append('\t'); - else - while (spaces-- > 0) - ret.append(' '); - - } catch (BadLocationException e) { - } - - return ret; - } - - /** - * Creates a string that represents the given number of indents (can be - * spaces or tabs..) - * - * @param indent - * the requested indentation level. - * - * @return the indentation specified by indent - */ - public StringBuffer createIndent(int indent) { - StringBuffer oneIndent = createIndent(); - - StringBuffer ret = new StringBuffer(); - while (indent-- > 0) - ret.append(oneIndent); - - return ret; - } - - /** - * Creates a string that represents one indent (can be spaces or tabs..) - * - * @return one indentation - */ - private StringBuffer createIndent() { - // get a sensible default when running without the infrastructure for - // testing - StringBuffer oneIndent = new StringBuffer(); - // JavaCore plugin= JavaCore.getJavaCore(); - WebUI plugin = WebUI.getDefault(); - if (plugin == null) { - oneIndent.append('\t'); - } else { - if (JavaCore.SPACE - .equals(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) { - int tabLen = Integer - .parseInt(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE)); - for (int i = 0; i < tabLen; i++) - oneIndent.append(' '); - } else if (JavaCore.TAB - .equals(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - oneIndent.append('\t'); - else - oneIndent.append('\t'); // default - } - return oneIndent; - } - - /** - * Returns the reference position regarding to indentation for - * offset, or NOT_FOUND. This method calls - * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} - * where nextChar is the next character after - * offset. - * - * @param offset - * the offset for which the reference is computed - * @return the reference statement relative to which offset - * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} - */ -// public int findReferencePosition(int offset) { -// return findReferencePosition(offset, peekChar(offset)); -// } - - /** - * Peeks the next char in the document that comes after offset - * on the same line as offset. - * - * @param offset - * the offset into document - * @return the token symbol of the next element, or TokenEOF if there is - * none - */ - private int peekChar(int offset) { - if (offset < fDocument.getLength()) { - try { - IRegion line = fDocument.getLineInformationOfOffset(offset); - int lineOffset = line.getOffset(); - int next = fScanner.nextToken(offset, lineOffset - + line.getLength()); - return next; - } catch (BadLocationException e) { - } - } - return Symbols.TokenEOF; - } - - /** - * Returns the reference position regarding to indentation for - * position, or NOT_FOUND. - * - *

- * If peekNextChar is true, the next token - * after offset is read and taken into account when computing - * the indentation. Currently, if the next token is the first token on the - * line (i.e. only preceded by whitespace), the following tokens are - * specially handled: - *

    - *
  • switch labels are indented relative to the switch - * block
  • - *
  • opening curly braces are aligned correctly with the introducing code
  • - *
  • closing curly braces are aligned properly with the introducing code - * of the matching opening brace
  • - *
  • closing parenthesis' are aligned with their opening peer
  • - *
  • the else keyword is aligned with its if, - * anything else is aligned normally (i.e. with the base of any introducing - * statements).
  • - *
  • if there is no token on the same line after offset, - * the indentation is the same as for an else keyword
  • - *
- * - * @param offset - * the offset for which the reference is computed - * @param nextToken - * the next token to assume in the document - * @return the reference statement relative to which offset - * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} - */ - public int findReferencePosition(int offset, int nextToken) { - boolean danglingElse = false; - boolean unindent = false; - boolean indent = false; - boolean matchBrace = false; - boolean matchParen = false; - boolean matchCase = false; - - // account for unindenation characters already typed in, but after - // position - // if they are on a line by themselves, the indentation gets adjusted - // accordingly - // - // also account for a dangling else - if (offset < fDocument.getLength()) { - try { - IRegion line = fDocument.getLineInformationOfOffset(offset); - int lineOffset = line.getOffset(); - int prevPos = Math.max(offset - 1, 0); - boolean isFirstTokenOnLine = fDocument.get(lineOffset, - prevPos + 1 - lineOffset).trim().length() == 0; - int prevToken = fScanner.previousToken(prevPos, - JavaHeuristicScanner.UNBOUND); - if (prevToken == Symbols.TokenEOF && nextToken == Symbols.TokenEOF) { - ITypedRegion partition = TextUtilities.getPartition(fDocument, IPHPPartitions.PHP_PARTITIONING, offset, true); - if (partition.getType().equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { - fAlign = fScanner.getPosition(); - } else { - fAlign = JavaHeuristicScanner.NOT_FOUND; - } - return JavaHeuristicScanner.NOT_FOUND; - } - boolean bracelessBlockStart = fScanner.isBracelessBlockStart( - prevPos, JavaHeuristicScanner.UNBOUND); - - switch (nextToken) { - case Symbols.TokenEOF: - case Symbols.TokenELSE: - danglingElse = true; - break; - case Symbols.TokenCASE: - case Symbols.TokenDEFAULT: - if (isFirstTokenOnLine) - matchCase = true; - break; - case Symbols.TokenLBRACE: // for opening-brace-on-new-line - // style - // if (bracelessBlockStart && !prefIndentBracesForBlocks()) - // unindent= true; - // else if ((prevToken == Symbols.TokenCOLON || prevToken == - // Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && - // !prefIndentBracesForArrays()) - // unindent= true; - // else if (!bracelessBlockStart && - // prefIndentBracesForMethods()) - // indent= true; - // break; - if (bracelessBlockStart) - unindent = true; - else if ((prevToken == Symbols.TokenCOLON - || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET)) - unindent = true; - else if (!bracelessBlockStart) - indent = true; - break; - case Symbols.TokenRBRACE: // closing braces get unindented - if (isFirstTokenOnLine) - matchBrace = true; - break; - case Symbols.TokenRPAREN: - if (isFirstTokenOnLine) - matchParen = true; - break; - } - } catch (BadLocationException e) { - } - } else { - // assume an else could come if we are at the end of file - danglingElse = true; - } - - int ref = findReferencePosition(offset, danglingElse, matchBrace, - matchParen, matchCase); - if (unindent) - fIndent--; - if (indent) - fIndent++; - return ref; - } - - /** - * Returns the reference position regarding to indentation for - * position, or NOT_FOUND.fIndent - * will contain the relative indentation (in indentation units, not - * characters) after the call. If there is a special alignment (e.g. for a - * method declaration where parameters should be aligned), - * fAlign will contain the absolute position of the alignment - * reference in fDocument, otherwise fAlign - * is set to JavaHeuristicScanner.NOT_FOUND. - * - * @param offset - * the offset for which the reference is computed - * @param danglingElse - * whether a dangling else should be assumed at - * position - * @param matchBrace - * whether the position of the matching brace should be returned - * instead of doing code analysis - * @param matchParen - * whether the position of the matching parenthesis should be - * returned instead of doing code analysis - * @param matchCase - * whether the position of a switch statement reference should be - * returned (either an earlier case statement or the switch block - * brace) - * @return the reference statement relative to which position - * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} - */ - public int findReferencePosition(int offset, boolean danglingElse, - boolean matchBrace, boolean matchParen, boolean matchCase) { - fIndent = 0; // the indentation modification - fAlign = JavaHeuristicScanner.NOT_FOUND; - fPosition = offset; - - // forward cases - // an unindentation happens sometimes if the next token is special, - // namely on braces, parens and case labels - // align braces, but handle the case where we align with the method - // declaration start instead of - // the opening brace. - if (matchBrace) { - if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) { - try { - // align with the opening brace that is on a line by its own - int lineOffset = fDocument.getLineOffset(fLine); - if (lineOffset <= fPosition - && fDocument - .get(lineOffset, fPosition - lineOffset) - .trim().length() == 0) - return fPosition; - } catch (BadLocationException e) { - // concurrent modification - walk default path - } - // if the opening brace is not on the start of the line, skip to - // the start - int pos = skipToStatementStart(true, true); - fIndent = 0; // indent is aligned with reference position - return pos; - } else { - // if we can't find the matching brace, the heuristic is to - // unindent - // by one against the normal position - int pos = findReferencePosition(offset, danglingElse, false, - matchParen, matchCase); - fIndent--; - return pos; - } - } - - // align parenthesis' - if (matchParen) { - if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) - return fPosition; - else { - // if we can't find the matching paren, the heuristic is to - // unindent - // by one against the normal position - int pos = findReferencePosition(offset, danglingElse, - matchBrace, false, matchCase); - fIndent--; - return pos; - } - } - - // the only reliable way to get case labels aligned (due to many - // different styles of using braces in a block) - // is to go for another case statement, or the scope opening brace - if (matchCase) { - return matchCaseAlignment(); - } - - nextToken(); - switch (fToken) { - case Symbols.TokenRBRACE: - // skip the block and fall through - // if we can't complete the scope, reset the scan position - int pos = fPosition; - if (!skipScope()) - fPosition = pos; - case Symbols.TokenSEMICOLON: - // this is the 90% case: after a statement block - // the end of the previous statement / block previous.end - // search to the end of the statement / block before the previous; - // the token just after that is previous.start - return skipToStatementStart(danglingElse, false); - - // scope introduction: special treat who special is - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACE: - case Symbols.TokenLBRACKET: - return handleScopeIntroduction(offset + 1); - - case Symbols.TokenEOF: - // trap when hitting start of document - return 0; - - case Symbols.TokenEQUAL: - // indent assignments - fIndent = prefAssignmentIndent(); - return fPosition; - - case Symbols.TokenCOLON: - // TODO handle ternary deep indentation - fIndent = prefCaseBlockIndent(); - return fPosition; - - case Symbols.TokenQUESTIONMARK: - if (prefTernaryDeepAlign()) { - setFirstElementAlignment(fPosition, offset + 1); - return fPosition; - } else { - fIndent = prefTernaryIndent(); - return fPosition; - } - - // indentation for blockless introducers: - case Symbols.TokenDO: - case Symbols.TokenWHILE: - case Symbols.TokenELSE: - fIndent = prefSimpleIndent(); - return fPosition; - case Symbols.TokenRPAREN: - int line = fLine; - if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) { - int scope = fPosition; - nextToken(); - if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE - || fToken == Symbols.TokenFOR) { - fIndent = prefSimpleIndent(); - return fPosition; - } - fPosition = scope; - if (looksLikeMethodDecl()) { - return skipToStatementStart(danglingElse, false); - } - } - // restore - fPosition = offset; - fLine = line; - // else: fall through to default - - case Symbols.TokenCOMMA: - // inside a list of some type - // easy if there is already a list item before with its own - // indentation - we just align - // if not: take the start of the list ( LPAREN, LBRACE, LBRACKET ) - // and either align or - // indent by list-indent - default: - // inside whatever we don't know about: similar to the list case: - // if we are inside a continued expression, then either align with a - // previous line that has indentation - // or indent from the expression start line (either a scope - // introducer or the start of the expr). - return skipToPreviousListItemOrListStart(); - - } - } - - /** - * Skips to the start of a statement that ends at the current position. - * - * @param danglingElse - * whether to indent aligned with the last if - * @param isInBlock - * whether the current position is inside a block, which limits - * the search scope to the next scope introducer - * @return the reference offset of the start of the statement - */ - private int skipToStatementStart(boolean danglingElse, boolean isInBlock) { - while (true) { - nextToken(); - - if (isInBlock) { - switch (fToken) { - // exit on all block introducers - case Symbols.TokenIF: - case Symbols.TokenELSE: - case Symbols.TokenSYNCHRONIZED: - case Symbols.TokenCOLON: - case Symbols.TokenSTATIC: - case Symbols.TokenCATCH: - case Symbols.TokenDO: - case Symbols.TokenWHILE: - case Symbols.TokenFINALLY: - case Symbols.TokenFOR: - case Symbols.TokenTRY: - return fPosition; - - case Symbols.TokenSWITCH: - fIndent = prefCaseIndent(); - return fPosition; - } - } - - switch (fToken) { - // scope introduction through: LPAREN, LBRACE, LBRACKET - // search stop on SEMICOLON, RBRACE, COLON, EOF - // -> the next token is the start of the statement (i.e. previousPos - // when backward scanning) - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACE: - case Symbols.TokenLBRACKET: - case Symbols.TokenSEMICOLON: - case Symbols.TokenEOF: - return fPreviousPos; - - case Symbols.TokenCOLON: - int pos = fPreviousPos; - if (!isConditional()) - return pos; - break; - - case Symbols.TokenRBRACE: - // RBRACE is a little tricky: it can be the end of an array - // definition, but - // usually it is the end of a previous block - pos = fPreviousPos; // store state - if (skipScope() && looksLikeArrayInitializerIntro()) - continue; // it's an array - else - return pos; // it's not - do as with all the above - - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - pos = fPreviousPos; - if (skipScope()) - break; - else - return pos; - - // IF / ELSE: align the position after the conditional block - // with the if - // so we are ready for an else, except if danglingElse is false - // in order for this to work, we must skip an else to its if - case Symbols.TokenIF: - if (danglingElse) - return fPosition; - else - break; - case Symbols.TokenELSE: - // skip behind the next if, as we have that one covered - pos = fPosition; - if (skipNextIF()) - break; - else - return pos; - - case Symbols.TokenDO: - // align the WHILE position with its do - return fPosition; - - case Symbols.TokenWHILE: - // this one is tricky: while can be the start of a while loop - // or the end of a do - while - pos = fPosition; - if (hasMatchingDo()) { - // continue searching from the DO on - break; - } else { - // continue searching from the WHILE on - fPosition = pos; - break; - } - default: - // keep searching - - } - - } - } - - /** - * Returns true if the colon at the current position is part of a - * conditional (ternary) expression, false otherwise. - * - * @return true if the colon at the current position is part of a - * conditional - */ - private boolean isConditional() { - while (true) { - nextToken(); - switch (fToken) { - - // search for case, otherwise return true - case Symbols.TokenIDENT: - continue; - case Symbols.TokenCASE: - return false; - - default: - return true; - } - } - } - - /** - * Returns as a reference any previous switch labels (case - * or default) or the offset of the brace that scopes the - * switch statement. Sets fIndent to - * prefCaseIndent upon a match. - * - * @return the reference offset for a switch label - */ - private int matchCaseAlignment() { - while (true) { - nextToken(); - switch (fToken) { - // invalid cases: another case label or an LBRACE must come before a - // case - // -> bail out with the current position - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACKET: - case Symbols.TokenEOF: - return fPosition; - case Symbols.TokenLBRACE: - // opening brace of switch statement - fIndent = 1; //prefCaseIndent() is for Java - return fPosition; - case Symbols.TokenCASE: - case Symbols.TokenDEFAULT: - // align with previous label - fIndent = 0; - return fPosition; - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - case Symbols.TokenRBRACE: - skipScope(); - break; - default: - // keep searching - continue; - } - } - } - - /** - * Returns the reference position for a list element. The algorithm tries to - * match any previous indentation on the same list. If there is none, the - * reference position returned is determined depending on the type of list: - * The indentation will either match the list scope introducer (e.g. for - * method declarations), so called deep indents, or simply increase the - * indentation by a number of standard indents. See also - * {@link #handleScopeIntroduction(int)}. - * - * @return the reference position for a list item: either a previous list - * item that has its own indentation, or the list introduction - * start. - */ - private int skipToPreviousListItemOrListStart() { - int startLine = fLine; - int startPosition = fPosition; - while (true) { - nextToken(); - - // if any line item comes with its own indentation, adapt to it - if (fLine < startLine) { - try { - int lineOffset = fDocument.getLineOffset(startLine); - int bound = Math.min(fDocument.getLength(), - startPosition + 1); - fAlign = fScanner.findNonWhitespaceForwardInAnyPartition( - lineOffset, bound); - } catch (BadLocationException e) { - // ignore and return just the position - } - return startPosition; - } - - switch (fToken) { - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - case Symbols.TokenRBRACE: - skipScope(); - break; - - // scope introduction: special treat who special is - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACE: - case Symbols.TokenLBRACKET: - return handleScopeIntroduction(startPosition + 1); - - case Symbols.TokenSEMICOLON: - return fPosition; - case Symbols.TokenQUESTIONMARK: - if (prefTernaryDeepAlign()) { - setFirstElementAlignment(fPosition - 1, fPosition + 1); - } else { - fIndent = prefTernaryIndent(); - } - return fPosition; - case Symbols.TokenEOF: - return 0; - - case Symbols.TokenEQUAL: - // indent assignments - fIndent= prefAssignmentIndent(); - return fPosition; - } - } - } - - /** - * Skips a scope and positions the cursor (fPosition) on - * the token that opens the scope. Returns true if a matching - * peer could be found, false otherwise. The current token - * when calling must be one out of Symbols.TokenRPAREN, - * Symbols.TokenRBRACE, and - * Symbols.TokenRBRACKET. - * - * @return true if a matching peer was found, - * false otherwise - */ - private boolean skipScope() { - switch (fToken) { - case Symbols.TokenRPAREN: - return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN); - case Symbols.TokenRBRACKET: - return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET); - case Symbols.TokenRBRACE: - return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); - default: - Assert.isTrue(false); - return false; - } - } - - /** - * Handles the introduction of a new scope. The current token must be one - * out of Symbols.TokenLPAREN, - * Symbols.TokenLBRACE, and - * Symbols.TokenLBRACKET. Returns as the reference position - * either the token introducing the scope or - if available - the first java - * token after that. - * - *

- * Depending on the type of scope introduction, the indentation will align - * (deep indenting) with the reference position (fAlign will - * be set to the reference position) or fIndent will be set - * to the number of indentation units. - *

- * - * @param bound - * the bound for the search for the first token after the scope - * introduction. - * @return - */ - private int handleScopeIntroduction(int bound) { - switch (fToken) { - // scope introduction: special treat who special is - case Symbols.TokenLPAREN: - int pos = fPosition; // store - - // special: method declaration deep indentation - if (looksLikeMethodDecl()) { - if (prefMethodDeclDeepIndent()) - return setFirstElementAlignment(pos, bound); - else { - fIndent = prefMethodDeclIndent(); - return pos; - } - } else { - fPosition = pos; - if (looksLikeMethodCall()) { - if (prefMethodCallDeepIndent()) - return setFirstElementAlignment(pos, bound); - else { - fIndent = prefMethodCallIndent(); - return pos; - } - } else if (prefParenthesisDeepIndent()) - return setFirstElementAlignment(pos, bound); - } - - // normal: return the parenthesis as reference - fIndent = prefParenthesisIndent(); - return pos; - - case Symbols.TokenLBRACE: - pos = fPosition; // store - - // special: array initializer - if (looksLikeArrayInitializerIntro()) - if (prefArrayDeepIndent()) - return setFirstElementAlignment(pos, bound); - else - fIndent = prefArrayIndent(); - else - fIndent = prefBlockIndent(); - - // normal: skip to the statement start before the scope introducer - // opening braces are often on differently ending indents than e.g. - // a method definition - fPosition = pos; // restore - return skipToStatementStart(true, true); // set to true to match - // the first if - - case Symbols.TokenLBRACKET: - pos = fPosition; // store - - // special: method declaration deep indentation - if (prefArrayDimensionsDeepIndent()) { - return setFirstElementAlignment(pos, bound); - } - - // normal: return the bracket as reference - fIndent = prefBracketIndent(); - return pos; // restore - - default: - Assert.isTrue(false); - return -1; // dummy - } - } - - /** - * Sets the deep indent offset (fAlign) to either the - * offset right after scopeIntroducerOffset or - if available - - * the first Java token after scopeIntroducerOffset, but - * before bound. - * - * @param scopeIntroducerOffset - * the offset of the scope introducer - * @param bound - * the bound for the search for another element - * @return the reference position - */ - private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) { - int firstPossible = scopeIntroducerOffset + 1; // align with the first - // position after the - // scope intro - fAlign = fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, - bound); - if (fAlign == JavaHeuristicScanner.NOT_FOUND) - fAlign = firstPossible; - return fAlign; - } - - /** - * Returns true if the next token received after calling - * nextToken is either an equal sign or an array designator - * ('[]'). - * - * @return true if the next elements look like the start of - * an array definition - */ - private boolean looksLikeArrayInitializerIntro() { - nextToken(); - if (fToken == Symbols.TokenEQUAL || skipBrackets()) { - return true; - } - return false; - } - - /** - * Skips over the next if keyword. The current token when - * calling this method must be an else keyword. Returns - * true if a matching if could be found, - * false otherwise. The cursor (fPosition) - * is set to the offset of the if token. - * - * @return true if a matching if token was - * found, false otherwise - */ - private boolean skipNextIF() { - Assert.isTrue(fToken == Symbols.TokenELSE); - - while (true) { - nextToken(); - switch (fToken) { - // scopes: skip them - case Symbols.TokenRPAREN: - case Symbols.TokenRBRACKET: - case Symbols.TokenRBRACE: - skipScope(); - break; - - case Symbols.TokenIF: - // found it, return - return true; - case Symbols.TokenELSE: - // recursively skip else-if blocks - skipNextIF(); - break; - - // shortcut scope starts - case Symbols.TokenLPAREN: - case Symbols.TokenLBRACE: - case Symbols.TokenLBRACKET: - case Symbols.TokenEOF: - return false; - } - } - } - - /** - * while(condition); is ambiguous when parsed backwardly, as it is a valid - * statement by its own, so we have to check whether there is a matching do. - * A do can either be separated from the while by a block, or - * by a single statement, which limits our search distance. - * - * @return true if the while currently in - * fToken has a matching do. - */ - private boolean hasMatchingDo() { - Assert.isTrue(fToken == Symbols.TokenWHILE); - nextToken(); - switch (fToken) { - case Symbols.TokenRBRACE: - skipScope(); // and fall thru - case Symbols.TokenSEMICOLON: - skipToStatementStart(false, false); - return fToken == Symbols.TokenDO; - } - return false; - } - - /** - * Skips brackets if the current token is a RBRACKET. There can be nothing - * but whitespace in between, this is only to be used for [] - * elements. - * - * @return true if a [] could be scanned, the - * current token is left at the LBRACKET. - */ - private boolean skipBrackets() { - if (fToken == Symbols.TokenRBRACKET) { - nextToken(); - if (fToken == Symbols.TokenLBRACKET) { - return true; - } - } - return false; - } - - /** - * Reads the next token in backward direction from the heuristic scanner and - * sets the fields fToken, fPreviousPosition and - * fPosition accordingly. - */ - private void nextToken() { - nextToken(fPosition); - } - - /** - * Reads the next token in backward direction of start from - * the heuristic scanner and sets the fields - * fToken, fPreviousPosition and fPosition - * accordingly. - */ - private void nextToken(int start) { - fToken = fScanner - .previousToken(start - 1, JavaHeuristicScanner.UNBOUND); - fPreviousPos = start; - fPosition = fScanner.getPosition() + 1; - try { - fLine = fDocument.getLineOfOffset(fPosition); - } catch (BadLocationException e) { - fLine = -1; - } - } - - /** - * Returns true if the current tokens look like a method - * declaration header (i.e. only the return type and method name). The - * heuristic calls nextToken and expects an identifier - * (method name) and a type declaration (an identifier with optional - * brackets) which also covers the visibility modifier of constructors; it - * does not recognize package visible constructors. - * - * @return true if the current position looks like a method - * declaration header. - */ - private boolean looksLikeMethodDecl() { - /* - * TODO This heuristic does not recognize package private constructors - * since those do have neither type nor visibility keywords. One option - * would be to go over the parameter list, but that might be empty as - * well - hard to do without an AST... - */ - - nextToken(); - if (fToken == Symbols.TokenIDENT) { // method name - do - nextToken(); - while (skipBrackets()); // optional brackets for array valued return - // types - return fToken == Symbols.TokenIDENT; // type name - - } - return false; - } - - /** - * Returns true if the current tokens look like a method call - * header (i.e. an identifier as opposed to a keyword taking parenthesized - * parameters such as if). - *

- * The heuristic calls nextToken and expects an identifier - * (method name). - * - * @return true if the current position looks like a method - * call header. - */ - private boolean looksLikeMethodCall() { - nextToken(); - return fToken == Symbols.TokenIDENT; // method name - } - - /** - * Scans tokens for the matching opening peer. The internal cursor (fPosition) - * is set to the offset of the opening peer if found. - * - * @return true if a matching token was found, - * false otherwise - */ - private boolean skipScope(int openToken, int closeToken) { - - int depth = 1; - - while (true) { - nextToken(); - - if (fToken == closeToken) { - depth++; - } else if (fToken == openToken) { - depth--; - if (depth == 0) - return true; - } else if (fToken == Symbols.TokenEOF) { - return false; - } - } - } - - // TODO adjust once there are per-project settings - - private int prefTabLength() { - int tabLen; - // JavaCore core= JavaCore.getJavaCore(); - WebUI plugin = WebUI.getDefault(); - // if (core != null && plugin != null) - if (plugin != null) - if (JavaCore.SPACE - .equals(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - // if the formatter uses chars to mark indentation, then don't - // substitute any chars - tabLen = -1; // results in no tabs being substituted for - // space runs - else - // if the formatter uses tabs to mark indentations, use the - // visual setting from the editor - // to get nicely aligned indentations - tabLen = plugin - .getPreferenceStore() - .getInt( - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - else - tabLen = 4; // sensible default for testing - - return tabLen; - } - - private boolean prefArrayDimensionsDeepIndent() { - return true; // sensible default - } - - private int prefArrayIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); - try { - if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) - return 1; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return prefContinuationIndent(); // default - } - - private boolean prefArrayDeepIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); - try { - return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return true; - } - - private boolean prefTernaryDeepAlign() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); - try { - return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - return false; - } - - private int prefTernaryIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); - try { - if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) - return 1; - else - return prefContinuationIndent(); - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return prefContinuationIndent(); - } - - private int prefCaseIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - if (DefaultCodeFormatterConstants.TRUE - .equals(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH))) - return prefBlockIndent(); - else - return 0; - } - - return 0; // sun standard - } - - private int prefAssignmentIndent() { - return prefBlockIndent(); - } - - private int prefCaseBlockIndent() { - if (true) - return prefBlockIndent(); - - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - if (DefaultCodeFormatterConstants.TRUE - .equals(JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES))) - return prefBlockIndent(); - else - return 0; - } - return prefBlockIndent(); // sun standard - } - - private int prefSimpleIndent() { - return prefBlockIndent(); - } - - private int prefBracketIndent() { - return prefBlockIndent(); - } - - private boolean prefMethodDeclDeepIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); - try { - return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return true; - } - - private int prefMethodDeclIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); - try { - if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) - return 1; - else - return prefContinuationIndent(); - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - return 1; - } - - private boolean prefMethodCallDeepIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); - try { - return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - return false; // sensible default - } - - private int prefMethodCallIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); - try { - if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) - return 1; - else - return prefContinuationIndent(); - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return 1; // sensible default - } - - private boolean prefParenthesisDeepIndent() { - - if (true) // don't do parenthesis deep indentation - return false; - - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); - try { - return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; - } catch (IllegalArgumentException e) { - // ignore and return default - } - } - - return false; // sensible default - } - - private int prefParenthesisIndent() { - return prefContinuationIndent(); - } - - private int prefBlockIndent() { - return 1; // sensible default - } - -// private boolean prefIndentBracesForBlocks() { -// Plugin plugin = JavaCore.getPlugin(); -// if (plugin != null) { -// String option = JavaCore -// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); -// return option -// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); -// } -// -// return false; // sensible default -// } - -// private boolean prefIndentBracesForArrays() { -// Plugin plugin = JavaCore.getPlugin(); -// if (plugin != null) { -// String option = JavaCore -// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER); -// return option -// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); -// } -// -// return false; // sensible default -// } - -// private boolean prefIndentBracesForMethods() { -// Plugin plugin = JavaCore.getPlugin(); -// if (plugin != null) { -// String option = JavaCore -// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); -// return option -// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); -// } -// -// return false; // sensible default -// } - - private int prefContinuationIndent() { - Plugin plugin = JavaCore.getPlugin(); - if (plugin != null) { - String option = JavaCore - .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); - try { - return Integer.parseInt(option); - } catch (NumberFormatException e) { - // ignore and return default - } - } - - return 2; // sensible default - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java deleted file mode 100644 index e37799c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java +++ /dev/null @@ -1,640 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IParent; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.ui.actions.OpenActionUtil; -import net.sourceforge.phpdt.internal.ui.util.StringMatcher; -import net.sourceforge.phpdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; -import net.sourceforge.phpdt.ui.JavaElementSorter; -import net.sourceforge.phpdt.ui.StandardJavaElementContentProvider; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlExtension; -import org.eclipse.jface.text.IInformationControlExtension2; -import org.eclipse.jface.viewers.AbstractTreeViewer; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -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.graphics.Color; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -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.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Layout; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeItem; - -/** - * @author dmegert - * - * To change this generated comment edit the template variable "typecomment": - * Window>Preferences>Java>Templates. To enable and disable the creation of type - * comments go to Window>Preferences>Java>Code Generation. - */ -public class JavaOutlineInformationControl implements IInformationControl, - IInformationControlExtension, IInformationControlExtension2 { - - /** - * The NamePatternFilter selects the elements which match the given string - * patterns. - *

- * The following characters have special meaning: ? => any character * => - * any string - *

- * - * @since 2.0 - */ - private static class NamePatternFilter extends ViewerFilter { - private String fPattern; - - private StringMatcher fMatcher; - - private ILabelProvider fLabelProvider; - - private Viewer fViewer; - - private StringMatcher getMatcher() { - return fMatcher; - } - - /* - * (non-Javadoc) Method declared on ViewerFilter. - */ - public boolean select(Viewer viewer, Object parentElement, - Object element) { - if (fMatcher == null) - return true; - - ILabelProvider labelProvider = getLabelProvider(viewer); - - String matchName = null; - if (labelProvider != null) - matchName = ((ILabelProvider) labelProvider).getText(element); - else if (element instanceof IJavaElement) - matchName = ((IJavaElement) element).getElementName(); - - if (matchName != null && fMatcher.match(matchName)) - return true; - - return hasUnfilteredChild(viewer, element); - } - - private ILabelProvider getLabelProvider(Viewer viewer) { - if (fViewer == viewer) - return fLabelProvider; - - fLabelProvider = null; - IBaseLabelProvider baseLabelProvider = null; - if (viewer instanceof StructuredViewer) - baseLabelProvider = ((StructuredViewer) viewer) - .getLabelProvider(); - - if (baseLabelProvider instanceof ILabelProvider) - fLabelProvider = (ILabelProvider) baseLabelProvider; - - return fLabelProvider; - } - - private boolean hasUnfilteredChild(Viewer viewer, Object element) { - IJavaElement[] children; - if (element instanceof IParent) { - try { - children = ((IParent) element).getChildren(); - } catch (JavaModelException ex) { - return false; - } - for (int i = 0; i < children.length; i++) - if (select(viewer, element, children[i])) - return true; - } - return false; - } - - /** - * Sets the patterns to filter out for the receiver. - *

- * The following characters have special meaning: ? => any character * => - * any string - *

- */ - public void setPattern(String pattern) { - fPattern = pattern; - if (fPattern == null) { - fMatcher = null; - return; - } - boolean ignoreCase = pattern.toLowerCase().equals(pattern); - fMatcher = new StringMatcher(pattern, ignoreCase, false); - } - } - - private static class BorderFillLayout extends Layout { - - /** The border widths. */ - final int fBorderSize; - - /** - * Creates a fill layout with a border. - */ - public BorderFillLayout(int borderSize) { - if (borderSize < 0) - throw new IllegalArgumentException(); - fBorderSize = borderSize; - } - - /** - * Returns the border size. - */ - public int getBorderSize() { - return fBorderSize; - } - - /* - * @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, - * int, int, boolean) - */ - protected Point computeSize(Composite composite, int wHint, int hHint, - boolean flushCache) { - - Control[] children = composite.getChildren(); - Point minSize = new Point(0, 0); - - if (children != null) { - for (int i = 0; i < children.length; i++) { - Point size = children[i].computeSize(wHint, hHint, - flushCache); - minSize.x = Math.max(minSize.x, size.x); - minSize.y = Math.max(minSize.y, size.y); - } - } - - minSize.x += fBorderSize * 2 + RIGHT_MARGIN; - minSize.y += fBorderSize * 2; - - return minSize; - } - - /* - * @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, - * boolean) - */ - protected void layout(Composite composite, boolean flushCache) { - - Control[] children = composite.getChildren(); - Point minSize = new Point(composite.getClientArea().width, - composite.getClientArea().height); - - if (children != null) { - for (int i = 0; i < children.length; i++) { - Control child = children[i]; - child.setSize(minSize.x - fBorderSize * 2, minSize.y - - fBorderSize * 2); - child.setLocation(fBorderSize, fBorderSize); - } - } - } - } - - /** Border thickness in pixels. */ - private static final int BORDER = 1; - - /** Right margin in pixels. */ - private static final int RIGHT_MARGIN = 3; - - /** The control's shell */ - private Shell fShell; - - /** The composite */ - Composite fComposite; - - /** The control's text widget */ - private Text fFilterText; - - /** The control's tree widget */ - private TreeViewer fTreeViewer; - - /** The control width constraint */ - private int fMaxWidth = -1; - - /** The control height constraint */ - private int fMaxHeight = -1; - - private StringMatcher fStringMatcher; - - /** - * Creates a tree information control with the given shell as parent. The - * given style is applied to the tree widget. - * - * @param parent - * the parent shell - * @param style - * the additional styles for the tree widget - */ - public JavaOutlineInformationControl(Shell parent, int style) { - this(parent, SWT.RESIZE, style); - } - - /** - * Creates a tree information control with the given shell as parent. No - * additional styles are applied. - * - * @param parent - * the parent shell - */ -// public JavaOutlineInformationControl(Shell parent) { -// this(parent, SWT.NONE); -// } - - /** - * Creates a tree information control with the given shell as parent. The - * given styles are applied to the shell and the tree widget. - * - * @param parent - * the parent shell - * @param shellStyle - * the additional styles for the shell - * @param treeStyle - * the additional styles for the tree widget - */ - public JavaOutlineInformationControl(Shell parent, int shellStyle, - int treeStyle) { - fShell = new Shell(parent, shellStyle); - Display display = fShell.getDisplay(); - fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); - - // Composite for filter text and tree - fComposite = new Composite(fShell, SWT.RESIZE); - GridLayout layout = new GridLayout(1, false); - fComposite.setLayout(layout); - fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - createFilterText(fComposite); - createTreeViewer(fComposite, treeStyle); - - int border = ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; - fShell.setLayout(new BorderFillLayout(border)); - - setInfoSystemColor(); - installFilter(); - } - - private void createTreeViewer(Composite parent, int style) { - Tree tree = new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI)); - GridData data = new GridData(GridData.FILL_BOTH); - tree.setLayoutData(data); - - fTreeViewer = new TreeViewer(tree); - - // Hide import declartions but show the container - // fTreeViewer.addFilter(new ViewerFilter() { - // public boolean select(Viewer viewer, Object parentElement, Object - // element) { - // return !(element instanceof IImportDeclaration); - // } - // }); - - fTreeViewer.setContentProvider(new StandardJavaElementContentProvider( - true, true)); - fTreeViewer.setSorter(new JavaElementSorter()); - fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); - - AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( - AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS - | JavaElementLabels.F_APP_TYPE_SIGNATURE, - AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); - fTreeViewer - .setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); - - fTreeViewer.getTree().addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent e) { - if (e.character == 0x1B) // ESC - dispose(); - } - - public void keyReleased(KeyEvent e) { - // do nothing - } - }); - - fTreeViewer.getTree().addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - // do nothing - } - - public void widgetDefaultSelected(SelectionEvent e) { - gotoSelectedElement(); - } - }); - } - - private Text createFilterText(Composite parent) { - fFilterText = new Text(parent, SWT.FLAT); - - GridData data = new GridData(); - GC gc = new GC(parent); - gc.setFont(parent.getFont()); - FontMetrics fontMetrics = gc.getFontMetrics(); - gc.dispose(); - - data.heightHint = org.eclipse.jface.dialogs.Dialog - .convertHeightInCharsToPixels(fontMetrics, 1); - data.horizontalAlignment = GridData.FILL; - data.verticalAlignment = GridData.BEGINNING; - fFilterText.setLayoutData(data); - - fFilterText.addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent e) { - if (e.keyCode == 0x0D) // return - gotoSelectedElement(); - if (e.keyCode == SWT.ARROW_DOWN) - fTreeViewer.getTree().setFocus(); - if (e.keyCode == SWT.ARROW_UP) - fTreeViewer.getTree().setFocus(); - if (e.character == 0x1B) // ESC - dispose(); - } - - public void keyReleased(KeyEvent e) { - // do nothing - } - }); - - // Horizonral separator line - Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL - | SWT.LINE_DOT); - separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - return fFilterText; - } - - private void setInfoSystemColor() { - Display display = fShell.getDisplay(); - setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - } - - private void installFilter() { - final NamePatternFilter viewerFilter = new NamePatternFilter(); - fTreeViewer.addFilter(viewerFilter); - fFilterText.setText(""); //$NON-NLS-1$ - - fFilterText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - String pattern = fFilterText.getText(); - if (pattern != null) { - int length = pattern.length(); - if (length == 0) - pattern = null; - else if (pattern.charAt(length - 1) != '*') - pattern = pattern + '*'; - } else - pattern = null; - viewerFilter.setPattern(pattern); - fStringMatcher = viewerFilter.getMatcher(); - fTreeViewer.getControl().setRedraw(false); - fTreeViewer.refresh(); - fTreeViewer.expandAll(); - selectFirstMatch(); - fTreeViewer.getControl().setRedraw(true); - } - }); - } - - private void gotoSelectedElement() { - Object selectedElement = ((IStructuredSelection) fTreeViewer - .getSelection()).getFirstElement(); - if (selectedElement != null) { - try { - dispose(); - OpenActionUtil.open(selectedElement, true); - } catch (CoreException ex) { - WebUI.log(ex); - } - } - } - - /** - * Selects the first element in the tree which matches the current filter - * pattern. - */ - private void selectFirstMatch() { - Tree tree = fTreeViewer.getTree(); - Object element = findElement(tree.getItems()); - if (element != null) - fTreeViewer.setSelection(new StructuredSelection(element), true); - else - fTreeViewer.setSelection(StructuredSelection.EMPTY); - } - - private IJavaElement findElement(TreeItem[] items) { - ILabelProvider labelProvider = (ILabelProvider) fTreeViewer - .getLabelProvider(); - for (int i = 0; i < items.length; i++) { - IJavaElement element = (IJavaElement) items[i].getData(); - if (fStringMatcher == null) - return element; - - if (element != null) { - String label = labelProvider.getText(element); - if (fStringMatcher.match(label)) - return element; - } - - element = findElement(items[i].getItems()); - if (element != null) - return element; - } - return null; - } - - /* - * @see IInformationControl#setInformation(String) - */ - public void setInformation(String information) { - // this method is ignored, see IInformationControlExtension2 - } - - /* - * @see IInformationControlExtension2#setInput(Object) - */ - public void setInput(Object information) { - fFilterText.setText(""); //$NON-NLS-1$ - if (information == null || information instanceof String) { - setInput(null); - return; - } - IJavaElement je = (IJavaElement) information; - IJavaElement sel = null; - ICompilationUnit cu = (ICompilationUnit) je - .getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) - sel = cu; - else - sel = je.getAncestor(IJavaElement.CLASS_FILE); - fTreeViewer.setInput(sel); - fTreeViewer.setSelection(new StructuredSelection(information)); - } - - /* - * @see IInformationControl#setVisible(boolean) - */ - public void setVisible(boolean visible) { - fShell.setVisible(visible); - } - - /* - * @see IInformationControl#dispose() - */ - public void dispose() { - if (fShell != null) { - if (!fShell.isDisposed()) - fShell.dispose(); - fShell = null; - fTreeViewer = null; - fComposite = null; - fFilterText = null; - } - } - - /* - * @see org.eclipse.jface.text.IInformationControlExtension#hasContents() - */ - public boolean hasContents() { - return fTreeViewer != null && fTreeViewer.getInput() != null; - } - - /* - * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, - * int) - */ - public void setSizeConstraints(int maxWidth, int maxHeight) { - fMaxWidth = maxWidth; - fMaxHeight = maxHeight; - } - - /* - * @see org.eclipse.jface.text.IInformationControl#computeSizeHint() - */ - public Point computeSizeHint() { - return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); - } - - /* - * @see IInformationControl#setLocation(Point) - */ - public void setLocation(Point location) { - Rectangle trim = fShell.computeTrim(0, 0, 0, 0); - Point textLocation = fComposite.getLocation(); - location.x += trim.x - textLocation.x; - location.y += trim.y - textLocation.y; - fShell.setLocation(location); - } - - /* - * @see IInformationControl#setSize(int, int) - */ - public void setSize(int width, int height) { - fShell.setSize(width, height); - } - - /* - * @see IInformationControl#addDisposeListener(DisposeListener) - */ - public void addDisposeListener(DisposeListener listener) { - fShell.addDisposeListener(listener); - } - - /* - * @see IInformationControl#removeDisposeListener(DisposeListener) - */ - public void removeDisposeListener(DisposeListener listener) { - fShell.removeDisposeListener(listener); - } - - /* - * @see IInformationControl#setForegroundColor(Color) - */ - public void setForegroundColor(Color foreground) { - fTreeViewer.getTree().setForeground(foreground); - fFilterText.setForeground(foreground); - fComposite.setForeground(foreground); - } - - /* - * @see IInformationControl#setBackgroundColor(Color) - */ - public void setBackgroundColor(Color background) { - fTreeViewer.getTree().setBackground(background); - fFilterText.setBackground(background); - fComposite.setBackground(background); - } - - /* - * @see IInformationControl#isFocusControl() - */ - public boolean isFocusControl() { - return fTreeViewer.getControl().isFocusControl() - || fFilterText.isFocusControl(); - } - - /* - * @see IInformationControl#setFocus() - */ - public void setFocus() { - fShell.forceFocus(); - fFilterText.setFocus(); - } - - /* - * @see IInformationControl#addFocusListener(FocusListener) - */ - public void addFocusListener(FocusListener listener) { - fShell.addFocusListener(listener); - } - - /* - * @see IInformationControl#removeFocusListener(FocusListener) - */ - public void removeFocusListener(FocusListener listener) { - fShell.removeFocusListener(listener); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java deleted file mode 100644 index 17106cc..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java +++ /dev/null @@ -1,463 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text; - -import net.sourceforge.phpdt.core.ElementChangedEvent; -import net.sourceforge.phpdt.core.IElementChangedListener; -import net.sourceforge.phpdt.core.JavaCore; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IMarkerDelta; -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.IWorkspace; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.MonoReconciler; -import org.eclipse.swt.events.ShellAdapter; -import org.eclipse.swt.events.ShellEvent; -import org.eclipse.swt.events.ShellListener; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IPartListener; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartSite; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * A reconciler that is also activated on editor activation. - */ -public class JavaReconciler extends MonoReconciler { - - /** - * Internal part listener for activating the reconciler. - */ - private class PartListener implements IPartListener { - - /* - * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) - */ - public void partActivated(IWorkbenchPart part) { - if (part == fTextEditor && hasJavaModelChanged()) - JavaReconciler.this.forceReconciling(); - } - - /* - * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) - */ - public void partBroughtToTop(IWorkbenchPart part) { - } - - /* - * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) - */ - public void partClosed(IWorkbenchPart part) { - } - - /* - * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) - */ - public void partDeactivated(IWorkbenchPart part) { - if (part == fTextEditor) - setJavaModelChanged(false); - } - - /* - * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) - */ - public void partOpened(IWorkbenchPart part) { - } - } - - /** - * Internal Shell activation listener for activating the reconciler. - */ - private class ActivationListener extends ShellAdapter { - - private Control fControl; - - public ActivationListener(Control control) { - fControl = control; - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) - */ - public void shellActivated(ShellEvent e) { - if (!fControl.isDisposed() && fControl.isVisible() - && hasJavaModelChanged()) - JavaReconciler.this.forceReconciling(); - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) - */ - public void shellDeactivated(ShellEvent e) { - setJavaModelChanged(false); - } - } - - /** - * Internal Java element changed listener - * - * @since 3.0 - */ - private class ElementChangedListener implements IElementChangedListener { - /* - * @see net.sourceforge.phpdt.core.IElementChangedListener#elementChanged(net.sourceforge.phpdt.core.ElementChangedEvent) - */ - public void elementChanged(ElementChangedEvent event) { - setJavaModelChanged(true); - } - } - - /** - * Internal resource change listener. - * - * @since 3.0 - */ - class ResourceChangeListener implements IResourceChangeListener { - - private IResource getResource() { - IEditorInput input = fTextEditor.getEditorInput(); - if (input instanceof IFileEditorInput) { - IFileEditorInput fileInput = (IFileEditorInput) input; - return fileInput.getFile(); - } - return null; - } - - /* - * @see IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) - */ - public void resourceChanged(IResourceChangeEvent e) { - IResourceDelta delta = e.getDelta(); - IResource resource = getResource(); - if (delta != null && resource != null) { - IResourceDelta child = delta.findMember(resource.getFullPath()); - if (child != null) { - IMarkerDelta[] deltas = child.getMarkerDeltas(); - if (deltas.length > 0) - forceReconciling(); - } - } - } - } - - /** The reconciler's editor */ - private ITextEditor fTextEditor; - - /** The part listener */ - private IPartListener fPartListener; - - /** The shell listener */ - private ShellListener fActivationListener; - - /** - * The mutex that keeps us from running multiple reconcilers on one editor. - * TODO remove once we have ensured that there is only one reconciler per - * editor. - */ - private Object fMutex; - - /** - * The Java element changed listener. - * - * @since 3.0 - */ - private IElementChangedListener fJavaElementChangedListener; - - /** - * Tells whether the Java model sent out a changed event. - * - * @since 3.0 - */ - private volatile boolean fHasJavaModelChanged = true; - - /** - * The resource change listener. - * - * @since 3.0 - */ - private IResourceChangeListener fResourceChangeListener; - - private boolean fIninitalProcessDone = false; - - /** - * Creates a new reconciler. - */ - public JavaReconciler(ITextEditor editor, - JavaCompositeReconcilingStrategy strategy, boolean isIncremental) { - super(strategy, isIncremental); - fTextEditor = editor; - - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 - // when re-using editors, a new reconciler is set up by the source - // viewer - // and the old one uninstalled. However, the old reconciler may still be - // running. - // To avoid having to reconcilers calling - // CompilationUnitEditor.reconciled, - // we synchronized on a lock object provided by the editor. - // The critical section is really the entire run() method of the - // reconciler - // thread, but synchronizing process() only will keep - // JavaReconcilingStrategy - // from running concurrently on the same editor. - // TODO remove once we have ensured that there is only one reconciler - // per editor. - if (editor instanceof PHPUnitEditor) - fMutex = ((PHPUnitEditor) editor).getReconcilerLock(); - else - fMutex = new Object(); // Null Object - } - - /* - * @see org.eclipse.jface.text.reconciler.IReconciler#install(org.eclipse.jface.text.ITextViewer) - */ - public void install(ITextViewer textViewer) { - super.install(textViewer); - - fPartListener = new PartListener(); - IWorkbenchPartSite site = fTextEditor.getSite(); - IWorkbenchWindow window = site.getWorkbenchWindow(); - window.getPartService().addPartListener(fPartListener); - - fActivationListener = new ActivationListener(textViewer.getTextWidget()); - Shell shell = window.getShell(); - shell.addShellListener(fActivationListener); - - fJavaElementChangedListener = new ElementChangedListener(); - JavaCore.addElementChangedListener(fJavaElementChangedListener); - - fResourceChangeListener = new ResourceChangeListener(); - IWorkspace workspace = WebUI.getWorkspace(); - workspace.addResourceChangeListener(fResourceChangeListener); - } - - /* - * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() - */ - public void uninstall() { - - IWorkbenchPartSite site = fTextEditor.getSite(); - IWorkbenchWindow window = site.getWorkbenchWindow(); - window.getPartService().removePartListener(fPartListener); - fPartListener = null; - - Shell shell = window.getShell(); - if (shell != null && !shell.isDisposed()) - shell.removeShellListener(fActivationListener); - fActivationListener = null; - - JavaCore.removeElementChangedListener(fJavaElementChangedListener); - fJavaElementChangedListener = null; - - IWorkspace workspace = WebUI.getWorkspace(); - workspace.removeResourceChangeListener(fResourceChangeListener); - fResourceChangeListener = null; - - super.uninstall(); - } - - /* - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#forceReconciling() - */ - protected void forceReconciling() { - if (!fIninitalProcessDone) - return; - - super.forceReconciling(); - JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); - strategy.notifyListeners(false); - } - - /* - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#aboutToReconcile() - * @since 3.0 - */ - protected void aboutToBeReconciled() { - JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); - strategy.aboutToBeReconciled(); - } - - /* - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerReset() - */ - protected void reconcilerReset() { - super.reconcilerReset(); - JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); - strategy.notifyListeners(true); - } - - /* - * @see org.eclipse.jface.text.reconciler.MonoReconciler#initialProcess() - */ - protected void initialProcess() { - // TODO remove once we have ensured that there is only one reconciler - // per editor. - synchronized (fMutex) { - super.initialProcess(); - } - fIninitalProcessDone = true; - } - - /* - * @see org.eclipse.jface.text.reconciler.MonoReconciler#process(org.eclipse.jface.text.reconciler.DirtyRegion) - */ - protected void process(DirtyRegion dirtyRegion) { - // TODO remove once we have ensured that there is only one reconciler - // per editor. - synchronized (fMutex) { - super.process(dirtyRegion); - } - } - - /** - * Tells whether the Java Model has changed or not. - * - * @return true iff the Java Model has changed - * @since 3.0 - */ - private synchronized boolean hasJavaModelChanged() { - return fHasJavaModelChanged; - } - - /** - * Sets whether the Java Model has changed or not. - * - * @param state - * true iff the java model has changed - * @since 3.0 - */ - private synchronized void setJavaModelChanged(boolean state) { - fHasJavaModelChanged = state; - } -} -// /** -// * A reconciler that is also activated on editor activation. -// */ -// public class JavaReconciler extends MonoReconciler { -// -// /** -// * Internal part listener for activating the reconciler. -// */ -// class PartListener implements IPartListener { -// -// /* -// * @see IPartListener#partActivated(IWorkbenchPart) -// */ -// public void partActivated(IWorkbenchPart part) { -// if (part == fTextEditor) -// JavaReconciler.this.forceReconciling(); -// } -// -// /* -// * @see IPartListener#partBroughtToTop(IWorkbenchPart) -// */ -// public void partBroughtToTop(IWorkbenchPart part) { -// } -// -// /* -// * @see IPartListener#partClosed(IWorkbenchPart) -// */ -// public void partClosed(IWorkbenchPart part) { -// } -// -// /* -// * @see IPartListener#partDeactivated(IWorkbenchPart) -// */ -// public void partDeactivated(IWorkbenchPart part) { -// } -// -// /* -// * @see IPartListener#partOpened(IWorkbenchPart) -// */ -// public void partOpened(IWorkbenchPart part) { -// } -// }; -// -// -// /** The reconciler's editor */ -// private ITextEditor fTextEditor; -// /** The part listener */ -// private IPartListener fPartListener; -// -// -// /** -// * Creates a new reconciler. -// */ -// public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, -// boolean isIncremental) { -// super(strategy, isIncremental); -// fTextEditor= editor; -// } -// -// /* -// * @see IReconciler#install(ITextViewer) -// */ -// public void install(ITextViewer textViewer) { -// super.install(textViewer); -// -// fPartListener= new PartListener(); -// IWorkbenchPartSite site= fTextEditor.getSite(); -// IWorkbenchWindow window= site.getWorkbenchWindow(); -// window.getPartService().addPartListener(fPartListener); -// } -// -// /* -// * @see IReconciler#uninstall() -// */ -// public void uninstall() { -// -// IWorkbenchPartSite site= fTextEditor.getSite(); -// IWorkbenchWindow window= site.getWorkbenchWindow(); -// window.getPartService().removePartListener(fPartListener); -// fPartListener= null; -// -// super.uninstall(); -// } -// -// /* -// * @see AbstractReconciler#forceReconciling() -// */ -// protected void forceReconciling() { -// super.forceReconciling(); -// IReconcilingStrategy strategy= -// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); -// if (strategy instanceof JavaReconcilingStrategy) { -// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; -// java.notifyParticipants(false); -// } -// } -// -// /* -// * @see AbstractReconciler#reconcilerReset() -// */ -// protected void reconcilerReset() { -// super.reconcilerReset(); -// IReconcilingStrategy strategy= -// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); -// if (strategy instanceof JavaReconcilingStrategy) { -// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; -// java.notifyParticipants(true); -// } -// } -// } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java deleted file mode 100644 index f3e79b3..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java +++ /dev/null @@ -1,1301 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text; - -import java.util.Arrays; - -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -//incastrix -//import net.sourceforge.phpdt.internal.corext.Assert; -import org.eclipse.core.runtime.Assert; -import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager.UndoSpec; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.texteditor.ITextEditorExtension2; -import org.eclipse.ui.texteditor.ITextEditorExtension3; - -/** - * Modifies DocumentCommands inserting semicolons and opening - * braces to place them smartly, i.e. moving them to the end of a line if that - * is what the user expects. - * - *

- * In practice, semicolons and braces (and the caret) are moved to the end of - * the line if they are typed anywhere except for semicolons in a - * for statements definition. If the line contains a semicolon or - * brace after the current caret position, the cursor is moved after it. - *

- * - * @see org.eclipse.jface.text.DocumentCommand - * @since 3.0 - */ -public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { - - /** String representation of a semicolon. */ - private static final String SEMICOLON = ";"; //$NON-NLS-1$ - - /** Char representation of a semicolon. */ - private static final char SEMICHAR = ';'; - - /** String represenattion of a opening brace. */ - private static final String BRACE = "{"; //$NON-NLS-1$ - - /** Char representation of a opening brace */ - private static final char BRACECHAR = '{'; - - private char fCharacter; - - private String fPartitioning; - - /** - * Creates a new SmartSemicolonAutoEditStrategy. - * - * @param partitioning - * the document partitioning - */ - public SmartSemicolonAutoEditStrategy(String partitioning) { - fPartitioning = partitioning; - } - - /* - * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.DocumentCommand) - */ - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - // 0: early pruning - // also customize if doit is false (so it works in code - // completion situations) - // if (!command.doit) - // return; - - if (command.text == null) - return; - - if (command.text.equals(SEMICOLON)) - fCharacter = SEMICHAR; - else if (command.text.equals(BRACE)) - fCharacter = BRACECHAR; - else - return; - - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - if (fCharacter == SEMICHAR - && !store - .getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)) - return; - if (fCharacter == BRACECHAR - && !store - .getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE)) - return; - - IWorkbenchPage page = WebUI.getActivePage(); - if (page == null) - return; - IEditorPart part = page.getActiveEditor(); - if (!(part instanceof PHPUnitEditor)) - return; - PHPUnitEditor editor = (PHPUnitEditor) part; - if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT - || !editor.isEditable()) - return; - ITextEditorExtension2 extension = (ITextEditorExtension2) editor - .getAdapter(ITextEditorExtension2.class); - if (extension != null && !extension.validateEditorInputState()) - return; - if (isMultilineSelection(document, command)) - return; - - // 1: find concerned line / position in java code, location in statement - int pos = command.offset; - ITextSelection line; - try { - IRegion l = document.getLineInformationOfOffset(pos); - line = new TextSelection(document, l.getOffset(), l.getLength()); - } catch (BadLocationException e) { - return; - } - - // 2: choose action based on findings (is for-Statement?) - // for now: compute the best position to insert the new character - int positionInLine = computeCharacterPosition(document, line, pos - - line.getOffset(), fCharacter, fPartitioning); - int position = positionInLine + line.getOffset(); - - // never position before the current position! - if (position < pos) - return; - - // never double already existing content - if (alreadyPresent(document, fCharacter, position)) - return; - - // don't do special processing if what we do is actually the normal - // behaviour - String insertion = adjustSpacing(document, position, fCharacter); - if (command.offset == position && insertion.equals(command.text)) - return; - - try { - - final SmartBackspaceManager manager = (SmartBackspaceManager) editor - .getAdapter(SmartBackspaceManager.class); - if (manager != null - && WebUI.getDefault().getPreferenceStore() - .getBoolean( - PreferenceConstants.EDITOR_SMART_BACKSPACE)) { - TextEdit e1 = new ReplaceEdit(command.offset, command.text - .length(), document.get(command.offset, command.length)); - UndoSpec s1 = new UndoSpec(command.offset - + command.text.length(), new Region(command.offset, 0), - new TextEdit[] { e1 }, 0, null); - - DeleteEdit smart = new DeleteEdit(position, insertion.length()); - ReplaceEdit raw = new ReplaceEdit(command.offset, - command.length, command.text); - UndoSpec s2 = new UndoSpec(position + insertion.length(), - new Region(command.offset + command.text.length(), 0), - new TextEdit[] { smart, raw }, 2, s1); - manager.register(s2); - } - - // 3: modify command - command.offset = position; - command.length = 0; - command.caretOffset = position; - command.text = insertion; - command.doit = true; - command.owner = null; - } catch (MalformedTreeException e) { - WebUI.log(e); - } catch (BadLocationException e) { - WebUI.log(e); - } - - } - - /** - * Returns true if the document command is applied on a multi - * line selection, false otherwise. - * - * @param document - * the document - * @param command - * the command - * @return true if command is a multiline - * command - */ - private boolean isMultilineSelection(IDocument document, - DocumentCommand command) { - try { - return document.getNumberOfLines(command.offset, command.length) > 1; - } catch (BadLocationException e) { - // ignore - return false; - } - } - - /** - * Adds a space before a brace if it is inserted after a parenthesis, equal - * sign, or one of the keywords try, else, do. - * - * @param document - * the document we are working on - * @param position - * the insert position of character - * @param character - * the character to be inserted - * @return a String consisting of character - * plus any additional spacing - */ - private String adjustSpacing(IDocument doc, int position, char character) { - if (character == BRACECHAR) { - if (position > 0 && position <= doc.getLength()) { - int pos = position - 1; - if (looksLike(doc, pos, ")") //$NON-NLS-1$ - || looksLike(doc, pos, "=") //$NON-NLS-1$ - || looksLike(doc, pos, "]") //$NON-NLS-1$ - || looksLike(doc, pos, "try") //$NON-NLS-1$ - || looksLike(doc, pos, "else") //$NON-NLS-1$ - || looksLike(doc, pos, "synchronized") //$NON-NLS-1$ - || looksLike(doc, pos, "static") //$NON-NLS-1$ - || looksLike(doc, pos, "finally") //$NON-NLS-1$ - || looksLike(doc, pos, "do")) //$NON-NLS-1$ - return new String(new char[] { ' ', character }); - } - } - - return new String(new char[] { character }); - } - - /** - * Checks whether a character to be inserted is already present at the - * insert location (perhaps separated by some whitespace from - * position. - * - * @param document - * the document we are working on - * @param position - * the insert position of ch - * @param character - * the character to be inserted - * @return true if ch is already present at - * location, false otherwise - */ - private boolean alreadyPresent(IDocument document, char ch, int position) { - int pos = firstNonWhitespaceForward(document, position, fPartitioning, - document.getLength()); - try { - if (pos != -1 && document.getChar(pos) == ch) - return true; - } catch (BadLocationException e) { - } - - return false; - } - - /** - * Computes the next insert position of the given character in the current - * line. - * - * @param document - * the document we are working on - * @param line - * the line where the change is being made - * @param offset - * the position of the caret in the line when - * character was typed - * @param character - * the character to look for - * @param partitioning - * the document partitioning - * @return the position where character should be inserted / - * replaced - */ - protected static int computeCharacterPosition(IDocument document, - ITextSelection line, int offset, char character, String partitioning) { - String text = line.getText(); - if (text == null) - return 0; - - int insertPos; - if (character == BRACECHAR) { - - insertPos = computeArrayInitializationPos(document, line, offset, - partitioning); - - if (insertPos == -1) { - insertPos = computeAfterTryDoElse(document, line, offset); - } - - if (insertPos == -1) { - insertPos = computeAfterParenthesis(document, line, offset, - partitioning); - } - - } else if (character == SEMICHAR) { - - if (isForStatement(text, offset)) { - insertPos = -1; // don't do anything in for statements, as semis - // are vital part of these - } else { - int nextPartitionPos = nextPartitionOrLineEnd(document, line, - offset, partitioning); - insertPos = startOfWhitespaceBeforeOffset(text, - nextPartitionPos); - // if there is a semi present, return its location as - // alreadyPresent() will take it out this way. - if (insertPos > 0 && text.charAt(insertPos - 1) == character) - insertPos = insertPos - 1; - } - - } else { - Assert.isTrue(false); - return -1; - } - - return insertPos; - } - - /** - * Computes an insert position for an opening brace if offset - * maps to a position in document that looks like being the - * RHS of an assignment or like an array definition. - * - * @param document - * the document being modified - * @param line - * the current line under investigation - * @param offset - * the offset of the caret position, relative to the line start. - * @param partitioning - * the document partitioning - * @return an insert position relative to the line start if - * line looks like being an array initialization at - * offset, -1 otherwise - */ - private static int computeArrayInitializationPos(IDocument document, - ITextSelection line, int offset, String partitioning) { - // search backward while WS, find = (not != <= >= ==) in default - // partition - int pos = offset + line.getOffset(); - - if (pos == 0) - return -1; - - int p = firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); - - if (p == -1) - return -1; - - try { - - char ch = document.getChar(p); - if (ch != '=' && ch != ']') - return -1; - - if (p == 0) - return offset; - - p = firstNonWhitespaceBackward(document, p - 1, partitioning, -1); - if (p == -1) - return -1; - - ch = document.getChar(p); - if (Scanner.isPHPIdentifierPart(ch) || ch == ']' || ch == '[') - return offset; - - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Computes an insert position for an opening brace if offset - * maps to a position in document involving a keyword taking - * a block after it. These are: try, do, - * synchronized, static, - * finally, or else. - * - * @param document - * the document being modified - * @param line - * the current line under investigation - * @param offset - * the offset of the caret position, relative to the line start. - * @return an insert position relative to the line start if - * line contains one of the above keywords at or - * before offset, -1 otherwise - */ - private static int computeAfterTryDoElse(IDocument doc, - ITextSelection line, int offset) { - // search backward while WS, find 'try', 'do', 'else' in default - // partition - int p = offset + line.getOffset(); - p = firstWhitespaceToRight(doc, p); - if (p == -1) - return -1; - p--; - - if (looksLike(doc, p, "try") //$NON-NLS-1$ - || looksLike(doc, p, "do") //$NON-NLS-1$ - || looksLike(doc, p, "synchronized") //$NON-NLS-1$ - || looksLike(doc, p, "static") //$NON-NLS-1$ - || looksLike(doc, p, "finally") //$NON-NLS-1$ - || looksLike(doc, p, "else")) //$NON-NLS-1$ - return p + 1 - line.getOffset(); - - return -1; - } - - /** - * Computes an insert position for an opening brace if offset - * maps to a position in document with a expression in - * parenthesis that will take a block after the closing parenthesis. - * - * @param document - * the document being modified - * @param line - * the current line under investigation - * @param offset - * the offset of the caret position, relative to the line start. - * @param partitioning - * the document partitioning - * @return an insert position relative to the line start if - * line contains a parenthesized expression that can - * be followed by a block, -1 otherwise - */ - private static int computeAfterParenthesis(IDocument document, - ITextSelection line, int offset, String partitioning) { - // find the opening parenthesis for every closing parenthesis on the - // current line after offset - // return the position behind the closing parenthesis if it looks like a - // method declaration - // or an expression for an if, while, for, catch statement - int pos = offset + line.getOffset(); - int length = line.getOffset() + line.getLength(); - int scanTo = scanForward(document, pos, partitioning, length, '}'); - if (scanTo == -1) - scanTo = length; - - int closingParen = findClosingParenToLeft(document, pos, partitioning) - 1; - - while (true) { - int startScan = closingParen + 1; - closingParen = scanForward(document, startScan, partitioning, - scanTo, ')'); - if (closingParen == -1) - break; - - int openingParen = findOpeningParenMatch(document, closingParen, - partitioning); - - // no way an expression at the beginning of the document can mean - // anything - if (openingParen < 1) - break; - - // only select insert positions for parenthesis currently embracing - // the caret - if (openingParen > pos) - continue; - - if (looksLikeAnonymousClassDef(document, openingParen - 1, - partitioning)) - return closingParen + 1 - line.getOffset(); - - if (looksLikeIfWhileForCatch(document, openingParen - 1, - partitioning)) - return closingParen + 1 - line.getOffset(); - - if (looksLikeMethodDecl(document, openingParen - 1, partitioning)) - return closingParen + 1 - line.getOffset(); - - } - - return -1; - } - - /** - * Finds a closing parenthesis to the left of position in - * document, where that parenthesis is only separated by whitespace from - * position. If no such parenthesis can be found, - * position is returned. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return the position of a closing parenthesis left to - * position separated only by whitespace, or - * position if no parenthesis can be found - */ - private static int findClosingParenToLeft(IDocument document, int position, - String partitioning) { - final char CLOSING_PAREN = ')'; - try { - if (position < 1) - return position; - - int nonWS = firstNonWhitespaceBackward(document, position - 1, - partitioning, -1); - if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN) - return nonWS; - } catch (BadLocationException e1) { - } - return position; - } - - /** - * Finds the first whitespace character position to the right of (and - * including) position. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @return the position of a whitespace character greater or equal than - * position separated only by whitespace, or -1 if - * none found - */ - private static int firstWhitespaceToRight(IDocument document, int position) { - int length = document.getLength(); - Assert.isTrue(position >= 0); - Assert.isTrue(position <= length); - - try { - while (position < length) { - char ch = document.getChar(position); - if (Character.isWhitespace(ch)) - return position; - position++; - } - return position; - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Finds the highest position in document such that the - * position is <= position and > bound - * and Character.isWhitespace(document.getChar(pos)) - * evaluates to false and the position is in the default - * partition. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @param bound - * the first position in document to not consider - * any more, with bound > position - * @return the highest position of one element in chars in [position, - * scanTo) that resides in a Java partition, or - * -1 if none can be found - */ - private static int firstNonWhitespaceBackward(IDocument document, - int position, String partitioning, int bound) { - Assert.isTrue(position < document.getLength()); - Assert.isTrue(bound >= -1); - - try { - while (position > bound) { - char ch = document.getChar(position); - if (!Character.isWhitespace(ch) - && isDefaultPartition(document, position, partitioning)) - return position; - position--; - } - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Finds the smallest position in document such that the - * position is >= position and < bound - * and Character.isWhitespace(document.getChar(pos)) - * evaluates to false and the position is in the default - * partition. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @param bound - * the first position in document to not consider - * any more, with bound > position - * @return the smallest position of one element in chars in [position, - * scanTo) that resides in a Java partition, or - * -1 if none can be found - */ - private static int firstNonWhitespaceForward(IDocument document, - int position, String partitioning, int bound) { - Assert.isTrue(position >= 0); - Assert.isTrue(bound <= document.getLength()); - - try { - while (position < bound) { - char ch = document.getChar(position); - if (!Character.isWhitespace(ch) - && isDefaultPartition(document, position, partitioning)) - return position; - position++; - } - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Finds the highest position in document such that the - * position is <= position and > bound - * and document.getChar(position) == ch evaluates to - * true for at least one ch in chars and the - * position is in the default partition. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @param bound - * the first position in document to not consider - * any more, with scanTo > - * position - * @param chars - * an array of char to search for - * @return the highest position of one element in chars in (bound, - * position] that resides in a Java partition, or - * -1 if none can be found - */ - private static int scanBackward(IDocument document, int position, - String partitioning, int bound, char[] chars) { - Assert.isTrue(bound >= -1); - Assert.isTrue(position < document.getLength()); - - Arrays.sort(chars); - - try { - while (position > bound) { - - if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 - && isDefaultPartition(document, position, partitioning)) - return position; - - position--; - } - } catch (BadLocationException e) { - } - return -1; - } - - // /** - // * Finds the highest position in document such that the - // position is <= position - // * and > bound and document.getChar(position) == - // ch evaluates to true - // * and the position is in the default partition. - // * - // * @param document the document being modified - // * @param position the first character position in document - // to be considered - // * @param bound the first position in document to not - // consider any more, with scanTo > position - // * @param chars an array of char to search for - // * @return the highest position of one element in chars in - // [position, scanTo) that resides in a Java - // partition, or -1 if none can be found - // */ - // private static int scanBackward(IDocument document, int position, int - // bound, char ch) { - // return scanBackward(document, position, bound, new char[] {ch}); - // } - // - /** - * Finds the lowest position in document such that the - * position is >= position and < bound - * and document.getChar(position) == ch evaluates to - * true for at least one ch in chars and the - * position is in the default partition. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @param bound - * the first position in document to not consider - * any more, with scanTo > - * position - * @param chars - * an array of char to search for - * @return the lowest position of one element in chars in [position, - * bound) that resides in a Java partition, or - * -1 if none can be found - */ - private static int scanForward(IDocument document, int position, - String partitioning, int bound, char[] chars) { - Assert.isTrue(position >= 0); - Assert.isTrue(bound <= document.getLength()); - - Arrays.sort(chars); - - try { - while (position < bound) { - - if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 - && isDefaultPartition(document, position, partitioning)) - return position; - - position++; - } - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Finds the lowest position in document such that the - * position is >= position and < bound - * and document.getChar(position) == ch evaluates to - * true and the position is in the default partition. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @param bound - * the first position in document to not consider - * any more, with scanTo > - * position - * @param chars - * an array of char to search for - * @return the lowest position of one element in chars in [position, - * bound) that resides in a Java partition, or - * -1 if none can be found - */ - private static int scanForward(IDocument document, int position, - String partitioning, int bound, char ch) { - return scanForward(document, position, partitioning, bound, - new char[] { ch }); - } - - /** - * Checks whether the content of document in the range (offset, - * length) contains the new keyword. - * - * @param document - * the document being modified - * @param offset - * the first character position in document to be - * considered - * @param length - * the length of the character range to be considered - * @param partitioning - * the document partitioning - * @return true if the specified character range contains a - * new keyword, false otherwise. - */ - private static boolean isNewMatch(IDocument document, int offset, - int length, String partitioning) { - Assert.isTrue(length >= 0); - Assert.isTrue(offset >= 0); - Assert.isTrue(offset + length < document.getLength() + 1); - - try { - String text = document.get(offset, length); - int pos = text.indexOf("new"); //$NON-NLS-1$ - - while (pos != -1 - && !isDefaultPartition(document, pos + offset, partitioning)) - pos = text.indexOf("new", pos + 2); //$NON-NLS-1$ - - if (pos < 0) - return false; - - if (pos != 0 && Scanner.isPHPIdentifierPart(text.charAt(pos - 1))) - return false; - - if (pos + 3 < length - && Scanner.isPHPIdentifierPart(text.charAt(pos + 3))) - return false; - - return true; - - } catch (BadLocationException e) { - } - return false; - } - - /** - * Checks whether the content of document at - * position looks like an anonymous class definition. - * position must be to the left of the opening parenthesis of - * the definition's parameter list. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return true if the content of document - * looks like an anonymous class definition, false - * otherwise - */ - private static boolean looksLikeAnonymousClassDef(IDocument document, - int position, String partitioning) { - int previousCommaOrParen = scanBackward(document, position - 1, - partitioning, -1, new char[] { ',', '(' }); - if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 - // for - // borders, - // 3 - // for - // "new" - return false; - - if (isNewMatch(document, previousCommaOrParen + 1, position - - previousCommaOrParen - 2, partitioning)) - return true; - - return false; - } - - /** - * Checks whether position resides in a default (Java) - * partition of document. - * - * @param document - * the document being modified - * @param position - * the position to be checked - * @param partitioning - * the document partitioning - * @return true if position is in the default - * partition of document, false - * otherwise - */ - private static boolean isDefaultPartition(IDocument document, int position, - String partitioning) { - Assert.isTrue(position >= 0); - Assert.isTrue(position <= document.getLength()); - - try { - // don't use getPartition2 since we're interested in the scanned - // character's partition - ITypedRegion region = TextUtilities.getPartition(document, - partitioning, position, false); - return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE); - - } catch (BadLocationException e) { - } - - return false; - } - - /** - * Finds the position of the parenthesis matching the closing parenthesis at - * position. - * - * @param document - * the document being modified - * @param position - * the position in document of a closing - * parenthesis - * @param partitioning - * the document partitioning - * @return the position in document of the matching - * parenthesis, or -1 if none can be found - */ - private static int findOpeningParenMatch(IDocument document, int position, - String partitioning) { - final char CLOSING_PAREN = ')'; - final char OPENING_PAREN = '('; - - Assert.isTrue(position < document.getLength()); - Assert.isTrue(position >= 0); - Assert.isTrue(isDefaultPartition(document, position, partitioning)); - - try { - - Assert.isTrue(document.getChar(position) == CLOSING_PAREN); - - int depth = 1; - while (true) { - position = scanBackward(document, position - 1, partitioning, - -1, new char[] { CLOSING_PAREN, OPENING_PAREN }); - if (position == -1) - return -1; - - if (document.getChar(position) == CLOSING_PAREN) - depth++; - else - depth--; - - if (depth == 0) - return position; - } - - } catch (BadLocationException e) { - return -1; - } - } - - /** - * Checks whether, to the left of position and separated only - * by whitespace, document contains a keyword taking a - * parameter list and a block after it. These are: if, - * while, catch, for, - * synchronized, switch. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return true if document contains any of - * the above keywords to the left of position, - * false otherwise - */ - private static boolean looksLikeIfWhileForCatch(IDocument document, - int position, String partitioning) { - position = firstNonWhitespaceBackward(document, position, partitioning, - -1); - if (position == -1) - return false; - - return looksLike(document, position, "if") //$NON-NLS-1$ - || looksLike(document, position, "while") //$NON-NLS-1$ - || looksLike(document, position, "catch") //$NON-NLS-1$ - || looksLike(document, position, "synchronized") //$NON-NLS-1$ - || looksLike(document, position, "switch") //$NON-NLS-1$ - || looksLike(document, position, "for"); //$NON-NLS-1$ - } - - /** - * Checks whether code>document contains the String like - * such that its last character is at position. If like - * starts with a identifier part (as determined by - * {@link Scanner#isPHPIdentifierPart(char)}), it is also made sure that - * like is preceded by some non-identifier character or - * stands at the document start. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param like - * the String to look for. - * @return true if document contains like - * such that it ends at position, false - * otherwise - */ - private static boolean looksLike(IDocument document, int position, - String like) { - int length = like.length(); - if (position < length - 1) - return false; - - try { - if (!like.equals(document.get(position - length + 1, length))) - return false; - - if (position >= length - && Scanner.isPHPIdentifierPart(like.charAt(0)) - && Scanner.isPHPIdentifierPart(document.getChar(position - - length))) - return false; - - } catch (BadLocationException e) { - return false; - } - - return true; - } - - /** - * Checks whether the content of document at - * position looks like a method declaration header (i.e. only - * the return type and method name). position must be just - * left of the opening parenthesis of the parameter list. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return true if the content of document - * looks like a method definition, false otherwise - */ - private static boolean looksLikeMethodDecl(IDocument document, - int position, String partitioning) { - - // method name - position = eatIdentToLeft(document, position, partitioning); - if (position < 1) - return false; - - position = eatBrackets(document, position - 1, partitioning); - if (position < 1) - return false; - - position = eatIdentToLeft(document, position - 1, partitioning); - - return position != -1; - } - - /** - * From position to the left, eats any whitespace and then a - * pair of brackets as used to declare an array return type like - * - *
-	 * String [ ]
-	 * 
. The return value is either the position of the opening bracket - * or position if no pair of brackets can be parsed. - * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return the smallest character position of bracket pair or - * position - */ - private static int eatBrackets(IDocument document, int position, - String partitioning) { - // accept array return type - int pos = firstNonWhitespaceBackward(document, position, partitioning, - -1); - try { - if (pos > 1 && document.getChar(pos) == ']') { - pos = firstNonWhitespaceBackward(document, pos - 1, - partitioning, -1); - if (pos > 0 && document.getChar(pos) == '[') - return pos; - } - } catch (BadLocationException e) { - // won't happen - } - return position; - } - - /** - * From position to the left, eats any whitespace and the - * first identifier, returning the position of the first identifier - * character (in normal read order). - *

- * When called on a document with content " some string " and - * positionition 13, the return value will be 6 (the first letter in - * string). - *

- * - * @param document - * the document being modified - * @param position - * the first character position in document to be - * considered - * @param partitioning - * the document partitioning - * @return the smallest character position of an identifier or -1 if none - * can be found; always <= position - */ - private static int eatIdentToLeft(IDocument document, int position, - String partitioning) { - if (position < 0) - return -1; - Assert.isTrue(position < document.getLength()); - - int p = firstNonWhitespaceBackward(document, position, partitioning, -1); - if (p == -1) - return -1; - - try { - while (p >= 0) { - - char ch = document.getChar(p); - if (Scanner.isPHPIdentifierPart(ch)) { - p--; - continue; - } - - // length must be > 0 - if (Character.isWhitespace(ch) && p != position) - return p + 1; - else - return -1; - - } - - // start of document reached - return 0; - - } catch (BadLocationException e) { - } - return -1; - } - - /** - * Returns a position in the first java partition after the last non-empty - * and non-comment partition. There is no non-whitespace from the returned - * position to the end of the partition it is contained in. - * - * @param document - * the document being modified - * @param line - * the line under investigation - * @param offset - * the caret offset into line - * @param partitioning - * the document partitioning - * @return the position of the next Java partition, or the end of - * line - */ - private static int nextPartitionOrLineEnd(IDocument document, - ITextSelection line, int offset, String partitioning) { - // run relative to document - final int docOffset = offset + line.getOffset(); - final int eol = line.getOffset() + line.getLength(); - int nextPartitionPos = eol; // init with line end - int validPosition = docOffset; - - try { - ITypedRegion partition = TextUtilities.getPartition(document, - partitioning, nextPartitionPos, true); - validPosition = getValidPositionForPartition(document, partition, - eol); - while (validPosition == -1) { - nextPartitionPos = partition.getOffset() - 1; - if (nextPartitionPos < docOffset) { - validPosition = docOffset; - break; - } - partition = TextUtilities.getPartition(document, partitioning, - nextPartitionPos, false); - validPosition = getValidPositionForPartition(document, - partition, eol); - } - } catch (BadLocationException e) { - } - - validPosition = Math.max(validPosition, docOffset); - // make relative to line - validPosition -= line.getOffset(); - return validPosition; - } - - /** - * Returns a valid insert location (except for whitespace) in - * partition or -1 if there is no valid insert location. An - * valid insert location is right after any java string or character - * partition, or at the end of a java default partition, but never behind - * maxOffset. Comment partitions or empty java partitions do - * never yield valid insert positions. - * - * @param doc - * the document being modified - * @param partition - * the current partition - * @param maxOffset - * the maximum offset to consider - * @return a valid insert location in partition, or -1 if - * there is no valid insert location - */ - private static int getValidPositionForPartition(IDocument doc, - ITypedRegion partition, int maxOffset) { - final int INVALID = -1; - - if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(partition.getType())) - return INVALID; - if (IPHPPartitions.PHP_MULTILINE_COMMENT.equals(partition.getType())) - return INVALID; - if (IPHPPartitions.PHP_SINGLELINE_COMMENT.equals(partition.getType())) - return INVALID; - - int endOffset = Math.min(maxOffset, partition.getOffset() - + partition.getLength()); - - // if (IPHPPartitions.JAVA_CHARACTER.equals(partition.getType())) - // return endOffset; - if (IPHPPartitions.PHP_STRING_DQ.equals(partition.getType())) - return endOffset; - if (IPHPPartitions.PHP_STRING_SQ.equals(partition.getType())) - return endOffset; - if (IPHPPartitions.PHP_STRING_HEREDOC.equals(partition.getType())) - return endOffset; - if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) { - try { - if (doc.get(partition.getOffset(), - endOffset - partition.getOffset()).trim().length() == 0) - return INVALID; - else - return endOffset; - } catch (BadLocationException e) { - return INVALID; - } - } - // default: we don't know anything about the partition - assume valid - return endOffset; - } - - /** - * Determines whether the current line contains a for statement. Algorithm: - * any "for" word in the line is a positive, "for" contained in a string - * literal will produce a false positive. - * - * @param line - * the line where the change is being made - * @param offset - * the position of the caret - * @return true if line contains - * for, false otherwise - */ - private static boolean isForStatement(String line, int offset) { - /* searching for (^|\s)for(\s|$) */ - int forPos = line.indexOf("for"); //$NON-NLS-1$ - if (forPos != -1) { - if ((forPos == 0 || !Scanner.isPHPIdentifierPart(line - .charAt(forPos - 1))) - && (line.length() == forPos + 3 || !Scanner - .isPHPIdentifierPart(line.charAt(forPos + 3)))) - return true; - } - return false; - } - - /** - * Returns the position in text after which there comes only - * whitespace, up to offset. - * - * @param text - * the text being searched - * @param offset - * the maximum offset to search for - * @return the smallest value v such that - * text.substring(v, offset).trim() == 0 - */ - private static int startOfWhitespaceBeforeOffset(String text, int offset) { - int i = Math.min(offset, text.length()); - for (; i >= 1; i--) { - if (!Character.isWhitespace(text.charAt(i - 1))) - break; - } - return i; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java deleted file mode 100644 index 42d14eb..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java +++ /dev/null @@ -1,185 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.folding; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore; -import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore.OverlayKey; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.swt.SWT; -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; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; - -/** - * Java default folding preferences. - * - * @since 3.0 - */ -public class DefaultJavaFoldingPreferenceBlock implements - IJavaFoldingPreferenceBlock { - - private IPreferenceStore fStore; - - private OverlayPreferenceStore fOverlayStore; - - private OverlayKey[] fKeys; - - private Map fCheckBoxes = new HashMap(); - - private SelectionListener fCheckBoxListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - Button button = (Button) e.widget; - fOverlayStore.setValue((String) fCheckBoxes.get(button), button - .getSelection()); - } - }; - - public DefaultJavaFoldingPreferenceBlock() { - fStore = WebUI.getDefault().getPreferenceStore(); - fKeys = createKeys(); - fOverlayStore = new OverlayPreferenceStore(fStore, fKeys); - } - - private OverlayKey[] createKeys() { - ArrayList overlayKeys = new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_JAVADOC)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_HEADERS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_INNERTYPES)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey( - OverlayPreferenceStore.BOOLEAN, - PreferenceConstants.EDITOR_FOLDING_METHODS)); - // overlayKeys.add(new - // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, - // PreferenceConstants.EDITOR_FOLDING_IMPORTS)); - - return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys - .size()]); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) - */ - public Control createControl(Composite composite) { - fOverlayStore.load(); - fOverlayStore.start(); - - Composite inner = new Composite(composite, SWT.NONE); - GridLayout layout = new GridLayout(1, true); - layout.verticalSpacing = 3; - layout.marginWidth = 0; - inner.setLayout(layout); - - Label label = new Label(inner, SWT.LEFT); - label.setText(FoldingMessages - .getString("DefaultJavaFoldingPreferenceBlock.title")); //$NON-NLS-1$ - - addCheckBox( - inner, - FoldingMessages - .getString("DefaultJavaFoldingPreferenceBlock.comments"), PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0); //$NON-NLS-1$ - addCheckBox( - inner, - FoldingMessages - .getString("DefaultJavaFoldingPreferenceBlock.headers"), PreferenceConstants.EDITOR_FOLDING_HEADERS, 0);//$NON-NLS-1$ - addCheckBox(inner, FoldingMessages - .getString("DefaultJavaFoldingPreferenceBlock.innerTypes"), - PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0); //$NON-NLS-1$ - addCheckBox( - inner, - FoldingMessages - .getString("DefaultJavaFoldingPreferenceBlock.methods"), PreferenceConstants.EDITOR_FOLDING_METHODS, 0); //$NON-NLS-1$ - // addCheckBox(inner, - // FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.imports"), - // PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0); //$NON-NLS-1$ - - return inner; - } - - private Button addCheckBox(Composite parent, String label, String key, - int indentation) { - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - gd.horizontalSpan = 1; - gd.grabExcessVerticalSpace = false; - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(fCheckBoxListener); - - fCheckBoxes.put(checkBox, key); - - return checkBox; - } - - private void initializeFields() { - Iterator it = fCheckBoxes.keySet().iterator(); - while (it.hasNext()) { - Button b = (Button) it.next(); - String key = (String) fCheckBoxes.get(b); - b.setSelection(fOverlayStore.getBoolean(key)); - } - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performOk() - */ - public void performOk() { - fOverlayStore.propagate(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#initialize() - */ - public void initialize() { - initializeFields(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performDefaults() - */ - public void performDefaults() { - fOverlayStore.loadDefaults(); - initializeFields(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#dispose() - */ - public void dispose() { - fOverlayStore.stop(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java deleted file mode 100644 index ddac268..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java +++ /dev/null @@ -1,1064 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.folding; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import net.sourceforge.phpdt.core.ElementChangedEvent; -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IElementChangedListener; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaElementDelta; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IParent; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.core.ToolFactory; -import net.sourceforge.phpdt.core.compiler.IScanner; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.projection.IProjectionListener; -import org.eclipse.jface.text.source.projection.IProjectionPosition; -import org.eclipse.jface.text.source.projection.ProjectionAnnotation; -import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Updates the projection model of a class file or compilation unit. - * - * @since 3.0 - */ -public class DefaultJavaFoldingStructureProvider implements - IProjectionListener, IJavaFoldingStructureProvider { - - private static class JavaProjectionAnnotation extends ProjectionAnnotation { - - private IJavaElement fJavaElement; - - private boolean fIsComment; - - public JavaProjectionAnnotation(IJavaElement element, - boolean isCollapsed, boolean isComment) { - super(isCollapsed); - fJavaElement = element; - fIsComment = isComment; - } - - public IJavaElement getElement() { - return fJavaElement; - } - - public void setElement(IJavaElement element) { - fJavaElement = element; - } - - public boolean isComment() { - return fIsComment; - } - - public void setIsComment(boolean isComment) { - fIsComment = isComment; - } - - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return "JavaProjectionAnnotation:\n" + //$NON-NLS-1$ - "\telement: \t" + fJavaElement.toString() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ - "\tcollapsed: \t" + isCollapsed() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ - "\tcomment: \t" + fIsComment + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - private static final class Tuple { - JavaProjectionAnnotation annotation; - - Position position; - - Tuple(JavaProjectionAnnotation annotation, Position position) { - this.annotation = annotation; - this.position = position; - } - } - - private class ElementChangedListener implements IElementChangedListener { - - /* - * @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent) - */ - public void elementChanged(ElementChangedEvent e) { - IJavaElementDelta delta = findElement(fInput, e.getDelta()); - if (delta != null) - processDelta(delta); - } - - private IJavaElementDelta findElement(IJavaElement target, - IJavaElementDelta delta) { - - if (delta == null || target == null) - return null; - - IJavaElement element = delta.getElement(); - - if (element.getElementType() > IJavaElement.CLASS_FILE) - return null; - - if (target.equals(element)) - return delta; - - IJavaElementDelta[] children = delta.getAffectedChildren(); - - for (int i = 0; i < children.length; i++) { - IJavaElementDelta d = findElement(target, children[i]); - if (d != null) - return d; - } - - return null; - } - } - - /** - * Projection position that will return two foldable regions: one folding - * away the region from after the '/**' to the beginning of the content, the - * other from after the first content line until after the comment. - * - * @since 3.1 - */ - private static final class CommentPosition extends Position implements - IProjectionPosition { - CommentPosition(int offset, int length) { - super(offset, length); - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) - */ - public IRegion[] computeProjectionRegions(IDocument document) - throws BadLocationException { - DocumentCharacterIterator sequence = new DocumentCharacterIterator( - document, offset, offset + length); - int prefixEnd = 0; - int contentStart = findFirstContent(sequence, prefixEnd); - - int firstLine = document.getLineOfOffset(offset + prefixEnd); - int captionLine = document.getLineOfOffset(offset + contentStart); - int lastLine = document.getLineOfOffset(offset + length); - - Assert.isTrue(firstLine <= captionLine, - "first folded line is greater than the caption line"); //$NON-NLS-1$ - Assert.isTrue(captionLine <= lastLine, - "caption line is greater than the last folded line"); //$NON-NLS-1$ - - IRegion preRegion; - if (firstLine < captionLine) { - // preRegion= new Region(offset + prefixEnd, contentStart - - // prefixEnd); - int preOffset = document.getLineOffset(firstLine); - IRegion preEndLineInfo = document - .getLineInformation(captionLine); - int preEnd = preEndLineInfo.getOffset(); - preRegion = new Region(preOffset, preEnd - preOffset); - } else { - preRegion = null; - } - - if (captionLine < lastLine) { - int postOffset = document.getLineOffset(captionLine + 1); - IRegion postRegion = new Region(postOffset, offset + length - - postOffset); - - if (preRegion == null) - return new IRegion[] { postRegion }; - - return new IRegion[] { preRegion, postRegion }; - } - - if (preRegion != null) - return new IRegion[] { preRegion }; - - return null; - } - - /** - * Finds the offset of the first identifier part within - * content. Returns 0 if none is found. - * - * @param content - * the content to search - * @return the first index of a unicode identifier part, or zero if none - * can be found - */ - private int findFirstContent(final CharSequence content, int prefixEnd) { - int lenght = content.length(); - for (int i = prefixEnd; i < lenght; i++) { - if (Character.isUnicodeIdentifierPart(content.charAt(i))) - return i; - } - return 0; - } - - // /** - // * Finds the offset of the first identifier part within - // content. - // * Returns 0 if none is found. - // * - // * @param content the content to search - // * @return the first index of a unicode identifier part, or zero if - // none - // can - // * be found - // */ - // private int findPrefixEnd(final CharSequence content) { - // // return the index after the leading '/*' or '/**' - // int len= content.length(); - // int i= 0; - // while (i < len && isWhiteSpace(content.charAt(i))) - // i++; - // if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) - // == - // '*') - // if (len >= i + 3 && content.charAt(i + 2) == '*') - // return i + 3; - // else - // return i + 2; - // else - // return i; - // } - // - // private boolean isWhiteSpace(char c) { - // return c == ' ' || c == '\t'; - // } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) - */ - public int computeCaptionOffset(IDocument document) { - // return 0; - DocumentCharacterIterator sequence = new DocumentCharacterIterator( - document, offset, offset + length); - return findFirstContent(sequence, 0); - } - } - - /** - * Projection position that will return two foldable regions: one folding - * away the lines before the one containing the simple name of the java - * element, one folding away any lines after the caption. - * - * @since 3.1 - */ - private static final class JavaElementPosition extends Position implements - IProjectionPosition { - - private IMember fMember; - - public JavaElementPosition(int offset, int length, IMember member) { - super(offset, length); - Assert.isNotNull(member); - fMember = member; - } - - public void setMember(IMember member) { - Assert.isNotNull(member); - fMember = member; - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) - */ - public IRegion[] computeProjectionRegions(IDocument document) - throws BadLocationException { - int nameStart = offset; - try { - /* - * The member's name range may not be correct. However, - * reconciling would trigger another element delta which would - * lead to reentrant situations. Therefore, we optimistically - * assume that the name range is correct, but double check the - * received lines below. - */ - ISourceRange nameRange = fMember.getNameRange(); - if (nameRange != null) - nameStart = nameRange.getOffset(); - - } catch (JavaModelException e) { - // ignore and use default - } - - int firstLine = document.getLineOfOffset(offset); - int captionLine = document.getLineOfOffset(nameStart); - int lastLine = document.getLineOfOffset(offset + length); - - /* - * see comment above - adjust the caption line to be inside the - * entire folded region, and rely on later element deltas to correct - * the name range. - */ - if (captionLine < firstLine) - captionLine = firstLine; - if (captionLine > lastLine) - captionLine = lastLine; - - IRegion preRegion; - if (firstLine < captionLine) { - int preOffset = document.getLineOffset(firstLine); - IRegion preEndLineInfo = document - .getLineInformation(captionLine); - int preEnd = preEndLineInfo.getOffset(); - preRegion = new Region(preOffset, preEnd - preOffset); - } else { - preRegion = null; - } - - if (captionLine < lastLine) { - int postOffset = document.getLineOffset(captionLine + 1); - IRegion postRegion = new Region(postOffset, offset + length - - postOffset); - - if (preRegion == null) - return new IRegion[] { postRegion }; - - return new IRegion[] { preRegion, postRegion }; - } - - if (preRegion != null) - return new IRegion[] { preRegion }; - - return null; - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) - */ - public int computeCaptionOffset(IDocument document) - throws BadLocationException { - int nameStart = offset; - try { - // need a reconcile here? - ISourceRange nameRange = fMember.getNameRange(); - if (nameRange != null) - nameStart = nameRange.getOffset(); - } catch (JavaModelException e) { - // ignore and use default - } - - return nameStart - offset; - } - - } - - private IDocument fCachedDocument; - - private ProjectionAnnotationModel fCachedModel; - - private ITextEditor fEditor; - - private ProjectionViewer fViewer; - - private IJavaElement fInput; - - private IElementChangedListener fElementListener; - - private boolean fAllowCollapsing = false; - - private boolean fCollapseJavadoc = false; - - // private boolean fCollapseImportContainer = true; - - private boolean fCollapseInnerTypes = true; - - private boolean fCollapseMethods = false; - - private boolean fCollapseHeaderComments = true; - - /* caches for header comment extraction. */ - private IType fFirstType; - - private boolean fHasHeaderComment; - - public DefaultJavaFoldingStructureProvider() { - } - - public void install(ITextEditor editor, ProjectionViewer viewer) { - if (editor instanceof PHPEditor) { - fEditor = editor; - fViewer = viewer; - fViewer.addProjectionListener(this); - } - } - - public void uninstall() { - if (isInstalled()) { - projectionDisabled(); - fViewer.removeProjectionListener(this); - fViewer = null; - fEditor = null; - } - } - - protected boolean isInstalled() { - return fEditor != null; - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled() - */ - public void projectionEnabled() { - // http://home.ott.oti.com/teams/wswb/anon/out/vms/index.html - // projectionEnabled messages are not always paired with - // projectionDisabled - // i.e. multiple enabled messages may be sent out. - // we have to make sure that we disable first when getting an enable - // message. - projectionDisabled(); - - if (fEditor instanceof PHPEditor) { - initialize(); - fElementListener = new ElementChangedListener(); - JavaCore.addElementChangedListener(fElementListener); - } - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled() - */ - public void projectionDisabled() { - fCachedDocument = null; - if (fElementListener != null) { - JavaCore.removeElementChangedListener(fElementListener); - fElementListener = null; - } - } - - public void initialize() { - - if (!isInstalled()) - return; - - initializePreferences(); - - try { - - IDocumentProvider provider = fEditor.getDocumentProvider(); - fCachedDocument = provider.getDocument(fEditor.getEditorInput()); - fAllowCollapsing = true; - - fFirstType = null; - fHasHeaderComment = false; - - if (fEditor instanceof PHPUnitEditor) { - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - fInput = manager.getWorkingCopy(fEditor.getEditorInput()); - } - // else if (fEditor instanceof ClassFileEditor) { - // IClassFileEditorInput editorInput= (IClassFileEditorInput) - // fEditor.getEditorInput(); - // fInput= editorInput.getClassFile(); - // } - - if (fInput != null) { - ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor - .getAdapter(ProjectionAnnotationModel.class); - if (model != null) { - fCachedModel = model; - if (fInput instanceof ICompilationUnit) { - ICompilationUnit unit = (ICompilationUnit) fInput; - synchronized (unit) { - try { - // unit.reconcile(ICompilationUnit.NO_AST, - // false, null, null); - unit.reconcile(); - } catch (JavaModelException x) { - } - } - } - - Map additions = computeAdditions((IParent) fInput); - /* - * Minimize the events being sent out - as this happens in - * the UI thread merge everything into one call. - */ - List removals = new LinkedList(); - Iterator existing = model.getAnnotationIterator(); - while (existing.hasNext()) - removals.add(existing.next()); - model.replaceAnnotations((Annotation[]) removals - .toArray(new Annotation[removals.size()]), - additions); - } - } - - } finally { - fCachedDocument = null; - fCachedModel = null; - fAllowCollapsing = false; - - fFirstType = null; - fHasHeaderComment = false; - } - } - - private void initializePreferences() { - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - fCollapseInnerTypes = store - .getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); - // fCollapseImportContainer = - // store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS); - fCollapseJavadoc = store - .getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); - fCollapseMethods = store - .getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); - fCollapseHeaderComments = store - .getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); - } - - private Map computeAdditions(IParent parent) { - Map map = new LinkedHashMap(); // use a linked map to maintain ordering - // of - // comments - try { - computeAdditions(parent.getChildren(), map); - } catch (JavaModelException x) { - } - return map; - } - - private void computeAdditions(IJavaElement[] elements, Map map) - throws JavaModelException { - for (int i = 0; i < elements.length; i++) { - IJavaElement element = elements[i]; - - computeAdditions(element, map); - - if (element instanceof IParent) { - IParent parent = (IParent) element; - computeAdditions(parent.getChildren(), map); - } - } - } - - private void computeAdditions(IJavaElement element, Map map) { - - boolean createProjection = false; - - boolean collapse = false; - switch (element.getElementType()) { - - // case IJavaElement.IMPORT_CONTAINER: - // collapse = fAllowCollapsing && fCollapseImportContainer; - // createProjection = true; - // break; - case IJavaElement.TYPE: - collapse = fAllowCollapsing; - if (isInnerType((IType) element)) { - collapse = collapse && fCollapseInnerTypes; - } else { - collapse = false; // don't allow the most outer type to be - // folded, may be changed in future versions - } - createProjection = true; - break; - case IJavaElement.METHOD: - collapse = fAllowCollapsing && fCollapseMethods; - createProjection = true; - break; - } - - if (createProjection) { - IRegion[] regions = computeProjectionRanges(element); - if (regions != null) { - // comments - for (int i = 0; i < regions.length - 1; i++) { - Position position = createProjectionPosition(regions[i], - null); - boolean commentCollapse; - if (position != null) { - if (i == 0 && (regions.length > 2 || fHasHeaderComment) - && element == fFirstType) { - commentCollapse = fAllowCollapsing - && fCollapseHeaderComments; - } else { - commentCollapse = fAllowCollapsing - && fCollapseJavadoc; - } - map.put(new JavaProjectionAnnotation(element, - commentCollapse, true), position); - } - } - // code - Position position = createProjectionPosition( - regions[regions.length - 1], element); - if (position != null) - map.put(new JavaProjectionAnnotation(element, collapse, - false), position); - } - } - } - - private boolean isInnerType(IType type) { - - try { - return type.isMember(); - } catch (JavaModelException x) { - IJavaElement parent = type.getParent(); - if (parent != null) { - int parentType = parent.getElementType(); - return (parentType != IJavaElement.COMPILATION_UNIT && parentType != IJavaElement.CLASS_FILE); - } - } - - return false; - } - - /** - * Computes the projection ranges for a given IJavaElement. - * More than one range may be returned if the element has a leading comment - * which gets folded separately. If there are no foldable regions, - * null is returned. - * - * @param element - * the java element that can be folded - * @return the regions to be folded, or null if there are - * none - */ - private IRegion[] computeProjectionRanges(IJavaElement element) { - - try { - if (element instanceof ISourceReference) { - ISourceReference reference = (ISourceReference) element; - ISourceRange range = reference.getSourceRange(); - - String contents = reference.getSource(); - if (contents == null) - return null; - - List regions = new ArrayList(); - // now add all comments first to the regions list - if (fFirstType == null && element instanceof IType) { - fFirstType = (IType) element; - IRegion headerComment = computeHeaderComment(fFirstType); - if (headerComment != null) { - regions.add(headerComment); - fHasHeaderComment = true; - } - } - - final int shift = range.getOffset(); - int start = shift; - if (element instanceof IType) { - Scanner scanner = ToolFactory.createScanner(true, false, - false, false); - scanner.setSource(contents.toCharArray()); - scanner.setPHPMode(true); - - int token = scanner.getNextToken(); - while (token != ITerminalSymbols.TokenNameEOF) { - - token = scanner.getNextToken(); - start = shift + scanner.getCurrentTokenStartPosition(); - - switch (token) { - case ITerminalSymbols.TokenNameCOMMENT_PHPDOC: - case ITerminalSymbols.TokenNameCOMMENT_BLOCK: { - int end = shift - + scanner.getCurrentTokenEndPosition() + 1; - regions.add(new Region(start, end - start)); - } - case ITerminalSymbols.TokenNameCOMMENT_LINE: - continue; - } - } - } - // at the end add the element region - regions.add(new Region(range.getOffset(), range.getLength())); - - if (regions.size() > 0) { - IRegion[] result = new IRegion[regions.size()]; - regions.toArray(result); - return result; - } - - } - } catch (JavaModelException e) { - } catch (InvalidInputException e) { - } - - return null; - } - - private IRegion computeHeaderComment(IType type) throws JavaModelException { - if (fCachedDocument == null) - return null; - - // search at most up to the first type - ISourceRange range = type.getSourceRange(); - if (range == null) - return null; - int start = 0; - int end = range.getOffset(); - - if (fInput instanceof ISourceReference) { - String content; - try { - content = fCachedDocument.get(start, end - start); - } catch (BadLocationException e) { - return null; // ignore header comment in that case - } - - /* - * code adapted from CommentFormattingStrategy: scan the header - * content up to the first type. Once a comment is found, accumulate - * any additional comments up to the stop condition. The stop - * condition is reaching a package declaration, import container, or - * the end of the input. - */ - IScanner scanner = ToolFactory.createScanner(true, false, false, - false); - scanner.setSource(content.toCharArray()); - - int headerStart = -1; - int headerEnd = -1; - try { - boolean foundComment = false; - int terminal = scanner.getNextToken(); - while (terminal != ITerminalSymbols.TokenNameEOF - && !(terminal == ITerminalSymbols.TokenNameclass - || terminal == ITerminalSymbols.TokenNameinterface || foundComment)) { - - if (terminal == ITerminalSymbols.TokenNameCOMMENT_PHPDOC - || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK - || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) { - if (!foundComment) - headerStart = scanner - .getCurrentTokenStartPosition(); - headerEnd = scanner.getCurrentTokenEndPosition(); - foundComment = true; - } - terminal = scanner.getNextToken(); - } - - } catch (InvalidInputException ex) { - return null; - } - - if (headerEnd != -1) { - return new Region(headerStart, headerEnd - headerStart); - } - } - return null; - } - - private Position createProjectionPosition(IRegion region, - IJavaElement element) { - - if (fCachedDocument == null) - return null; - - try { - - int start = fCachedDocument.getLineOfOffset(region.getOffset()); - int end = fCachedDocument.getLineOfOffset(region.getOffset() - + region.getLength()); - if (start != end) { - int offset = fCachedDocument.getLineOffset(start); - int endOffset; - if (fCachedDocument.getNumberOfLines() > end + 1) - endOffset = fCachedDocument.getLineOffset(end + 1); - else if (end > start) - endOffset = fCachedDocument.getLineOffset(end) - + fCachedDocument.getLineLength(end); - else - return null; - if (element instanceof IMember) - return new JavaElementPosition(offset, endOffset - offset, - (IMember) element); - else - return new CommentPosition(offset, endOffset - offset); - } - - } catch (BadLocationException x) { - } - - return null; - } - - protected void processDelta(IJavaElementDelta delta) { - - if (!isInstalled()) - return; - - if ((delta.getFlags() & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_CHILDREN)) == 0) - return; - - ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor - .getAdapter(ProjectionAnnotationModel.class); - if (model == null) - return; - - try { - - IDocumentProvider provider = fEditor.getDocumentProvider(); - fCachedDocument = provider.getDocument(fEditor.getEditorInput()); - fCachedModel = model; - fAllowCollapsing = false; - - fFirstType = null; - fHasHeaderComment = false; - - Map additions = new HashMap(); - List deletions = new ArrayList(); - List updates = new ArrayList(); - - Map updated = computeAdditions((IParent) fInput); - Map previous = createAnnotationMap(model); - - Iterator e = updated.keySet().iterator(); - while (e.hasNext()) { - JavaProjectionAnnotation newAnnotation = (JavaProjectionAnnotation) e - .next(); -//+ - Position newPosition = (Position) updated.get(newAnnotation); - additions.put(newAnnotation, newPosition); -//- -// IJavaElement element = newAnnotation.getElement(); -// Position newPosition = (Position) updated.get(newAnnotation); -// -// List annotations = (List) previous.get(element); -// if (annotations == null) { -// -// additions.put(newAnnotation, newPosition); -// -// } else { -// Iterator x = annotations.iterator(); -// boolean matched = false; -// while (x.hasNext()) { -// Tuple tuple = (Tuple) x.next(); -// JavaProjectionAnnotation existingAnnotation = tuple.annotation; -// Position existingPosition = tuple.position; -// if (newAnnotation.isComment() == existingAnnotation -// .isComment()) { -// if (existingPosition != null -// && (!newPosition.equals(existingPosition))) { -// existingPosition.setOffset(newPosition -// .getOffset()); -// existingPosition.setLength(newPosition -// .getLength()); -// updates.add(existingAnnotation); -// } -// matched = true; -// x.remove(); -// break; -// } -// } -// if (!matched) -// additions.put(newAnnotation, newPosition); -// -// if (annotations.isEmpty()) -// previous.remove(element); -// } -//- - } - - e = previous.values().iterator(); - while (e.hasNext()) { - List list = (List) e.next(); - int size = list.size(); - for (int i = 0; i < size; i++) - deletions.add(((Tuple) list.get(i)).annotation); - } - - match(deletions, additions, updates); - - Annotation[] removals = new Annotation[deletions.size()]; - deletions.toArray(removals); - Annotation[] changes = new Annotation[updates.size()]; - updates.toArray(changes); - model.modifyAnnotations(removals, additions, changes); - - } finally { - fCachedDocument = null; - fAllowCollapsing = true; - fCachedModel = null; - - fFirstType = null; - fHasHeaderComment = false; - } - } - - /** - * Matches deleted annotations to changed or added ones. A deleted - * annotation/position tuple that has a matching addition / change is - * updated and marked as changed. The matching tuple is not added (for - * additions) or marked as deletion instead (for changes). The result is - * that more annotations are changed and fewer get deleted/re-added. - */ - private void match(List deletions, Map additions, List changes) { - if (deletions.isEmpty() || (additions.isEmpty() && changes.isEmpty())) - return; - - List newDeletions = new ArrayList(); - List newChanges = new ArrayList(); - - Iterator deletionIterator = deletions.iterator(); - while (deletionIterator.hasNext()) { - JavaProjectionAnnotation deleted = (JavaProjectionAnnotation) deletionIterator - .next(); - Position deletedPosition = fCachedModel.getPosition(deleted); - if (deletedPosition == null) - continue; - - Tuple deletedTuple = new Tuple(deleted, deletedPosition); - - Tuple match = findMatch(deletedTuple, changes, null); - boolean addToDeletions = true; - if (match == null) { - match = findMatch(deletedTuple, additions.keySet(), additions); - addToDeletions = false; - } - - if (match != null) { - IJavaElement element = match.annotation.getElement(); - deleted.setElement(element); - deletedPosition.setLength(match.position.getLength()); - if (deletedPosition instanceof JavaElementPosition - && element instanceof IMember) { - JavaElementPosition jep = (JavaElementPosition) deletedPosition; - jep.setMember((IMember) element); - } - - deletionIterator.remove(); - newChanges.add(deleted); - - if (addToDeletions) - newDeletions.add(match.annotation); - } - } - - deletions.addAll(newDeletions); - changes.addAll(newChanges); - } - - /** - * Finds a match for tuple in a collection of annotations. - * The positions for the JavaProjectionAnnotation instances - * in annotations can be found in the passed - * positionMap or fCachedModel if - * positionMap is null. - *

- * A tuple is said to match another if their annotations have the same - * comment flag and their position offsets are equal. - *

- *

- * If a match is found, the annotation gets removed from - * annotations. - *

- * - * @param tuple - * the tuple for which we want to find a match - * @param annotations - * collection of JavaProjectionAnnotation - * @param positionMap - * a Map<Annotation, Position> or - * null - * @return a matching tuple or null for no match - */ - private Tuple findMatch(Tuple tuple, Collection annotations, Map positionMap) { - Iterator it = annotations.iterator(); - while (it.hasNext()) { - JavaProjectionAnnotation annotation = (JavaProjectionAnnotation) it - .next(); - if (tuple.annotation.isComment() == annotation.isComment()) { - Position position = positionMap == null ? fCachedModel - .getPosition(annotation) : (Position) positionMap - .get(annotation); - if (position == null) - continue; - - if (tuple.position.getOffset() == position.getOffset()) { - it.remove(); - return new Tuple(annotation, position); - } - } - } - - return null; - } - - private Map createAnnotationMap(IAnnotationModel model) { - Map map = new HashMap(); - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Object annotation = e.next(); - if (annotation instanceof JavaProjectionAnnotation) { - JavaProjectionAnnotation java = (JavaProjectionAnnotation) annotation; - Position position = model.getPosition(java); - Assert.isNotNull(position); - List list = (List) map.get(java.getElement()); - if (list == null) { - list = new ArrayList(2); - map.put(java.getElement(), list); - } - list.add(new Tuple(java, position)); - } - } - - Comparator comparator = new Comparator() { - public int compare(Object o1, Object o2) { - return ((Tuple) o1).position.getOffset() - - ((Tuple) o2).position.getOffset(); - } - }; - for (Iterator it = map.values().iterator(); it.hasNext();) { - List list = (List) it.next(); - Collections.sort(list, comparator); - } - return map; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java deleted file mode 100644 index 2228c68..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.folding; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; - -/** - * @since 3.0 - */ -public class JavaFoldingStructureProviderRegistry { - - private static final String EXTENSION_POINT = "foldingStructureProviders"; //$NON-NLS-1$ - - /** The map of descriptors, indexed by their identifiers. */ - private Map fDescriptors; - - /** - * Creates a new instance. - */ - public JavaFoldingStructureProviderRegistry() { - } - - /** - * Returns an array of IJavaFoldingProviderDescriptor - * describing all extension to the foldingProviders extension - * point. - * - * @return the list of extensions to the - * quickDiffReferenceProvider extension point. - */ - public JavaFoldingStructureProviderDescriptor[] getFoldingProviderDescriptors() { - synchronized (this) { - ensureRegistered(); - return (JavaFoldingStructureProviderDescriptor[]) fDescriptors - .values() - .toArray( - new JavaFoldingStructureProviderDescriptor[fDescriptors - .size()]); - } - } - - /** - * Returns the folding provider with identifier id or - * null if no such provider is registered. - * - * @param id - * the identifier for which a provider is wanted - * @return the corresponding provider, or null if none can be - * found - */ - public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor( - String id) { - synchronized (this) { - ensureRegistered(); - return (JavaFoldingStructureProviderDescriptor) fDescriptors - .get(id); - } - } - - /** - * Instantiates and returns the provider that is currently configured in the - * preferences. - * - * @return the current provider according to the preferences - */ - public IJavaFoldingStructureProvider getCurrentFoldingProvider() { - String id = WebUI.getDefault().getPreferenceStore() - .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); - JavaFoldingStructureProviderDescriptor desc = getFoldingProviderDescriptor(id); - if (desc != null) { - try { - return desc.createProvider(); - } catch (CoreException e) { - WebUI.log(e); - } - } - return null; - } - - /** - * Ensures that the extensions are read and stored in - * fDescriptors. - */ - private void ensureRegistered() { - if (fDescriptors == null) - reloadExtensions(); - } - - /** - * Reads all extensions. - *

- * This method can be called more than once in order to reload from a - * changed extension registry. - *

- */ - public void reloadExtensions() { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - Map map = new HashMap(); - - IConfigurationElement[] elements = registry - .getConfigurationElementsFor(PHPeclipsePlugin.getPluginId(), - EXTENSION_POINT); - for (int i = 0; i < elements.length; i++) { - JavaFoldingStructureProviderDescriptor desc = new JavaFoldingStructureProviderDescriptor( - elements[i]); - map.put(desc.getId(), desc); - } - - synchronized (this) { - fDescriptors = Collections.unmodifiableMap(map); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java deleted file mode 100644 index 9642c6f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java +++ /dev/null @@ -1,218 +0,0 @@ -/*********************************************************************************************************************************** - * Copyright (c) 2000, 2003 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made - * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: IBM Corporation - initial API and implementation - **********************************************************************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -public class JavaReconcilingStrategy implements IReconcilingStrategy, - IReconcilingStrategyExtension { - - private ITextEditor fEditor; - - private IWorkingCopyManager fManager; - - private IDocumentProvider fDocumentProvider; - - private IProgressMonitor fProgressMonitor; - - private boolean fNotify = true; - - private IJavaReconcilingListener fJavaReconcilingListener; - - private boolean fIsJavaReconcilingListener; - - public JavaReconcilingStrategy(ITextEditor editor) { - fEditor = editor; - fManager = WebUI.getDefault().getWorkingCopyManager(); - fDocumentProvider = WebUI.getDefault() - .getCompilationUnitDocumentProvider(); - fIsJavaReconcilingListener = fEditor instanceof IJavaReconcilingListener; - if (fIsJavaReconcilingListener) - fJavaReconcilingListener = (IJavaReconcilingListener) fEditor; - } - - private IProblemRequestorExtension getProblemRequestorExtension() { - IAnnotationModel model = fDocumentProvider.getAnnotationModel(fEditor - .getEditorInput()); - if (model instanceof IProblemRequestorExtension) - return (IProblemRequestorExtension) model; - return null; - } - - private void reconcile() { - // // try { - // - // /* fix for missing cancel flag communication */ - // IProblemRequestorExtension extension = - // getProblemRequestorExtension(); - // if (extension != null) - // extension.setProgressMonitor(fProgressMonitor); - // - // // reconcile - // // synchronized (unit) { - // // unit.reconcile(true, fProgressMonitor); - // // } - // - // Parser parser = new Parser(); - // parser.initializeScanner(); - // // actualParser.setFileToParse(fileToParse); - // String text = - // fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()).get(); - // parser.init(text); - // parser.reportSyntaxError(); - // // checkAndReportBracketAnomalies(parser.problemReporter()); - // - // /* fix for missing cancel flag communication */ - // if (extension != null) - // extension.setProgressMonitor(null); - // - // // update participants - // try { - // if (fEditor instanceof IReconcilingParticipant && fNotify && - // !fProgressMonitor.isCanceled()) { - // IReconcilingParticipant p = (IReconcilingParticipant) fEditor; - // p.reconciled(); - // } - // } finally { - // fNotify = true; - // } - - // JDT implementation: - try { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor - .getEditorInput()); - if (unit != null) { - try { - - /* fix for missing cancel flag communication */ - IProblemRequestorExtension extension = getProblemRequestorExtension(); - if (extension != null) - extension.setProgressMonitor(fProgressMonitor); - - // reconcile - synchronized (unit) { - unit.reconcile(true, fProgressMonitor); - } - - /* fix for missing cancel flag communication */ - if (extension != null) - extension.setProgressMonitor(null); - - // update participants - try { - if (fEditor instanceof IReconcilingParticipant - && fNotify && !fProgressMonitor.isCanceled()) { - IReconcilingParticipant p = (IReconcilingParticipant) fEditor; - p.reconciled(); - } - } finally { - fNotify = true; - } - - } catch (JavaModelException x) { - // swallow exception - } - } - } finally { - // Always notify listeners, see - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=55969 for the final - // solution - try { - if (fIsJavaReconcilingListener) { - IProgressMonitor pm = fProgressMonitor; - if (pm == null) - pm = new NullProgressMonitor(); - fJavaReconcilingListener.reconciled(null, !fNotify, pm); - } - } finally { - fNotify = true; - } - - } - } - - /* - * @see IReconcilingStrategy#reconcile(IRegion) - */ - public void reconcile(IRegion partition) { - reconcile(); - } - - /* - * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - reconcile(); - } - - /* - * @see IReconcilingStrategy#setDocument(IDocument) - */ - public void setDocument(IDocument document) { - } - - /* - * @see IReconcilingStrategyExtension#setProgressMonitor(IProgressMonitor) - */ - public void setProgressMonitor(IProgressMonitor monitor) { - fProgressMonitor = monitor; - } - - /* - * @see IReconcilingStrategyExtension#initialReconcile() - */ - public void initialReconcile() { - reconcile(); - } - - /** - * Tells this strategy whether to inform its participants. - * - * @param notify - * true if participant should be notified - */ -// public void notifyParticipants(boolean notify) { -// fNotify = notify; -// } - - /** - * Tells this strategy whether to inform its listeners. - * - * @param notify - * true if listeners should be notified - */ - public void notifyListeners(boolean notify) { - fNotify = notify; - } - - /** - * Called before reconciling is started. - * - * @since 3.0 - */ - public void aboutToBeReconciled() { - if (fIsJavaReconcilingListener) - fJavaReconcilingListener.aboutToBeReconciled(); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java deleted file mode 100644 index 0f18909..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.java; - -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.texteditor.ITextEditorExtension3; - -/** - * Auto indent strategy for java strings - */ -public class JavaStringAutoIndentStrategyDQ extends - DefaultIndentLineAutoEditStrategy { - - private String fPartitioning; - - /** - * The input string doesn't contain any line delimiter. - * - * @param inputString - * the given input string - * @return the displayable string. - */ - private String displayString(String inputString, String indentation, - String delimiter) { - - int length = inputString.length(); - StringBuffer buffer = new StringBuffer(length); - java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( - inputString, "\n\r", true); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - - String token = tokenizer.nextToken(); - if (token.equals("\r")) { //$NON-NLS-1$ - buffer.append("\\r"); //$NON-NLS-1$ - if (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - if (token.equals("\n")) { //$NON-NLS-1$ - buffer.append("\\n"); //$NON-NLS-1$ - buffer.append("\" . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\""); //$NON-NLS-1$ - continue; - } else { - buffer.append("\" . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\""); //$NON-NLS-1$ - } - } else { - continue; - } - } else if (token.equals("\n")) { //$NON-NLS-1$ - buffer.append("\\n"); //$NON-NLS-1$ - buffer.append("\" . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\""); //$NON-NLS-1$ - continue; - } - - StringBuffer tokenBuffer = new StringBuffer(); - for (int i = 0; i < token.length(); i++) { - char c = token.charAt(i); - switch (c) { - case '\r': - tokenBuffer.append("\\r"); //$NON-NLS-1$ - break; - case '\n': - tokenBuffer.append("\\n"); //$NON-NLS-1$ - break; - case '\b': - tokenBuffer.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - // keep tabs verbatim - tokenBuffer.append("\t"); //$NON-NLS-1$ - break; - case '\f': - tokenBuffer.append("\\f"); //$NON-NLS-1$ - break; - case '\"': - tokenBuffer.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - tokenBuffer.append("\\'"); //$NON-NLS-1$ - break; - case '\\': - tokenBuffer.append("\\\\"); //$NON-NLS-1$ - break; - default: - tokenBuffer.append(c); - } - } - buffer.append(tokenBuffer); - } - return buffer.toString(); - } - - /** - * Creates a new Java string auto indent strategy for the given document - * partitioning. - * - * @param partitioning - * the document partitioning - */ - public JavaStringAutoIndentStrategyDQ(String partitioning) { - super(); - fPartitioning = partitioning; - } - - private boolean isLineDelimiter(IDocument document, String text) { - String[] delimiters = document.getLegalLineDelimiters(); - if (delimiters != null) - return TextUtilities.equals(delimiters, text) > -1; - return false; - } - - private String getLineIndentation(IDocument document, int offset) - throws BadLocationException { - - // find start of line - int adjustedOffset = (offset == document.getLength() ? offset - 1 - : offset); - IRegion line = document.getLineInformationOfOffset(adjustedOffset); - int start = line.getOffset(); - - // find white spaces - int end = findEndOfWhiteSpace(document, start, offset); - - return document.get(start, end - start); - } - - private String getModifiedText(String string, String indentation, - String delimiter) throws BadLocationException { - return displayString(string, indentation, delimiter); - } - - private void javaStringIndentAfterNewLine(IDocument document, - DocumentCommand command) throws BadLocationException { - - ITypedRegion partition = TextUtilities.getPartition(document, - fPartitioning, command.offset, false); - int offset = partition.getOffset(); - int length = partition.getLength(); - - if (command.offset == offset) { - // we are really just before the string partition -> feet the event - // through the java indenter - // new - // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, - // command); - return; - } - - if (command.offset == offset + length - && document.getChar(offset + length - 1) == '\"') - return; - - String indentation = getLineIndentation(document, command.offset); - String delimiter = TextUtilities.getDefaultLineDelimiter(document); - - IRegion line = document.getLineInformationOfOffset(offset); - String string = document.get(line.getOffset(), offset - - line.getOffset()); - if (string.trim().length() != 0) - indentation += String.valueOf("\t\t"); //$NON-NLS-1$ - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - if (isLineDelimiter(document, command.text)) - command.text = "\" ." + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$ - else if (command.text.length() > 1 - && preferenceStore - .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)) - command.text = getModifiedText(command.text, indentation, delimiter); - } - - private boolean isSmartMode() { - IWorkbenchPage page = WebUI.getActivePage(); - if (page != null) { - IEditorPart part = page.getActiveEditor(); - if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension = (ITextEditorExtension3) part; - return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; - } - } - return false; - } - - /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, - * DocumentCommand) - */ - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - try { - if (command.length != 0 || command.text == null) - return; - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - - if (preferenceStore - .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ) - && isSmartMode()) - javaStringIndentAfterNewLine(document, command); - - } catch (BadLocationException e) { - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java deleted file mode 100644 index 72e6e67..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.java; - -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.texteditor.ITextEditorExtension3; - -/** - * Auto indent strategy for java strings - */ -public class JavaStringAutoIndentStrategySQ extends - DefaultIndentLineAutoEditStrategy { - - private String fPartitioning; - - /** - * The input string doesn't contain any line delimiter. - * - * @param inputString - * the given input string - * @return the displayable string. - */ - private String displayString(String inputString, String indentation, - String delimiter) { - - int length = inputString.length(); - StringBuffer buffer = new StringBuffer(length); - java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( - inputString, "\n\r", true); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - - String token = tokenizer.nextToken(); - if (token.equals("\r")) { //$NON-NLS-1$ - buffer.append("\\r"); //$NON-NLS-1$ - if (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - if (token.equals("\n")) { //$NON-NLS-1$ - buffer.append("\\n"); //$NON-NLS-1$ - buffer.append("\' . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\'"); //$NON-NLS-1$ - continue; - } else { - buffer.append("\' . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\'"); //$NON-NLS-1$ - } - } else { - continue; - } - } else if (token.equals("\n")) { //$NON-NLS-1$ - buffer.append("\\n"); //$NON-NLS-1$ - buffer.append("\' . " + delimiter); //$NON-NLS-1$ - buffer.append(indentation); - buffer.append("\'"); //$NON-NLS-1$ - continue; - } - - StringBuffer tokenBuffer = new StringBuffer(); - for (int i = 0; i < token.length(); i++) { - char c = token.charAt(i); - switch (c) { - case '\r': - tokenBuffer.append("\\r"); //$NON-NLS-1$ - break; - case '\n': - tokenBuffer.append("\\n"); //$NON-NLS-1$ - break; - case '\b': - tokenBuffer.append("\\b"); //$NON-NLS-1$ - break; - case '\t': - // keep tabs verbatim - tokenBuffer.append("\t"); //$NON-NLS-1$ - break; - case '\f': - tokenBuffer.append("\\f"); //$NON-NLS-1$ - break; - case '\"': - tokenBuffer.append("\\\""); //$NON-NLS-1$ - break; - case '\'': - tokenBuffer.append("\\'"); //$NON-NLS-1$ - break; - case '\\': - tokenBuffer.append("\\\\"); //$NON-NLS-1$ - break; - default: - tokenBuffer.append(c); - } - } - buffer.append(tokenBuffer); - } - return buffer.toString(); - } - - /** - * Creates a new Java string auto indent strategy for the given document - * partitioning. - * - * @param partitioning - * the document partitioning - */ - public JavaStringAutoIndentStrategySQ(String partitioning) { - super(); - fPartitioning = partitioning; - } - - private boolean isLineDelimiter(IDocument document, String text) { - String[] delimiters = document.getLegalLineDelimiters(); - if (delimiters != null) - return TextUtilities.equals(delimiters, text) > -1; - return false; - } - - private String getLineIndentation(IDocument document, int offset) - throws BadLocationException { - - // find start of line - int adjustedOffset = (offset == document.getLength() ? offset - 1 - : offset); - IRegion line = document.getLineInformationOfOffset(adjustedOffset); - int start = line.getOffset(); - - // find white spaces - int end = findEndOfWhiteSpace(document, start, offset); - - return document.get(start, end - start); - } - - private String getModifiedText(String string, String indentation, - String delimiter) throws BadLocationException { - return displayString(string, indentation, delimiter); - } - - private void javaStringIndentAfterNewLine(IDocument document, - DocumentCommand command) throws BadLocationException { - - ITypedRegion partition = TextUtilities.getPartition(document, - fPartitioning, command.offset, false); - int offset = partition.getOffset(); - int length = partition.getLength(); - - if (command.offset == offset) { - // we are really just before the string partition -> feet the event - // through the java indenter - // new - // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, - // command); - return; - } - - if (command.offset == offset + length - && document.getChar(offset + length - 1) == '\'') - return; - - String indentation = getLineIndentation(document, command.offset); - String delimiter = TextUtilities.getDefaultLineDelimiter(document); - - IRegion line = document.getLineInformationOfOffset(offset); - String string = document.get(line.getOffset(), offset - - line.getOffset()); - if (string.trim().length() != 0) - indentation += String.valueOf("\t\t"); //$NON-NLS-1$ - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - if (isLineDelimiter(document, command.text)) - command.text = "\' ." + command.text + indentation + "\'"; //$NON-NLS-1$//$NON-NLS-2$ - else if (command.text.length() > 1 - && preferenceStore - .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)) - command.text = getModifiedText(command.text, indentation, delimiter); - } - - private boolean isSmartMode() { - IWorkbenchPage page = WebUI.getActivePage(); - if (page != null) { - IEditorPart part = page.getActiveEditor(); - if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension = (ITextEditorExtension3) part; - return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; - } - } - return false; - } - - /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, - * DocumentCommand) - */ - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - try { - if (command.length != 0 || command.text == null) - return; - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - - if (preferenceStore - .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ) - && isSmartMode()) - javaStringIndentAfterNewLine(document, command); - - } catch (BadLocationException e) { - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java deleted file mode 100644 index c1bbbdb..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.util.Iterator; - -import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaAnnotationIterator; -import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; -import org.eclipse.ui.texteditor.IDocumentProvider; - -/** - * Abstract super class for annotation hovers. - * - * @since 3.0 - */ -public abstract class AbstractAnnotationHover extends - AbstractJavaEditorTextHover { - - private IPreferenceStore fStore = WebUI.getDefault() - .getCombinedPreferenceStore(); - - private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); - - private boolean fAllAnnotations; - - public AbstractAnnotationHover(boolean allAnnotations) { - fAllAnnotations = allAnnotations; - } - - /* - * Formats a message as HTML text. - */ - private String formatMessage(String message) { - StringBuffer buffer = new StringBuffer(); - HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter - .convertToHTMLContent(message)); - HTMLPrinter.addPageEpilog(buffer); - return buffer.toString(); - } - - /* - * @see ITextHover#getHoverInfo(ITextViewer, IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - - if (getEditor() == null) - return null; - - IDocumentProvider provider = WebUI.getDefault() - .getCompilationUnitDocumentProvider(); - IAnnotationModel model = provider.getAnnotationModel(getEditor() - .getEditorInput()); - - if (model != null) { - Iterator e = new JavaAnnotationIterator(model, true, - fAllAnnotations); - int layer = -1; - String message = null; - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - - AnnotationPreference preference = getAnnotationPreference(a); - if (preference == null - || !(preference.getTextPreferenceKey() != null - && fStore.getBoolean(preference - .getTextPreferenceKey()) || (preference - .getHighlightPreferenceKey() != null && fStore - .getBoolean(preference - .getHighlightPreferenceKey())))) - continue; - - Position p = model.getPosition(a); - - int l = fAnnotationAccess.getLayer(a); - - if (l > layer - && p != null - && p.overlapsWith(hoverRegion.getOffset(), hoverRegion - .getLength())) { - String msg = a.getText(); - if (msg != null && msg.trim().length() > 0) { - message = msg; - layer = l; - } - } - } - if (layer > -1) - return formatMessage(message); - } - - return null; - } - - /* - * @see IJavaEditorTextHover#setEditor(IEditorPart) - */ - public void setEditor(IEditorPart editor) { - if (editor instanceof PHPUnitEditor) - super.setEditor(editor); - else - super.setEditor(null); - } - - /** - * Returns the annotation preference for the given annotation. - * - * @param annotation - * the annotation - * @return the annotation preference or null if none - */ - private AnnotationPreference getAnnotationPreference(Annotation annotation) { - - if (annotation.isMarkedDeleted()) - return null; - return EditorsUI.getAnnotationPreferenceLookup() - .getAnnotationPreference(annotation); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java deleted file mode 100644 index ba23080..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.util.List; - -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; -import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -//import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorPart; -//import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.commands.ICommand; -//import org.eclipse.ui.commands.ICommandManager; -import org.eclipse.ui.commands.IKeySequenceBinding; -import org.eclipse.ui.keys.KeySequence; -//import org.eclipse.jface.bindings.keys.KeySequence; -/** - * Abstract class for providing hover information for Java elements. - * - * @since 2.1 - */ -public abstract class AbstractJavaEditorTextHover implements - IJavaEditorTextHover { - - private IEditorPart fEditor; - - private ICommand fCommand; - { -// ICommandManager commandManager = PlatformUI.getWorkbench() -// .getCommandSupport().getCommandManager(); - // fCommand= - // commandManager.getCommand(PHPEditorActionDefinitionIds.SHOW_JAVADOC); - // if (!fCommand.isDefined()) - fCommand = null; - } - - /* - * @see IJavaEditorTextHover#setEditor(IEditorPart) - */ - public void setEditor(IEditorPart editor) { - fEditor = editor; - } - - protected IEditorPart getEditor() { - return fEditor; - } - - // protected ICodeAssist getCodeAssist() { - // if (fEditor != null) { - // IEditorInput input= fEditor.getEditorInput(); - // if (input instanceof IClassFileEditorInput) { - // IClassFileEditorInput cfeInput= (IClassFileEditorInput) input; - // return cfeInput.getClassFile(); - // } - // - // IWorkingCopyManager manager= - // PHPeclipsePlugin.getDefault().getWorkingCopyManager(); - // return manager.getWorkingCopy(input); - // } - // - // return null; - // } - - /* - * @see ITextHover#getHoverRegion(ITextViewer, int) - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - return JavaWordFinder.findWord(textViewer.getDocument(), offset); - } - - /* - * @see ITextHover#getHoverInfo(ITextViewer, IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - - // ICodeAssist resolve= getCodeAssist(); - // if (resolve != null) { - // try { - // IJavaElement[] result= null; - // - // synchronized (resolve) { - // result= resolve.codeSelect(hoverRegion.getOffset(), - // hoverRegion.getLength()); - // } - // - // if (result == null) - // return null; - // - // int nResults= result.length; - // if (nResults == 0) - // return null; - // - // return getHoverInfo(result); - // - // } catch (JavaModelException x) { - // PHPeclipsePlugin.log(x.getStatus()); - // } - // } - return null; - } - - /** - * Provides hover information for the given Java elements. - * - * @return the hover information string - * @since 2.1 - */ - protected String getHoverInfo(IJavaElement[] javaElements) { - return null; - } - - /* - * @see ITextHoverExtension#getHoverControlCreator() - * @since 3.0 - */ - public IInformationControlCreator getHoverControlCreator() { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - //incastrix - // return new DefaultInformationControl(parent, SWT.NONE, -// new HTMLTextPresenter(true), -// getTooltipAffordanceString()); - return new DefaultInformationControl(parent, getTooltipAffordanceString(), - new HTMLTextPresenter(true)); - } - }; - } - - /** - * Returns the tool tip affordance string. - * - * @return the affordance string or null if disabled or no - * key binding is defined - * @since 3.0 - */ - protected String getTooltipAffordanceString() { - if (!WebUI.getDefault().getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) - return null; - - KeySequence[] sequences = getKeySequences(); - if (sequences == null) - return null; - - String keySequence = sequences[0].format(); - return JavaHoverMessages.getFormattedString( - "JavaTextHover.makeStickyHint", keySequence); //$NON-NLS-1$ - } - - /** - * Returns the array of valid key sequence bindings for the show tool tip - * description command. - * - * @return the array with the {@link KeySequence}s - * - * @since 3.0 - */ - private KeySequence[] getKeySequences() { - if (fCommand != null) { - List list = fCommand.getKeySequenceBindings(); - if (!list.isEmpty()) { - KeySequence[] keySequences = new KeySequence[list.size()]; - for (int i = 0; i < keySequences.length; i++) { - keySequences[i] = ((IKeySequenceBinding) list.get(i)) - .getKeySequence(); - } - return keySequences; - } - } - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java deleted file mode 100644 index 23c07b9..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.util.Iterator; - -import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; -//import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaAnnotationIterator; -import net.sourceforge.phpeclipse.phpeditor.PHPTextHover; -import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; -import org.eclipse.ui.texteditor.IDocumentProvider; - -public class AnnotationHover extends AbstractJavaEditorTextHover { - - // private IPreferenceStore fStore = - // PHPeclipsePlugin.getDefault().getPreferenceStore(); - private IPreferenceStore fStore = EditorsUI.getPreferenceStore(); - - private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); - - private PHPTextHover fPHPTextHover = null; - - /* - * Formats a message as HTML text. - */ - private String formatMessage(String message) { - StringBuffer buffer = new StringBuffer(); - HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, message); // HTMLPrinter.convertToHTMLContent(message)); - HTMLPrinter.addPageEpilog(buffer); - return buffer.toString(); - } - - /* - * @see ITextHover#getHoverInfo(ITextViewer, IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - - if (getEditor() == null) - return null; - - IDocumentProvider provider = WebUI.getDefault() - .getCompilationUnitDocumentProvider(); - IAnnotationModel model = provider.getAnnotationModel(getEditor() - .getEditorInput()); - String message = null; - if (model != null) { - Iterator e = new JavaAnnotationIterator(model, true); - int layer = -1; - - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - - AnnotationPreference preference = getAnnotationPreference(a); - if (preference == null - || !(fStore.getBoolean(preference - .getTextPreferenceKey()) || (preference - .getHighlightPreferenceKey() != null && fStore - .getBoolean(preference - .getHighlightPreferenceKey())))) - continue; - - Position p = model.getPosition(a); - - int l = fAnnotationAccess.getLayer(a); - - if (l > layer - && p != null - && p.overlapsWith(hoverRegion.getOffset(), hoverRegion - .getLength())) { - String msg = a.getText(); - if (msg != null && msg.trim().length() > 0) { - message = msg; - layer = l; - } - } - } - if (layer > -1) - return formatMessage(message); - } - // Added as long as the above doesn't work - if (fPHPTextHover != null) { - message = fPHPTextHover.getHoverInfo(textViewer, hoverRegion); - if (message != null) { - return formatMessage(message); - } - } - return null; - } - - /* - * @see IJavaEditorTextHover#setEditor(IEditorPart) - */ - public void setEditor(IEditorPart editor) { - if (editor instanceof PHPUnitEditor) { - super.setEditor(editor); - if (editor != null) { - IEditorInput editorInput = editor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - try { - IFile f = ((IFileEditorInput) editorInput).getFile(); - fPHPTextHover = new PHPTextHover(f.getProject()); - return; - } catch (NullPointerException e) { - // this exception occurs, if getTextHover is called by - // preference pages ! - } - } - } - fPHPTextHover = new PHPTextHover(null); - } else { - super.setEditor(null); - } - } - - /** - * Returns the annotation preference for the given annotation. - * - * @param annotation - * the annotation - * @return the annotation preference or null if none - */ - private AnnotationPreference getAnnotationPreference(Annotation annotation) { - - if (annotation.isMarkedDeleted()) - return null; - return EditorsUI.getAnnotationPreferenceLookup() - .getAnnotationPreference(annotation); - } - -// static boolean isJavaProblemHover(String id) { -// return PreferenceConstants.ID_PROBLEM_HOVER.equals(id); -// } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java deleted file mode 100644 index 44c629f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.information.IInformationProviderExtension2; -//import org.eclipse.ui.IEditorPart; - -/** - * Caution: this implementation is a layer breaker and contains some "shortcuts" - */ -public class BestMatchHover extends AbstractJavaEditorTextHover implements - ITextHoverExtension, IInformationProviderExtension2 { - - private List fTextHoverSpecifications; - - private List fInstantiatedTextHovers; - - private ITextHover fBestHover; - - public BestMatchHover() { - installTextHovers(); - } - -// public BestMatchHover(IEditorPart editor) { -// this(); -// setEditor(editor); -// } - - /** - * Installs all text hovers. - */ - private void installTextHovers() { - - // initialize lists - indicates that the initialization happened - fTextHoverSpecifications = new ArrayList(2); - fInstantiatedTextHovers = new ArrayList(2); - - // populate list - JavaEditorTextHoverDescriptor[] hoverDescs = WebUI - .getDefault().getJavaEditorTextHoverDescriptors(); - for (int i = 0; i < hoverDescs.length; i++) { - // ensure that we don't add ourselves to the list - if (!PreferenceConstants.ID_BESTMATCH_HOVER.equals(hoverDescs[i] - .getId())) - fTextHoverSpecifications.add(hoverDescs[i]); - } - } - - private void checkTextHovers() { - if (fTextHoverSpecifications.size() == 0) - return; - - for (Iterator iterator = new ArrayList(fTextHoverSpecifications) - .iterator(); iterator.hasNext();) { - JavaEditorTextHoverDescriptor spec = (JavaEditorTextHoverDescriptor) iterator - .next(); - - IJavaEditorTextHover hover = spec.createTextHover(); - if (hover != null) { - hover.setEditor(getEditor()); - addTextHover(hover); - fTextHoverSpecifications.remove(spec); - } - } - } - - protected void addTextHover(ITextHover hover) { - if (!fInstantiatedTextHovers.contains(hover)) - fInstantiatedTextHovers.add(hover); - } - - /* - * @see ITextHover#getHoverInfo(ITextViewer, IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - - checkTextHovers(); - fBestHover = null; - - if (fInstantiatedTextHovers == null) - return null; - - for (Iterator iterator = fInstantiatedTextHovers.iterator(); iterator - .hasNext();) { - ITextHover hover = (ITextHover) iterator.next(); - - String s = hover.getHoverInfo(textViewer, hoverRegion); - if (s != null && s.trim().length() > 0) { - fBestHover = hover; - return s; - } - } - - return null; - } - - /* - * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() - * @since 3.0 - */ - public IInformationControlCreator getHoverControlCreator() { - if (fBestHover instanceof ITextHoverExtension) - return ((ITextHoverExtension) fBestHover).getHoverControlCreator(); - - return null; - } - - /* - * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() - * @since 3.0 - */ - public IInformationControlCreator getInformationPresenterControlCreator() { - if (fBestHover instanceof IInformationProviderExtension2) - return ((IInformationProviderExtension2) fBestHover) - .getInformationPresenterControlCreator(); - - return null; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java deleted file mode 100644 index 65ce27a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java +++ /dev/null @@ -1,368 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.StringTokenizer; - -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.EditorUtility; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.swt.SWT; -import org.osgi.framework.Bundle; - -/** - * Describes a Java editor text hover. - * - * @since 2.1 - */ -public class JavaEditorTextHoverDescriptor implements Comparable { - - private static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT = "net.sourceforge.phpeclipse.phpEditorTextHovers"; //$NON-NLS-1$ - - private static final String HOVER_TAG = "hover"; //$NON-NLS-1$ - - private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$ - - private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$ - - private static final String LABEL_ATTRIBUTE = "label"; //$NON-NLS-1$ - - private static final String ACTIVATE_PLUG_IN_ATTRIBUTE = "activate"; //$NON-NLS-1$ - - private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ - - public static final String NO_MODIFIER = "0"; //$NON-NLS-1$ - - public static final String DISABLED_TAG = "!"; //$NON-NLS-1$ - - public static final String VALUE_SEPARATOR = ";"; //$NON-NLS-1$ - - private int fStateMask; - - private String fModifierString; - - private boolean fIsEnabled; - - private IConfigurationElement fElement; - - /** - * Returns all Java editor text hovers contributed to the workbench. - */ - public static JavaEditorTextHoverDescriptor[] getContributedHovers() { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - IConfigurationElement[] elements = registry - .getConfigurationElementsFor(JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT); - JavaEditorTextHoverDescriptor[] hoverDescs = createDescriptors(elements); - initializeFromPreferences(hoverDescs); - return hoverDescs; - } - - /** - * Computes the state mask for the given modifier string. - * - * @param modifiers - * the string with the modifiers, separated by '+', '-', ';', ',' - * or '.' - * @return the state mask or -1 if the input is invalid - */ - public static int computeStateMask(String modifiers) { - if (modifiers == null) - return -1; - - if (modifiers.length() == 0) - return SWT.NONE; - - int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, - ",;.:+-* "); //$NON-NLS-1$ - while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility - .findLocalizedModifier(modifierTokenizer.nextToken()); - if (modifier == 0 || (stateMask & modifier) == modifier) - return -1; - stateMask = stateMask | modifier; - } - return stateMask; - } - - /** - * Creates a new Java Editor text hover descriptor from the given - * configuration element. - */ - private JavaEditorTextHoverDescriptor(IConfigurationElement element) { - Assert.isNotNull(element); - fElement = element; - } - - /** - * Creates the Java editor text hover. - */ - public IJavaEditorTextHover createTextHover() { - String pluginId = fElement.getDeclaringExtension().getNamespace(); - boolean isHoversPlugInActivated = Platform.getBundle(pluginId) - .getState() == Bundle.ACTIVE; - if (isHoversPlugInActivated || canActivatePlugIn()) { - try { - return (IJavaEditorTextHover) fElement - .createExecutableExtension(CLASS_ATTRIBUTE); - } catch (CoreException x) { - WebUI.log(new Status(IStatus.ERROR, WebUI - .getPluginId(), 0, JavaHoverMessages - .getString("JavaTextHover.createTextHover"), null)); //$NON-NLS-1$ - } - } - - return null; - } - - // ---- XML Attribute accessors - // --------------------------------------------- - - /** - * Returns the hover's id. - */ - public String getId() { - return fElement.getAttribute(ID_ATTRIBUTE); - } - - /** - * Returns the hover's class name. - */ - public String getHoverClassName() { - return fElement.getAttribute(CLASS_ATTRIBUTE); - } - - /** - * Returns the hover's label. - */ - public String getLabel() { - String label = fElement.getAttribute(LABEL_ATTRIBUTE); - if (label != null) - return label; - - // Return simple class name - label = getHoverClassName(); - int lastDot = label.lastIndexOf('.'); - if (lastDot >= 0 && lastDot < label.length() - 1) - return label.substring(lastDot + 1); - else - return label; - } - - /** - * Returns the hover's description. - * - * @return the hover's description or null if not provided - */ - public String getDescription() { - return fElement.getAttribute(DESCRIPTION_ATTRIBUTE); - } - - public boolean canActivatePlugIn() { - return Boolean.valueOf( - fElement.getAttribute(ACTIVATE_PLUG_IN_ATTRIBUTE)) - .booleanValue(); - } - - public boolean equals(Object obj) { - if (obj == null || !obj.getClass().equals(this.getClass()) - || getId() == null) - return false; - return getId().equals(((JavaEditorTextHoverDescriptor) obj).getId()); - } - - public int hashCode() { - return getId().hashCode(); - } - - /* - * Implements a method from IComparable - */ - public int compareTo(Object o) { - return Collator.getInstance().compare(getLabel(), - ((JavaEditorTextHoverDescriptor) o).getLabel()); - } - - // /** - // * @param descriptor a JavaEditorTextHoverDescriptor - // * @return true if this contributed hover depends on the - // other one - // */ - // public boolean dependsOn(JavaEditorTextHoverDescriptor descriptor) { - // if (descriptor == null) - // return false; - // - // IPluginDescriptor thisPluginDescriptor= - // fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); - // IPluginDescriptor otherPluginDescriptor= - // descriptor.fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); - // return dependsOn(thisPluginDescriptor, otherPluginDescriptor); - // } - - // private boolean dependsOn(IPluginDescriptor descriptor0, - // IPluginDescriptor descriptor1) { - // - // IPluginRegistry registry= Platform.getPluginRegistry(); - // IPluginPrerequisite[] prerequisites= - // descriptor0.getPluginPrerequisites(); - // - // for (int i= 0; i < prerequisites.length; i++) { - // IPluginPrerequisite prerequisite= prerequisites[i]; - // String id= prerequisite.getUniqueIdentifier(); - // IPluginDescriptor descriptor= registry.getPluginDescriptor(id); - // - // if (descriptor != null && (descriptor.equals(descriptor1) || - // dependsOn(descriptor, descriptor1))) - // return true; - // } - // - // return false; - // } - - private static JavaEditorTextHoverDescriptor[] createDescriptors( - IConfigurationElement[] elements) { - List result = new ArrayList(elements.length); - for (int i = 0; i < elements.length; i++) { - IConfigurationElement element = elements[i]; - if (HOVER_TAG.equals(element.getName())) { - JavaEditorTextHoverDescriptor desc = new JavaEditorTextHoverDescriptor( - element); - result.add(desc); - } - } - Collections.sort(result); - return (JavaEditorTextHoverDescriptor[]) result - .toArray(new JavaEditorTextHoverDescriptor[result.size()]); - } - - private static void initializeFromPreferences( - JavaEditorTextHoverDescriptor[] hovers) { - String compiledTextHoverModifiers = WebUI.getDefault() - .getPreferenceStore().getString( - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); - - StringTokenizer tokenizer = new StringTokenizer( - compiledTextHoverModifiers, VALUE_SEPARATOR); - HashMap idToModifier = new HashMap(tokenizer.countTokens() / 2); - - while (tokenizer.hasMoreTokens()) { - String id = tokenizer.nextToken(); - if (tokenizer.hasMoreTokens()) - idToModifier.put(id, tokenizer.nextToken()); - } - - String compiledTextHoverModifierMasks = WebUI.getDefault() - .getPreferenceStore().getString( - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); - - tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, - VALUE_SEPARATOR); - HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); - - while (tokenizer.hasMoreTokens()) { - String id = tokenizer.nextToken(); - if (tokenizer.hasMoreTokens()) - idToModifierMask.put(id, tokenizer.nextToken()); - } - - for (int i = 0; i < hovers.length; i++) { - String modifierString = (String) idToModifier - .get(hovers[i].getId()); - boolean enabled = true; - if (modifierString == null) - modifierString = DISABLED_TAG; - - if (modifierString.startsWith(DISABLED_TAG)) { - enabled = false; - modifierString = modifierString.substring(1); - } - - if (modifierString.equals(NO_MODIFIER)) - modifierString = ""; //$NON-NLS-1$ - - hovers[i].fModifierString = modifierString; - hovers[i].fIsEnabled = enabled; - hovers[i].fStateMask = computeStateMask(modifierString); - if (hovers[i].fStateMask == -1) { - // Fallback: use stored modifier masks - try { - hovers[i].fStateMask = Integer - .parseInt((String) idToModifierMask.get(hovers[i] - .getId())); - } catch (NumberFormatException ex) { - hovers[i].fStateMask = -1; - } - // Fix modifier string - int stateMask = hovers[i].fStateMask; - if (stateMask == -1) - hovers[i].fModifierString = ""; //$NON-NLS-1$ - else - hovers[i].fModifierString = EditorUtility - .getModifierString(stateMask); - } - } - } - - /** - * Returns the configured modifier getStateMask for this hover. - * - * @return the hover modifier stateMask or -1 if no hover is configured - */ - public int getStateMask() { - return fStateMask; - } - - /** - * Returns the modifier String as set in the preference store. - * - * @return the modifier string - */ - public String getModifierString() { - return fModifierString; - } - - /** - * Returns whether this hover is enabled or not. - * - * @return true if enabled - */ - public boolean isEnabled() { - return fIsEnabled; - } - - /** - * Returns this hover descriptors configuration element. - * - * @return the configuration element - * @since 3.0 - */ - public IConfigurationElement getConfigurationElement() { - return fElement; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java deleted file mode 100644 index cd37c94..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java +++ /dev/null @@ -1,225 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. - * 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 - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.IJavaAnnotation; -import net.sourceforge.phpeclipse.phpeditor.JavaMarkerAnnotation; -import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider.ProblemAnnotation; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IInformationControlExtension2; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.CompositeRuler; -import org.eclipse.jface.text.source.IAnnotationAccess; -import org.eclipse.jface.text.source.IAnnotationAccessExtension; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationPresentation; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.ImageUtilities; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; - -/** - * - * - * @since 3.0 - */ -public class JavaExpandHover extends AnnotationExpandHover { - - /** Id of the no breakpoint fake annotation */ - public static final String NO_BREAKPOINT_ANNOTATION = "net.sourceforge.phpdt.internal.ui.NoBreakpointAnnotation"; //$NON-NLS-1$ - - private static class NoBreakpointAnnotation extends Annotation implements - IAnnotationPresentation { - - public NoBreakpointAnnotation() { - super(NO_BREAKPOINT_ANNOTATION, false, JavaHoverMessages - .getString("NoBreakpointAnnotation.addBreakpoint")); - } - - /* - * @see org.eclipse.jface.text.source.IAnnotationPresentation#paint(org.eclipse.swt.graphics.GC, - * org.eclipse.swt.widgets.Canvas, - * org.eclipse.swt.graphics.Rectangle) - */ - public void paint(GC gc, Canvas canvas, Rectangle bounds) { - // draw affordance so the user know she can click here to get a - // breakpoint - Image fImage = PHPUiImages.get(PHPUiImages.IMG_FIELD_PUBLIC); - ImageUtilities.drawImage(fImage, gc, canvas, bounds, SWT.CENTER); - } - - /* - * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() - */ - public int getLayer() { - return IAnnotationPresentation.DEFAULT_LAYER; - } - } - - private AnnotationPreferenceLookup fLookup = new AnnotationPreferenceLookup(); - - private IPreferenceStore fStore = WebUI.getDefault() - .getCombinedPreferenceStore(); - - public JavaExpandHover(CompositeRuler ruler, IAnnotationAccess access, - IDoubleClickListener doubleClickListener) { - super(ruler, access, doubleClickListener); - } - - /* - * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getHoverInfoForLine(org.eclipse.jface.text.source.ISourceViewer, - * int) - */ - protected Object getHoverInfoForLine(final ISourceViewer viewer, - final int line) { - final boolean showTemporaryProblems = PreferenceConstants - .getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_CORRECTION_INDICATION); - IAnnotationModel model = viewer.getAnnotationModel(); - IDocument document = viewer.getDocument(); - - if (model == null) - return null; - - List exact = new ArrayList(); - HashMap messagesAtPosition = new HashMap(); - - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Annotation annotation = (Annotation) e.next(); - - if (fAnnotationAccess instanceof IAnnotationAccessExtension) - if (!((IAnnotationAccessExtension) fAnnotationAccess) - .isPaintable(annotation)) - continue; - - if (annotation instanceof IJavaAnnotation - && !isIncluded((IJavaAnnotation) annotation, - showTemporaryProblems)) - continue; - - AnnotationPreference pref = fLookup - .getAnnotationPreference(annotation); - if (pref != null) { - String key = pref.getVerticalRulerPreferenceKey(); - if (key != null && !fStore.getBoolean(key)) - continue; - } - - Position position = model.getPosition(annotation); - if (position == null) - continue; - - if (compareRulerLine(position, document, line) == 1) { - - if (isDuplicateMessage(messagesAtPosition, position, annotation - .getText())) - continue; - - exact.add(annotation); - } - } - - sort(exact, model); - - if (exact.size() > 0) - setLastRulerMouseLocation(viewer, line); - - if (exact.size() > 0) { - Annotation first = (Annotation) exact.get(0); - if (!isBreakpointAnnotation(first)) - exact.add(0, new NoBreakpointAnnotation()); - } - - if (exact.size() <= 1) - return null; - - AnnotationHoverInput input = new AnnotationHoverInput(); - input.fAnnotations = (Annotation[]) exact.toArray(new Annotation[0]); - input.fViewer = viewer; - input.fRulerInfo = fCompositeRuler; - input.fAnnotationListener = fgListener; - input.fDoubleClickListener = fDblClickListener; - input.redoAction = new AnnotationExpansionControl.ICallback() { - - public void run(IInformationControlExtension2 control) { - control.setInput(getHoverInfoForLine(viewer, line)); - } - - }; - input.model = model; - - return input; - } - - private boolean isIncluded(IJavaAnnotation annotation, - boolean showTemporaryProblems) { - - // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138601 - if (annotation instanceof ProblemAnnotation - && JavaMarkerAnnotation.TASK_ANNOTATION_TYPE.equals(annotation - .getType())) - return false; - - if (!annotation.isProblem()) - return true; - - if (annotation.isMarkedDeleted() && !annotation.hasOverlay()) - return true; - - if (annotation.hasOverlay() && !annotation.isMarkedDeleted()) - return true; - - if (annotation.hasOverlay()) - return (!isIncluded(annotation.getOverlay(), showTemporaryProblems)); - - return showTemporaryProblems; // && - // JavaCorrectionProcessor.hasCorrections((Annotation)annotation); - } - - /* - * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getOrder(org.eclipse.jface.text.source.Annotation) - */ - protected int getOrder(Annotation annotation) { - if (isBreakpointAnnotation(annotation)) - return 1000; - else - return super.getOrder(annotation); - } - - private boolean isBreakpointAnnotation(Annotation a) { - if (a instanceof JavaMarkerAnnotation) { - JavaMarkerAnnotation jma = (JavaMarkerAnnotation) a; - // HACK to get breakpoints to show up first - return jma.getType().equals("org.eclipse.debug.core.breakpoint"); //$NON-NLS-1$ - } - return false; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java deleted file mode 100644 index f8dd369..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import java.io.IOException; - -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; -import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; - -/** - * Provides source as hover info for Java elements. - */ -public class JavaSourceHover extends AbstractJavaEditorTextHover { - - private final int LABEL_FLAGS = JavaElementLabels.ALL_FULLY_QUALIFIED - | JavaElementLabels.M_PRE_RETURNTYPE - | JavaElementLabels.M_PARAMETER_TYPES - | JavaElementLabels.M_PARAMETER_NAMES - | JavaElementLabels.M_EXCEPTIONS - | JavaElementLabels.F_PRE_TYPE_SIGNATURE; - - /* - * @see JavaElementHover - */ - protected String getHoverInfo(IJavaElement[] result) { - int nResults = result.length; - StringBuffer buffer = new StringBuffer(); - - if (nResults > 1) { - - for (int i = 0; i < result.length; i++) { - HTMLPrinter.startBulletList(buffer); - IJavaElement curr = result[i]; - if (curr instanceof IMember) - HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); - HTMLPrinter.endBulletList(buffer); - } - - } else { - - IJavaElement curr = result[0]; - if (curr instanceof IMember && curr instanceof ISourceReference) { - HTMLPrinter.addSmallHeader(buffer, - getInfoText(((IMember) curr))); - try { - String source = ((ISourceReference) curr).getSource(); - source = removeLeadingComments(source); - HTMLPrinter.addParagraph(buffer, "
"); //$NON-NLS-1$
-					HTMLPrinter.addParagraph(buffer, source);
-					HTMLPrinter.addParagraph(buffer, "
"); //$NON-NLS-1$ - } catch (JavaModelException ex) { - // only write small header - } - } - } - - if (buffer.length() > 0) { - HTMLPrinter.insertPageProlog(buffer, 0); - HTMLPrinter.addPageEpilog(buffer); - return buffer.toString(); - } - - return null; - } - - private String getInfoText(IMember member) { - return JavaElementLabels.getElementLabel(member, LABEL_FLAGS); - } - - private String removeLeadingComments(String source) { - PHPCodeReader reader = new PHPCodeReader(); - IDocument document = new Document(source); - int i; - try { - reader.configureForwardReader(document, 0, document.getLength(), - true, false); - int c = reader.read(); - while (c != -1 && (c == '\r' || c == '\n')) { - c = reader.read(); - } - i = reader.getOffset(); - reader.close(); - } catch (IOException ex) { - i = 0; - } finally { - try { - if (reader != null) - reader.close(); - } catch (IOException ex) { - WebUI.log(ex); - } - } - - if (i < 0) - return source; - return source.substring(i); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java deleted file mode 100644 index 9ec2472..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java +++ /dev/null @@ -1,447 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.java.hover; - -import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlExtension; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.FontData; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; - -/** - * Source viewer based implementation of IInformationControl. - * Displays information in a source viewer. - * - * @since 3.0 - */ -public class SourceViewerInformationControl implements IInformationControl, - IInformationControlExtension, DisposeListener { - - /** Border thickness in pixels. */ - private static final int BORDER = 1; - - /** The control's shell */ - private Shell fShell; - - /** The control's text widget */ - private StyledText fText; - - /** The control's source viewer */ - private SourceViewer fViewer; - - /** - * The optional status field. - * - * @since 3.0 - */ - private Label fStatusField; - - /** - * The separator for the optional status field. - * - * @since 3.0 - */ - private Label fSeparator; - - /** - * The font of the optional status text label. - * - * @since 3.0 - */ - private Font fStatusTextFont; - - /** - * Creates a default information control with the given shell as parent. The - * given information presenter is used to process the information to be - * displayed. The given styles are applied to the created styled text - * widget. - * - * @param parent - * the parent shell - * @param shellStyle - * the additional styles for the shell - * @param style - * the additional styles for the styled text widget - */ - public SourceViewerInformationControl(Shell parent, int shellStyle, - int style) { - this(parent, shellStyle, style, null); - } - - /** - * Creates a default information control with the given shell as parent. The - * given information presenter is used to process the information to be - * displayed. The given styles are applied to the created styled text - * widget. - * - * @param parent - * the parent shell - * @param shellStyle - * the additional styles for the shell - * @param style - * the additional styles for the styled text widget - * @param statusFieldText - * the text to be used in the optional status field or - * null if the status field should be hidden - * @since 3.0 - */ - public SourceViewerInformationControl(Shell parent, int shellStyle, - int style, String statusFieldText) { - GridLayout layout; - GridData gd; - - fShell = new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); - Display display = fShell.getDisplay(); - fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); - - Composite composite = fShell; - layout = new GridLayout(1, false); - int border = ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; - layout.marginHeight = border; - layout.marginWidth = border; - composite.setLayout(layout); - gd = new GridData(GridData.FILL_HORIZONTAL); - composite.setLayoutData(gd); - - if (statusFieldText != null) { - composite = new Composite(composite, SWT.NONE); - layout = new GridLayout(1, false); - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - gd = new GridData(GridData.FILL_BOTH); - composite.setLayoutData(gd); - composite.setForeground(display - .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - composite.setBackground(display - .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - } - - // Source viewer - IPreferenceStore store = WebUI.getDefault() - .getCombinedPreferenceStore(); - fViewer = new JavaSourceViewer(composite, null, null, false, style, - store); - fViewer.configure(new PHPSourceViewerConfiguration(WebUI - .getDefault().getJavaTextTools().getColorManager(), store, - null, null)); - fViewer.setEditable(false); - - fText = fViewer.getTextWidget(); - gd = new GridData(GridData.BEGINNING | GridData.FILL_BOTH); - fText.setLayoutData(gd); - fText.setForeground(parent.getDisplay().getSystemColor( - SWT.COLOR_INFO_FOREGROUND)); - fText.setBackground(parent.getDisplay().getSystemColor( - SWT.COLOR_INFO_BACKGROUND)); - - fText.addKeyListener(new KeyListener() { - - public void keyPressed(KeyEvent e) { - if (e.character == 0x1B) // ESC - fShell.dispose(); - } - - public void keyReleased(KeyEvent e) { - } - }); - - // Status field - if (statusFieldText != null) { - - // Horizontal separator line - fSeparator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL - | SWT.LINE_DOT); - fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - // Status field label - fStatusField = new Label(composite, SWT.RIGHT); - fStatusField.setText(statusFieldText); - Font font = fStatusField.getFont(); - FontData[] fontDatas = font.getFontData(); - for (int i = 0; i < fontDatas.length; i++) - fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); - fStatusTextFont = new Font(fStatusField.getDisplay(), fontDatas); - fStatusField.setFont(fStatusTextFont); - GridData gd2 = new GridData(GridData.FILL_VERTICAL - | GridData.FILL_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_BEGINNING - | GridData.VERTICAL_ALIGN_BEGINNING); - fStatusField.setLayoutData(gd2); - - // Regarding the color see bug 41128 - fStatusField.setForeground(display - .getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); - - fStatusField.setBackground(display - .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - } - - addDisposeListener(this); - } - - /** - * Creates a default information control with the given shell as parent. The - * given information presenter is used to process the information to be - * displayed. The given styles are applied to the created styled text - * widget. - * - * @param parent - * the parent shell - * @param style - * the additional styles for the styled text widget - */ - public SourceViewerInformationControl(Shell parent, int style) { - this(parent, SWT.NO_TRIM, style); - } - - /** - * Creates a default information control with the given shell as parent. The - * given information presenter is used to process the information to be - * displayed. The given styles are applied to the created styled text - * widget. - * - * @param parent - * the parent shell - * @param style - * the additional styles for the styled text widget - * @param statusFieldText - * the text to be used in the optional status field or - * null if the status field should be hidden - * @since 3.0 - */ - public SourceViewerInformationControl(Shell parent, int style, - String statusFieldText) { - this(parent, SWT.NO_TRIM, style, statusFieldText); - } - - /** - * Creates a default information control with the given shell as parent. No - * information presenter is used to process the information to be displayed. - * No additional styles are applied to the styled text widget. - * - * @param parent - * the parent shell - */ - public SourceViewerInformationControl(Shell parent) { - this(parent, SWT.NONE); - } - - /** - * Creates a default information control with the given shell as parent. No - * information presenter is used to process the information to be displayed. - * No additional styles are applied to the styled text widget. - * - * @param parent - * the parent shell - * @param statusFieldText - * the text to be used in the optional status field or - * null if the status field should be hidden - * @since 3.0 - */ -// public SourceViewerInformationControl(Shell parent, String statusFieldText) { -// this(parent, SWT.NONE, statusFieldText); -// } - - /* - * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object) - */ - public void setInput(Object input) { - if (input instanceof String) - setInformation((String) input); - else - setInformation(null); - } - - /* - * @see IInformationControl#setInformation(String) - */ - public void setInformation(String content) { - if (content == null) { - fViewer.setInput(null); - return; - } - - IDocument doc = new Document(content); - WebUI.getDefault().getJavaTextTools() - .setupJavaDocumentPartitioner(doc); - - fViewer.setInput(doc); - } - - /* - * @see IInformationControl#setVisible(boolean) - */ - public void setVisible(boolean visible) { - fShell.setVisible(visible); - } - - /** - * {@inheritDoc} - * - * @since 3.0 - */ - public void widgetDisposed(DisposeEvent event) { - if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) - fStatusTextFont.dispose(); - - fStatusTextFont = null; - fShell = null; - fText = null; - } - - /** - * {@inheritDoc} - */ - public final void dispose() { - if (fShell != null && !fShell.isDisposed()) - fShell.dispose(); - else - widgetDisposed(null); - } - - /* - * @see IInformationControl#setSize(int, int) - */ - public void setSize(int width, int height) { - - if (fStatusField != null) { - GridData gd = (GridData) fViewer.getTextWidget().getLayoutData(); - Point statusSize = fStatusField.computeSize(SWT.DEFAULT, - SWT.DEFAULT, true); - Point separatorSize = fSeparator.computeSize(SWT.DEFAULT, - SWT.DEFAULT, true); - gd.heightHint = height - statusSize.y - separatorSize.y; - } - fShell.setSize(width, height); - - if (fStatusField != null) - fShell.pack(true); - } - - /* - * @see IInformationControl#setLocation(Point) - */ - public void setLocation(Point location) { - Rectangle trim = fShell.computeTrim(0, 0, 0, 0); - Point textLocation = fText.getLocation(); - location.x += trim.x - textLocation.x; - location.y += trim.y - textLocation.y; - fShell.setLocation(location); - } - - /* - * @see IInformationControl#setSizeConstraints(int, int) - */ - public void setSizeConstraints(int maxWidth, int maxHeight) { - maxWidth = maxHeight; - } - - /* - * @see IInformationControl#computeSizeHint() - */ - public Point computeSizeHint() { - return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); - } - - /* - * @see IInformationControl#addDisposeListener(DisposeListener) - */ - public void addDisposeListener(DisposeListener listener) { - fShell.addDisposeListener(listener); - } - - /* - * @see IInformationControl#removeDisposeListener(DisposeListener) - */ - public void removeDisposeListener(DisposeListener listener) { - fShell.removeDisposeListener(listener); - } - - /* - * @see IInformationControl#setForegroundColor(Color) - */ - public void setForegroundColor(Color foreground) { - fText.setForeground(foreground); - } - - /* - * @see IInformationControl#setBackgroundColor(Color) - */ - public void setBackgroundColor(Color background) { - fText.setBackground(background); - } - - /* - * @see IInformationControl#isFocusControl() - */ - public boolean isFocusControl() { - return fText.isFocusControl(); - } - - /* - * @see IInformationControl#setFocus() - */ - public void setFocus() { - fShell.forceFocus(); - fText.setFocus(); - } - - /* - * @see IInformationControl#addFocusListener(FocusListener) - */ - public void addFocusListener(FocusListener listener) { - fText.addFocusListener(listener); - } - - /* - * @see IInformationControl#removeFocusListener(FocusListener) - */ - public void removeFocusListener(FocusListener listener) { - fText.removeFocusListener(listener); - } - - /* - * @see IInformationControlExtension#hasContents() - */ - public boolean hasContents() { - return fText.getCharCount() > 0; - } - - protected ISourceViewer getViewer() { - return fViewer; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java deleted file mode 100644 index 56b2f29..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java +++ /dev/null @@ -1,833 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.link; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import net.sourceforge.phpeclipse.ui.WebUI; - -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IPositionUpdater; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.TypedPosition; -//import org.eclipse.jface.text.contentassist.ICompletionProposal; - -/** - * This class manages linked positions in a document. Positions are linked by - * type names. If positions have the same type name, they are considered as - * linked. - * - * The manager remains active on a document until any of the following actions - * occurs: - * - *
    - *
  • A document change is performed which would invalidate any of the above - * constraints.
  • - * - *
  • The method uninstall() is called.
  • - * - *
  • Another instance of LinkedPositionManager tries to gain - * control of the same document. - *
- */ -public class LinkedPositionManager implements IDocumentListener, - IPositionUpdater, IAutoEditStrategy { - - // This class still exists to properly handle code assist. - // This is due to the fact that it cannot be distinguished betweeen document - // changes which are - // issued by code assist and document changes which origin from another text - // viewer. - // There is a conflict in interest since in the latter case the linked mode - // should be left, but in the former case - // the linked mode should remain. - // To support content assist, document changes have to be propagated to - // connected positions - // by registering replace commands using IDocumentExtension. - // if it wasn't for the support of content assist, the documentChanged() - // method could be reduced to - // a simple call to leave(true) - private class Replace implements IDocumentExtension.IReplace { - - private Position fReplacePosition; - - private int fReplaceDeltaOffset; - - private int fReplaceLength; - - private String fReplaceText; - - public Replace(Position position, int deltaOffset, int length, - String text) { - fReplacePosition = position; - fReplaceDeltaOffset = deltaOffset; - fReplaceLength = length; - fReplaceText = text; - } - - public void perform(IDocument document, IDocumentListener owner) { - document.removeDocumentListener(owner); - try { - document.replace(fReplacePosition.getOffset() - + fReplaceDeltaOffset, fReplaceLength, fReplaceText); - } catch (BadLocationException e) { - WebUI.log(e); - // TBD - } - document.addDocumentListener(owner); - } - } - - private static class PositionComparator implements Comparator { - /* - * @see Comparator#compare(Object, Object) - */ - public int compare(Object object0, Object object1) { - Position position0 = (Position) object0; - Position position1 = (Position) object1; - - return position0.getOffset() - position1.getOffset(); - } - } - - private static final String LINKED_POSITION_PREFIX = "LinkedPositionManager.linked.position"; //$NON-NLS-1$ - - private static final Comparator fgPositionComparator = new PositionComparator(); - - private static final Map fgActiveManagers = new HashMap(); - - private static int fgCounter = 0; - - private IDocument fDocument; - - private ILinkedPositionListener fListener; - - private String fPositionCategoryName; - - private boolean fMustLeave; - - /** - * Flag that records the state of this manager. As there are many different - * entities that may call leave or exit, these cannot always be sure whether - * the linked position infrastructure is still active. This is especially - * true for multithreaded situations. - */ - private boolean fIsActive = false; - - /** - * Creates a LinkedPositionManager for a - * IDocument. - * - * @param document - * the document to use with linked positions. - * @param canCoexist - * true if this manager can coexist with an - * already existing one - */ - public LinkedPositionManager(IDocument document, boolean canCoexist) { - Assert.isNotNull(document); - fDocument = document; - fPositionCategoryName = LINKED_POSITION_PREFIX + (fgCounter++); - install(canCoexist); - } - - /** - * Creates a LinkedPositionManager for a - * IDocument. - * - * @param document - * the document to use with linked positions. - */ - public LinkedPositionManager(IDocument document) { - this(document, false); - } - - /** - * Sets a listener to notify changes of current linked position. - */ - public void setLinkedPositionListener(ILinkedPositionListener listener) { - fListener = listener; - } - - /** - * Adds a linked position to the manager with the type being the content of - * the document at the specified range. There are the following constraints - * for linked positions: - * - *
    - *
  • Any two positions have spacing of at least one character. This - * implies that two positions must not overlap.
  • - * - *
  • The string at any position must not contain line delimiters.
  • - *
- * - * @param offset - * the offset of the position. - * @param length - * the length of the position. - */ - public void addPosition(int offset, int length) throws BadLocationException { - String type = fDocument.get(offset, length); - addPosition(offset, length, type); - } - - /** - * Adds a linked position of the specified position type to the manager. - * There are the following constraints for linked positions: - * - *
    - *
  • Any two positions have spacing of at least one character. This - * implies that two positions must not overlap.
  • - * - *
  • The string at any position must not contain line delimiters.
  • - *
- * - * @param offset - * the offset of the position. - * @param length - * the length of the position. - * @param type - * the position type name - any positions with the same type are - * linked. - */ - public void addPosition(int offset, int length, String type) - throws BadLocationException { - Position[] positions = getPositions(fDocument); - - if (positions != null) { - for (int i = 0; i < positions.length; i++) - if (collides(positions[i], offset, length)) - throw new BadLocationException( - LinkedPositionMessages - .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ - } - - String content = fDocument.get(offset, length); - - if (containsLineDelimiters(content)) - throw new BadLocationException( - LinkedPositionMessages - .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ - - try { - fDocument.addPosition(fPositionCategoryName, new TypedPosition( - offset, length, type)); - } catch (BadPositionCategoryException e) { - WebUI.log(e); - Assert.isTrue(false); - } - } - - /** - * Adds a linked position to the manager. The current document content at - * the specified range is taken as the position type. - *

- * There are the following constraints for linked positions: - * - *

    - *
  • Any two positions have spacing of at least one character. This - * implies that two positions must not overlap.
  • - * - *
  • The string at any position must not contain line delimiters.
  • - *
- * - * It is usually best to set the first item in - * additionalChoices to be equal with the text inserted at - * the current position. - *

- * - * @param offset - * the offset of the position. - * @param length - * the length of the position. - * @param additionalChoices - * a number of additional choices to be displayed when selecting - * a position of this type. - */ -// public void addPosition(int offset, int length, -// ICompletionProposal[] additionalChoices) -// throws BadLocationException { -// String type = fDocument.get(offset, length); -// addPosition(offset, length, type, additionalChoices); -// } - - /** - * Adds a linked position of the specified position type to the manager. - * There are the following constraints for linked positions: - * - *
    - *
  • Any two positions have spacing of at least one character. This - * implies that two positions must not overlap.
  • - * - *
  • The string at any position must not contain line delimiters.
  • - *
- * - * It is usually best to set the first item in - * additionalChoices to be equal with the text inserted at - * the current position. - * - * @param offset - * the offset of the position. - * @param length - * the length of the position. - * @param type - * the position type name - any positions with the same type are - * linked. - * @param additionalChoices - * a number of additional choices to be displayed when selecting - * a position of this type. - */ -// public void addPosition(int offset, int length, String type, -// ICompletionProposal[] additionalChoices) -// throws BadLocationException { -// Position[] positions = getPositions(fDocument); -// -// if (positions != null) { -// for (int i = 0; i < positions.length; i++) -// if (collides(positions[i], offset, length)) -// throw new BadLocationException( -// LinkedPositionMessages -// .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ -// } -// -// String content = fDocument.get(offset, length); -// -// if (containsLineDelimiters(content)) -// throw new BadLocationException( -// LinkedPositionMessages -// .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ -// -// try { -// fDocument.addPosition(fPositionCategoryName, new ProposalPosition( -// offset, length, type, additionalChoices)); -// } catch (BadPositionCategoryException e) { -// WebUI.log(e); -// Assert.isTrue(false); -// } -// } - - /** - * Tests if a manager is already active for a document. - */ -// public static boolean hasActiveManager(IDocument document) { -// return fgActiveManagers.get(document) != null; -// } - - private void install(boolean canCoexist) { - - if (fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager - // is already active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - else { - fIsActive = true; - // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), - // IStatus.OK, "LinkedPositionManager activated: - // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ - } - - if (!canCoexist) { - LinkedPositionManager manager = (LinkedPositionManager) fgActiveManagers - .get(fDocument); - if (manager != null) - manager.leave(true); - } - - fgActiveManagers.put(fDocument, this); - fDocument.addPositionCategory(fPositionCategoryName); - fDocument.addPositionUpdater(this); - fDocument.addDocumentListener(this); - - fMustLeave = false; - } - - /** - * Leaves the linked mode. If unsuccessful, the linked positions are - * restored to the values at the time they were added. - */ - public void uninstall(boolean success) { - - if (!fIsActive) - // we migth also just return - ;// JavaPlugin(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager - // activated: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - else { - fDocument.removeDocumentListener(this); - - try { - Position[] positions = getPositions(fDocument); - if ((!success) && (positions != null)) { - // restore - for (int i = 0; i != positions.length; i++) { - TypedPosition position = (TypedPosition) positions[i]; - fDocument.replace(position.getOffset(), position - .getLength(), position.getType()); - } - } - - fDocument.removePositionCategory(fPositionCategoryName); - - fIsActive = false; - // JavaPlugin.log(new Status(IStatus.INFO, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager - // deactivated: "+fPositionCategoryName, new Exception())); - // //$NON-NLS-1$ - - } catch (BadLocationException e) { - WebUI.log(e); - Assert.isTrue(false); - - } catch (BadPositionCategoryException e) { - WebUI.log(e); - Assert.isTrue(false); - - } finally { - fDocument.removePositionUpdater(this); - fgActiveManagers.remove(fDocument); - } - } - - } - - /** - * Returns the position at the given offset, null if there is - * no position. - * - * @since 2.1 - */ - public Position getPosition(int offset) { - Position[] positions = getPositions(fDocument); - if (positions == null) - return null; - - for (int i = positions.length - 1; i >= 0; i--) { - Position position = positions[i]; - if (offset >= position.getOffset() - && offset <= position.getOffset() + position.getLength()) - return positions[i]; - } - - return null; - } - - /** - * Returns the first linked position. - * - * @return returns null if no linked position exist. - */ - public Position getFirstPosition() { - return getNextPosition(-1); - } - - public Position getLastPosition() { - Position[] positions = getPositions(fDocument); - for (int i = positions.length - 1; i >= 0; i--) { - String type = ((TypedPosition) positions[i]).getType(); - int j; - for (j = 0; j != i; j++) - if (((TypedPosition) positions[j]).getType().equals(type)) - break; - - if (j == i) - return positions[i]; - } - - return null; - } - - /** - * Returns the next linked position with an offset greater than - * offset. If another position with the same type and offset - * lower than offset exists, the position is skipped. - * - * @return returns null if no linked position exist. - */ - public Position getNextPosition(int offset) { - Position[] positions = getPositions(fDocument); - return findNextPosition(positions, offset); - } - - private static Position findNextPosition(Position[] positions, int offset) { - // skip already visited types - for (int i = 0; i != positions.length; i++) { - if (positions[i].getOffset() > offset) { - String type = ((TypedPosition) positions[i]).getType(); - int j; - for (j = 0; j != i; j++) - if (((TypedPosition) positions[j]).getType().equals(type)) - break; - - if (j == i) - return positions[i]; - } - } - - return null; - } - - /** - * Returns the position with the greatest offset smaller than - * offset. - * - * @return returns null if no linked position exist. - */ - public Position getPreviousPosition(int offset) { - Position[] positions = getPositions(fDocument); - if (positions == null) - return null; - - TypedPosition currentPosition = (TypedPosition) findCurrentPosition( - positions, offset); - String currentType = currentPosition == null ? null : currentPosition - .getType(); - - Position lastPosition = null; - Position position = getFirstPosition(); - - while (position != null && position.getOffset() < offset) { - if (!((TypedPosition) position).getType().equals(currentType)) - lastPosition = position; - position = findNextPosition(positions, position.getOffset()); - } - - return lastPosition; - } - - private Position[] getPositions(IDocument document) { - - if (!fIsActive) - // we migth also just return an empty array - ;// JavaPlugin(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager - // is not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - - try { - Position[] positions = document.getPositions(fPositionCategoryName); - Arrays.sort(positions, fgPositionComparator); - return positions; - - } catch (BadPositionCategoryException e) { - WebUI.log(e); - Assert.isTrue(false); - } - - return null; - } - - public static boolean includes(Position position, int offset, int length) { - return (offset >= position.getOffset()) - && (offset + length <= position.getOffset() - + position.getLength()); - } - -// public static boolean excludes(Position position, int offset, int length) { -// return (offset + length <= position.getOffset()) -// || (position.getOffset() + position.getLength() <= offset); -// } - - /* - * Collides if spacing if positions intersect each other or are adjacent. - */ - private static boolean collides(Position position, int offset, int length) { - return (offset <= position.getOffset() + position.getLength()) - && (position.getOffset() <= offset + length); - } - - private void leave(boolean success) { - try { - uninstall(success); - - if (fListener != null) - fListener.exit((success ? LinkedPositionUI.COMMIT : 0) - | LinkedPositionUI.UPDATE_CARET); - } finally { - fMustLeave = false; - } - } - - private void abort() { - uninstall(true); // don't revert anything - - if (fListener != null) - fListener.exit(LinkedPositionUI.COMMIT); // don't let the UI - // restore anything - - // don't set fMustLeave, as we will get re-registered by a document - // event - } - - /* - * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - - if (fMustLeave) { - event.getDocument().removeDocumentListener(this); - return; - } - - IDocument document = event.getDocument(); - - Position[] positions = getPositions(document); - Position position = findCurrentPosition(positions, event.getOffset()); - - // modification outside editable position - if (position == null) { - // check for destruction of constraints (spacing of at least 1) - if ((event.getText() == null || event.getText().length() == 0) - && (findCurrentPosition(positions, event.getOffset()) != null) - && // will never become true, see condition above - (findCurrentPosition(positions, event.getOffset() - + event.getLength()) != null)) { - leave(true); - } - - // modification intersects editable position - } else { - // modificaction inside editable position - if (includes(position, event.getOffset(), event.getLength())) { - if (containsLineDelimiters(event.getText())) - leave(true); - - // modificaction exceeds editable position - } else { - leave(true); - } - } - } - - /* - * @see IDocumentListener#documentChanged(DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - - // have to handle code assist, so can't just leave the linked mode - // leave(true); - - IDocument document = event.getDocument(); - - Position[] positions = getPositions(document); - TypedPosition currentPosition = (TypedPosition) findCurrentPosition( - positions, event.getOffset()); - - // ignore document changes (assume it won't invalidate constraints) - if (currentPosition == null) - return; - - int deltaOffset = event.getOffset() - currentPosition.getOffset(); - - if (fListener != null) { - int length = event.getText() == null ? 0 : event.getText().length(); - fListener.setCurrentPosition(currentPosition, deltaOffset + length); - } - - for (int i = 0; i != positions.length; i++) { - TypedPosition p = (TypedPosition) positions[i]; - - if (p.getType().equals(currentPosition.getType()) - && !p.equals(currentPosition)) { - Replace replace = new Replace(p, deltaOffset, - event.getLength(), event.getText()); - ((IDocumentExtension) document) - .registerPostNotificationReplace(this, replace); - } - } - } - - /* - * @see IPositionUpdater#update(DocumentEvent) - */ - public void update(DocumentEvent event) { - - int eventOffset = event.getOffset(); - int eventOldLength = event.getLength(); - int eventNewLength = event.getText() == null ? 0 : event.getText() - .length(); - int deltaLength = eventNewLength - eventOldLength; - - Position[] positions = getPositions(event.getDocument()); - - for (int i = 0; i != positions.length; i++) { - - Position position = positions[i]; - - if (position.isDeleted()) - continue; - - int offset = position.getOffset(); - int length = position.getLength(); - int end = offset + length; - - if (offset > eventOffset + eventOldLength) // position comes way - // after change - shift - position.setOffset(offset + deltaLength); - else if (end < eventOffset) // position comes way before change - - // leave alone - ; - else if (offset <= eventOffset - && end >= eventOffset + eventOldLength) { - // event completely internal to the position - adjust length - position.setLength(length + deltaLength); - } else if (offset < eventOffset) { - // event extends over end of position - adjust length - int newEnd = eventOffset + eventNewLength; - position.setLength(newEnd - offset); - } else if (end > eventOffset + eventOldLength) { - // event extends from before position into it - adjust offset - // and length - // offset becomes end of event, length ajusted acordingly - // we want to recycle the overlapping part - int newOffset = eventOffset + eventNewLength; - position.setOffset(newOffset); - position.setLength(length + deltaLength); - } else { - // event consumes the position - delete it - position.delete(); - // JavaPlugin.log(new Status(IStatus.INFO, - // JavaPlugin.getPluginId(), IStatus.OK, "linked position - // deleted -> must leave: "+fPositionCategoryName, null)); - // //$NON-NLS-1$ - fMustLeave = true; - } - } - - if (fMustLeave) - abort(); - } - - private static Position findCurrentPosition(Position[] positions, int offset) { - for (int i = 0; i != positions.length; i++) - if (includes(positions[i], offset, 0)) - return positions[i]; - - return null; - } - - private boolean containsLineDelimiters(String string) { - - if (string == null) - return false; - - String[] delimiters = fDocument.getLegalLineDelimiters(); - - for (int i = 0; i != delimiters.length; i++) - if (string.indexOf(delimiters[i]) != -1) - return true; - - return false; - } - - /** - * Test if ok to modify through UI. - */ - public boolean anyPositionIncludes(int offset, int length) { - Position[] positions = getPositions(fDocument); - - Position position = findCurrentPosition(positions, offset); - if (position == null) - return false; - - return includes(position, offset, length); - } - - /** - * Returns the position that includes the given range. - * - * @param offset - * @param length - * @return position that includes the given range - */ - public Position getEmbracingPosition(int offset, int length) { - Position[] positions = getPositions(fDocument); - - Position position = findCurrentPosition(positions, offset); - if (position != null && includes(position, offset, length)) - return position; - - return null; - } - - /* - * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.DocumentCommand) - */ - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - - if (fMustLeave) { - leave(true); - return; - } - - // don't interfere with preceding auto edit strategies - if (command.getCommandCount() != 1) { - leave(true); - return; - } - - Position[] positions = getPositions(document); - TypedPosition currentPosition = (TypedPosition) findCurrentPosition( - positions, command.offset); - - // handle edits outside of a position - if (currentPosition == null) { - leave(true); - return; - } - - if (!command.doit) - return; - - command.doit = false; - command.owner = this; - command.caretOffset = command.offset + command.length; - - int deltaOffset = command.offset - currentPosition.getOffset(); - - if (fListener != null) - fListener.setCurrentPosition(currentPosition, deltaOffset - + command.text.length()); - - for (int i = 0; i != positions.length; i++) { - TypedPosition position = (TypedPosition) positions[i]; - - try { - if (position.getType().equals(currentPosition.getType()) - && !position.equals(currentPosition)) - command.addCommand(position.getOffset() + deltaOffset, - command.length, command.text, this); - } catch (BadLocationException e) { - WebUI.log(e); - } - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java deleted file mode 100644 index d9e63ed..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java +++ /dev/null @@ -1,974 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.link; - -import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DefaultPositionUpdater; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IPositionUpdater; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.IRewriteTarget; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextEvent; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.events.ShellEvent; -import org.eclipse.swt.events.ShellListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; - -/** - * A user interface for LinkedPositionManager, using - * ITextViewer. - */ -public class LinkedPositionUI implements ILinkedPositionListener, - ITextInputListener, ITextListener, ModifyListener, VerifyListener, - VerifyKeyListener, PaintListener, IPropertyChangeListener, - ShellListener { - - /** - * A listener for notification when the user cancelled the edit operation. - */ - public interface ExitListener { - void exit(boolean accept); - } - - public static class ExitFlags { - public int flags; - - public boolean doit; - - public ExitFlags(int flags, boolean doit) { - this.flags = flags; - this.doit = doit; - } - } - - public interface ExitPolicy { - ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, - int offset, int length); - } - - // leave flags - private static final int UNINSTALL = 1; // uninstall linked position manager - - public static final int COMMIT = 2; // commit changes - - private static final int DOCUMENT_CHANGED = 4; // document has changed - - public static final int UPDATE_CARET = 8; // update caret - - private static final IPreferenceStore fgStore = WebUI - .getDefault().getPreferenceStore(); - - private static final String CARET_POSITION_PREFIX = "LinkedPositionUI.caret.position"; //$NON-NLS-1$ - - private static int fgCounter = 0; - - private final ITextViewer fViewer; - - private final LinkedPositionManager fManager; - - private final IPositionUpdater fUpdater; - - private final String fPositionCategoryName; - - private Color fFrameColor; - - private int fFinalCaretOffset = -1; // no final caret offset - - private Position fFinalCaretPosition; - - private Position fFramePosition; - - private int fInitialOffset = -1; - - private int fCaretOffset; - - private ExitPolicy fExitPolicy; - - private ExitListener fExitListener; - - private boolean fNeedRedraw; - - private String fContentType; - - private Position fPreviousPosition; - - // private ContentAssistant2 fAssistant; - - /** - * Flag that records the state of this ui object. As there are many - * different entities that may call leave or exit, these cannot always be - * sure whether the linked position infrastructure is still active. This is - * especially true for multithreaded situations. - */ - private boolean fIsActive = false; - - /** - * Creates a user interface for LinkedPositionManager. - * - * @param viewer - * the text viewer. - * @param manager - * the LinkedPositionManager managing a - * IDocument of the ITextViewer. - */ - public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) { - Assert.isNotNull(viewer); - Assert.isNotNull(manager); - - fViewer = viewer; - fManager = manager; - - fPositionCategoryName = CARET_POSITION_PREFIX + (fgCounter++); - fUpdater = new DefaultPositionUpdater(fPositionCategoryName); - - fManager.setLinkedPositionListener(this); - - initializeHighlightColor(viewer); - } - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals( - PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) { - initializeHighlightColor(fViewer); - redrawRegion(); - } - } - - private void initializeHighlightColor(ITextViewer viewer) { - - if (fFrameColor != null) - fFrameColor.dispose(); - - StyledText text = viewer.getTextWidget(); - if (text != null) { - Display display = text.getDisplay(); - fFrameColor = createColor(fgStore, - PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, display); - } - } - - /** - * Creates a color from the information stored in the given preference - * store. Returns null if there is no such information - * available. - */ - private Color createColor(IPreferenceStore store, String key, - Display display) { - - RGB rgb = null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb = PreferenceConverter.getDefaultColor(store, key); - else - rgb = PreferenceConverter.getColor(store, key); - - if (rgb != null) - return new Color(display, rgb); - } - - return null; - } - - /** - * Sets the initial offset. - * - * @param offset - */ -// public void setInitialOffset(int offset) { -// fInitialOffset = offset; -// } - - /** - * Sets the final position of the caret when the linked mode is exited - * successfully by leaving the last linked position using TAB. The set - * position will be a TAB stop as well as the positions configured in the - * LinkedPositionManager. - */ - public void setFinalCaretOffset(int offset) { - fFinalCaretOffset = offset; - } - - /** - * Sets a CancelListener which is notified if the linked mode - * is exited unsuccessfully by hitting ESC. - */ - public void setCancelListener(ExitListener listener) { - fExitListener = listener; - } - - /** - * Sets an ExitPolicy which decides when and how the linked - * mode is exited. - */ - public void setExitPolicy(ExitPolicy policy) { - fExitPolicy = policy; - } - - /* - * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, - * int) - */ - public void setCurrentPosition(Position position, int caretOffset) { - if (!fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - - if (!fFramePosition.equals(position)) { - fNeedRedraw = true; - fFramePosition = position; - } - - fCaretOffset = caretOffset; - } - - /** - * Enters the linked mode. The linked mode can be left by calling - * exit. - * - * @see #exit(boolean) - */ - public void enter() { - if (fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // already active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - else { - fIsActive = true; - // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), - // IStatus.OK, "LinkedPositionUI activated: "+fPositionCategoryName, - // new Exception())); //$NON-NLS-1$ - } - - // track final caret - IDocument document = fViewer.getDocument(); - document.addPositionCategory(fPositionCategoryName); - document.addPositionUpdater(fUpdater); - - try { - if (fFinalCaretOffset != -1) { - fFinalCaretPosition = new Position(fFinalCaretOffset); - document - .addPosition(fPositionCategoryName, fFinalCaretPosition); - } - } catch (BadLocationException e) { - handleException(fViewer.getTextWidget().getShell(), e); - - } catch (BadPositionCategoryException e) { - WebUI.log(e); - Assert.isTrue(false); - } - - fViewer.addTextInputListener(this); - fViewer.addTextListener(this); - - ITextViewerExtension extension = (ITextViewerExtension) fViewer; - extension.prependVerifyKeyListener(this); - - StyledText text = fViewer.getTextWidget(); - text.addVerifyListener(this); - text.addModifyListener(this); - text.addPaintListener(this); - text.showSelection(); - - Shell shell = text.getShell(); - shell.addShellListener(this); - - fFramePosition = (fInitialOffset == -1) ? fManager.getFirstPosition() - : fManager.getPosition(fInitialOffset); - if (fFramePosition == null) { - leave(UNINSTALL | COMMIT | UPDATE_CARET); - return; - } - - fgStore.addPropertyChangeListener(this); - - // try { - // fContentType= TextUtilities.getContentType(document, - // IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset); - // if (fViewer instanceof ITextViewerExtension2) { - // ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, - // fContentType); - // } else { - // Assert.isTrue(false); - // } - // - // } catch (BadLocationException e) { - // handleException(fViewer.getTextWidget().getShell(), e); - // } - try { - fContentType = document.getContentType(fFramePosition.offset); - if (fViewer instanceof ITextViewerExtension2) { - ((ITextViewerExtension2) fViewer).prependAutoEditStrategy( - fManager, fContentType); - } else { - Assert.isTrue(false); - } - - } catch (BadLocationException e) { - handleException(fViewer.getTextWidget().getShell(), e); - } - selectRegion(); - // triggerContentAssist(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.link.ILinkedPositionListener#exit(boolean) - */ - public void exit(int flags) { - leave(flags); - } - - /** - * Returns the cursor selection, after having entered the linked mode. - * enter() must be called prior to a call to this method. - */ - public IRegion getSelectedRegion() { - if (!fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - - if (fFramePosition == null) - return new Region(fFinalCaretOffset, 0); - else - return new Region(fFramePosition.getOffset(), fFramePosition - .getLength()); - } - - private void leave(int flags) { - if (!fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - else { - fIsActive = false; - // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), - // IStatus.OK, "LinkedPositionUI deactivated: - // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ - } - - fInitialOffset = -1; - - if ((flags & UNINSTALL) != 0) - fManager.uninstall((flags & COMMIT) != 0); - - fgStore.removePropertyChangeListener(this); - - if (fFrameColor != null) { - fFrameColor.dispose(); - fFrameColor = null; - } - - StyledText text = fViewer.getTextWidget(); - // bail out if the styled text is null, meaning the viewer has been - // disposed (-> document is null as well) - // see pr https://bugs.eclipse.org/bugs/show_bug.cgi?id=46821 - if (text == null) - return; - - text.removePaintListener(this); - text.removeModifyListener(this); - text.removeVerifyListener(this); - - Shell shell = text.getShell(); - shell.removeShellListener(this); - - // if (fAssistant != null) { - // Display display= text.getDisplay(); - // if (display != null && !display.isDisposed()) { - // display.asyncExec(new Runnable() { - // public void run() { - // if (fAssistant != null) { - // fAssistant.uninstall(); - // fAssistant= null; - // } - // } - // }); - // } - // } - - ITextViewerExtension extension = (ITextViewerExtension) fViewer; - extension.removeVerifyKeyListener(this); - - IRewriteTarget target = extension.getRewriteTarget(); - target.endCompoundChange(); - - if (fViewer instanceof ITextViewerExtension2 && fContentType != null) - ((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, - fContentType); - fContentType = null; - - fViewer.removeTextListener(this); - fViewer.removeTextInputListener(this); - - try { - IDocument document = fViewer.getDocument(); - - if (((flags & COMMIT) != 0) && ((flags & DOCUMENT_CHANGED) == 0) - && ((flags & UPDATE_CARET) != 0)) { - Position[] positions = document - .getPositions(fPositionCategoryName); - if ((positions != null) && (positions.length != 0)) { - - if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension3 = (ITextViewerExtension5) fViewer; - int widgetOffset = extension3 - .modelOffset2WidgetOffset(positions[0] - .getOffset()); - if (widgetOffset >= 0) - text.setSelection(widgetOffset, widgetOffset); - - } else { - IRegion region = fViewer.getVisibleRegion(); - int offset = positions[0].getOffset() - - region.getOffset(); - if ((offset >= 0) && (offset <= region.getLength())) - text.setSelection(offset, offset); - } - } - } - - document.removePositionUpdater(fUpdater); - document.removePositionCategory(fPositionCategoryName); - - if (fExitListener != null) - fExitListener.exit(((flags & COMMIT) != 0) - || ((flags & DOCUMENT_CHANGED) != 0)); - - } catch (BadPositionCategoryException e) { - WebUI.log(e); - Assert.isTrue(false); - } - - if ((flags & DOCUMENT_CHANGED) == 0) - text.redraw(); - } - - private void next() { - if (!fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - - redrawRegion(); - - if (fFramePosition == fFinalCaretPosition) - fFramePosition = fManager.getFirstPosition(); - else - fFramePosition = fManager.getNextPosition(fFramePosition - .getOffset()); - if (fFramePosition == null) { - if (fFinalCaretPosition != null) - fFramePosition = fFinalCaretPosition; - else - fFramePosition = fManager.getFirstPosition(); - } - if (fFramePosition == null) { - leave(UNINSTALL | COMMIT | UPDATE_CARET); - } else { - selectRegion(); - // triggerContentAssist(); - redrawRegion(); - } - } - - private void previous() { - if (!fIsActive) - ;// JavaPlugin.log(new Status(IStatus.WARNING, - // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is - // not active: "+fPositionCategoryName, new - // IllegalStateException())); //$NON-NLS-1$ - - redrawRegion(); - - fFramePosition = fManager.getPreviousPosition(fFramePosition - .getOffset()); - if (fFramePosition == null) { - if (fFinalCaretPosition != null) - fFramePosition = fFinalCaretPosition; - else - fFramePosition = fManager.getLastPosition(); - } - if (fFramePosition == null) { - leave(UNINSTALL | COMMIT | UPDATE_CARET); - } else { - selectRegion(); - // triggerContentAssist(); - redrawRegion(); - } - } - - /** Trigger content assist on choice positions */ - // private void triggerContentAssist() { - // if (fFramePosition instanceof ProposalPosition) { - // - // ProposalPosition pp= (ProposalPosition) fFramePosition; - // initializeContentAssistant(); - // if (fAssistant == null) - // return; - // fAssistant.setCompletions(pp.getChoices()); - // fAssistant.showPossibleCompletions(); - // } else { - // if (fAssistant != null) - // fAssistant.setCompletions(new ICompletionProposal[0]); - // } - // } - /** Lazy initialize content assistant for this linked ui */ - // private void initializeContentAssistant() { - // if (fAssistant != null) - // return; - // fAssistant= new ContentAssistant2(); - // fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); - // fAssistant.install(fViewer); - // } - /* - * @see VerifyKeyListener#verifyKey(VerifyEvent) - */ - public void verifyKey(VerifyEvent event) { - - if (!event.doit || !fIsActive) - return; - - Point selection = fViewer.getSelectedRange(); - int offset = selection.x; - int length = selection.y; - - ExitFlags exitFlags = fExitPolicy == null ? null : fExitPolicy.doExit( - fManager, event, offset, length); - if (exitFlags != null) { - leave(UNINSTALL | exitFlags.flags); - event.doit = exitFlags.doit; - return; - } - - switch (event.character) { - // [SHIFT-]TAB = hop between edit boxes - case 0x09: { - // if tab was treated as a document change, would it exceed variable - // range? - if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { - leave(UNINSTALL | COMMIT); - return; - } - } - - if (event.stateMask == SWT.SHIFT) - previous(); - else - next(); - - event.doit = false; - break; - - // ENTER - case 0x0A: // Ctrl+Enter - case 0x0D: { - // if (fAssistant != null && fAssistant.wasProposalChosen()) { - // next(); - // event.doit= false; - // break; - // } - - // if enter was treated as a document change, would it exceed - // variable range? - if (!LinkedPositionManager.includes(fFramePosition, offset, length) - || (fFramePosition == fFinalCaretPosition)) { - leave(UNINSTALL | COMMIT); - return; - } - } - - leave(UNINSTALL | COMMIT | UPDATE_CARET); - event.doit = false; - break; - - // ESC - case 0x1B: - leave(UNINSTALL | COMMIT); - event.doit = false; - break; - - case ';': - leave(UNINSTALL | COMMIT); - event.doit = true; - break; - - default: - if (event.character != 0) { - if (!controlUndoBehavior(offset, length) - || fFramePosition == fFinalCaretPosition) { - leave(UNINSTALL | COMMIT); - break; - } - } - } - } - - private boolean controlUndoBehavior(int offset, int length) { - - Position position = fManager.getEmbracingPosition(offset, length); - if (position != null) { - - ITextViewerExtension extension = (ITextViewerExtension) fViewer; - IRewriteTarget target = extension.getRewriteTarget(); - - if (fPreviousPosition != null - && !fPreviousPosition.equals(position)) - target.endCompoundChange(); - target.beginCompoundChange(); - } - - fPreviousPosition = position; - return fPreviousPosition != null; - } - - /* - * @see VerifyListener#verifyText(VerifyEvent) - */ - public void verifyText(VerifyEvent event) { - if (!event.doit) - return; - - int offset = 0; - int length = 0; - - if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; - IRegion modelRange = extension.widgetRange2ModelRange(new Region( - event.start, event.end - event.start)); - if (modelRange == null) - return; - - offset = modelRange.getOffset(); - length = modelRange.getLength(); - - } else { - IRegion visibleRegion = fViewer.getVisibleRegion(); - offset = event.start + visibleRegion.getOffset(); - length = event.end - event.start; - } - - // allow changes only within linked positions when coming through UI - if (!fManager.anyPositionIncludes(offset, length)) - leave(UNINSTALL | COMMIT); - } - - /* - * @see PaintListener#paintControl(PaintEvent) - */ - public void paintControl(PaintEvent event) { - if (fFramePosition == null) - return; - - IRegion widgetRange = asWidgetRange(fFramePosition); - if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; - } - - int offset = widgetRange.getOffset(); - int length = widgetRange.getLength(); - - StyledText text = fViewer.getTextWidget(); - - // support for bidi - Point minLocation = getMinimumLocation(text, offset, length); - Point maxLocation = getMaximumLocation(text, offset, length); - - int x1 = minLocation.x; - int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; - int y = minLocation.y + text.getLineHeight() - 1; - - GC gc = event.gc; - gc.setForeground(fFrameColor); - gc.drawLine(x1, y, x2, y); - } - - protected IRegion asWidgetRange(Position position) { - if (fViewer instanceof ITextViewerExtension5) { - - ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; - return extension.modelRange2WidgetRange(new Region(position - .getOffset(), position.getLength())); - - } else { - - IRegion region = fViewer.getVisibleRegion(); - if (includes(region, position)) - return new Region(position.getOffset() - region.getOffset(), - position.getLength()); - } - - return null; - } - - private static Point getMinimumLocation(StyledText text, int offset, - int length) { - Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x < minLocation.x) - minLocation.x = location.x; - if (location.y < minLocation.y) - minLocation.y = location.y; - } - - return minLocation; - } - - private static Point getMaximumLocation(StyledText text, int offset, - int length) { - Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x > maxLocation.x) - maxLocation.x = location.x; - if (location.y > maxLocation.y) - maxLocation.y = location.y; - } - - return maxLocation; - } - - private void redrawRegion() { - IRegion widgetRange = asWidgetRange(fFramePosition); - if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; - } - - StyledText text = fViewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), - true); - } - - private void selectRegion() { - - IRegion widgetRange = asWidgetRange(fFramePosition); - if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; - } - - StyledText text = fViewer.getTextWidget(); - if (text != null && !text.isDisposed()) { - int start = widgetRange.getOffset(); - int end = widgetRange.getLength() + start; - text.setSelection(start, end); - } - } - - private void updateCaret() { - - IRegion widgetRange = asWidgetRange(fFramePosition); - if (widgetRange == null) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - return; - } - - int offset = widgetRange.getOffset() + fCaretOffset; - StyledText text = fViewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.setCaretOffset(offset); - } - - /* - * @see ModifyListener#modifyText(ModifyEvent) - */ - public void modifyText(ModifyEvent e) { - // reposition caret after StyledText - redrawRegion(); - updateCaret(); - } - - private static void handleException(Shell shell, Exception e) { - String title = LinkedPositionMessages - .getString("LinkedPositionUI.error.title"); //$NON-NLS-1$ - if (e instanceof CoreException) - ExceptionHandler.handle((CoreException) e, shell, title, null); - else if (e instanceof InvocationTargetException) - ExceptionHandler.handle((InvocationTargetException) e, shell, - title, null); - else { - MessageDialog.openError(shell, title, e.getMessage()); - WebUI.log(e); - } - } - - /* - * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, - * IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, - IDocument newInput) { - // 5326: leave linked mode on document change - int flags = UNINSTALL | COMMIT - | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); - leave(flags); - } - - /* - * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) - */ - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - } - - private static boolean includes(IRegion region, Position position) { - return position.getOffset() >= region.getOffset() - && position.getOffset() + position.getLength() <= region - .getOffset() - + region.getLength(); - } - - /* - * @see org.eclipse.jface.text.ITextListener#textChanged(TextEvent) - */ - public void textChanged(TextEvent event) { - if (!fNeedRedraw) - return; - - redrawRegion(); - fNeedRedraw = false; - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) - */ - public void shellActivated(ShellEvent event) { - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellClosed(org.eclipse.swt.events.ShellEvent) - */ - public void shellClosed(ShellEvent event) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) - */ - public void shellDeactivated(ShellEvent event) { - // don't deactivate on focus lost, since the proposal popups may take - // focus - // plus: it doesn't hurt if you can check with another window without - // losing linked mode - // since there is no intrusive popup sticking out. - - // need to check first what happens on reentering based on an open - // action - // Seems to be no problem - - // TODO check whether we can leave it or uncomment it after debugging - // PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell - // deactivated does not mean - // it is not visible any longer. - // leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - - // Better: - // Check with content assistant and only leave if its not the proposal - // shell that took the - // focus away. - - StyledText text; - Display display; - - // if (fAssistant == null || fViewer == null || (text= - // fViewer.getTextWidget()) == null - // || (display= text.getDisplay()) == null || display.isDisposed()) { - if (fViewer == null || (text = fViewer.getTextWidget()) == null - || (display = text.getDisplay()) == null - || display.isDisposed()) { - leave(UNINSTALL | COMMIT); - } else { - // Post in UI thread since the assistant popup will only get the - // focus after we lose it. - display.asyncExec(new Runnable() { - public void run() { - // TODO add isDisposed / isUninstalled / hasLeft check? for - // now: check for content type, - // since it gets nullified in leave() - if (fIsActive) {// && (fAssistant == null || - // !fAssistant.hasFocus())) { - leave(UNINSTALL | COMMIT); - } - } - }); - } - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellDeiconified(org.eclipse.swt.events.ShellEvent) - */ - public void shellDeiconified(ShellEvent event) { - } - - /* - * @see org.eclipse.swt.events.ShellListener#shellIconified(org.eclipse.swt.events.ShellEvent) - */ - public void shellIconified(ShellEvent event) { - leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java deleted file mode 100644 index 84c8219..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java +++ /dev/null @@ -1,938 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.phpdoc; - -import java.text.BreakIterator; - -//import net.sourceforge.phpdt.core.ICompilationUnit; -//import net.sourceforge.phpdt.core.IJavaElement; -//import net.sourceforge.phpdt.core.IMethod; -//import net.sourceforge.phpdt.core.ISourceRange; -//import net.sourceforge.phpdt.core.IType; -//import net.sourceforge.phpdt.internal.corext.util.Strings; -//import net.sourceforge.phpdt.ui.CodeGeneration; -//import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -//import org.eclipse.core.runtime.CoreException; -//import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -//import org.eclipse.ui.IWorkbenchWindow; -//import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.ui.texteditor.ITextEditorExtension3; - -/** - * Auto indent strategy for java doc comments - */ -public class JavaDocAutoIndentStrategy extends - DefaultIndentLineAutoEditStrategy { - - private String fPartitioning; - - /** - * Creates a new Javadoc auto indent strategy for the given document - * partitioning. - * - * @param partitioning - * the document partitioning - */ - public JavaDocAutoIndentStrategy(String partitioning) { - fPartitioning = partitioning; - } - - private static String getLineDelimiter(IDocument document) { - try { - if (document.getNumberOfLines() > 1) - return document.getLineDelimiter(0); - } catch (BadLocationException e) { - WebUI.log(e); - } - - return System.getProperty("line.separator"); //$NON-NLS-1$ - } - - /** - * Copies the indentation of the previous line and add a star. If the - * javadoc just started on this line add standard method tags and close the - * javadoc. - * - * @param d - * the document to work on - * @param c - * the command to deal with - */ - private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) { - - if (c.offset == -1 || d.getLength() == 0) - return; - - try { - // find start of line - int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset); - IRegion info = d.getLineInformationOfOffset(p); - int start = info.getOffset(); - - // find white spaces - int end = findEndOfWhiteSpace(d, start, c.offset); - - StringBuffer buf = new StringBuffer(c.text); - if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness - // not work for class comments - // append to input - String indentation = jdocExtractLinePrefix(d, d - .getLineOfOffset(c.offset)); - buf.append(indentation); - if (end < c.offset) { - if (d.getChar(end) == '/') { - // javadoc started on this line - buf.append(" * "); //$NON-NLS-1$ - - if (WebUI - .getDefault() - .getPreferenceStore() - .getBoolean( - PreferenceConstants.EDITOR_CLOSE_JAVADOCS) - && isNewComment(d, c.offset, fPartitioning)) { - String lineDelimiter = getLineDelimiter(d); - - String endTag = lineDelimiter + indentation + " */"; //$NON-NLS-1$ - d.replace(c.offset, 0, endTag); //$NON-NLS-1$ - // evaluate method signature - //ICompilationUnit unit = getCompilationUnit(); - - // if - // (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) - // && - // unit != null) - // { - // try { - // JavaModelUtil.reconcile(unit); - // String string= createJavaDocTags(d, c, - // indentation, lineDelimiter, unit); - // if (string != null) { - // d.replace(c.offset, 0, string); - // } - // } catch (CoreException e) { - // // ignore - // } - // } - } - - } - } - } - - c.text = buf.toString(); - - } catch (BadLocationException excp) { - // stop work - } - } - -// private String createJavaDocTags(IDocument document, -// DocumentCommand command, String indentation, String lineDelimiter, -// ICompilationUnit unit) throws CoreException, BadLocationException { -// IJavaElement element = unit.getElementAt(command.offset); -// if (element == null) -// return null; -// -// switch (element.getElementType()) { -// case IJavaElement.TYPE: -// return createTypeTags(document, command, indentation, -// lineDelimiter, (IType) element); -// -// case IJavaElement.METHOD: -// return createMethodTags(document, command, indentation, -// lineDelimiter, (IMethod) element); -// -// default: -// return null; -// } -// } - - /* - * Removes start and end of a comment and corrects indentation and line - * delimiters. - */ -// private String prepareTemplateComment(String comment, String indentation, -// String lineDelimiter) { -// // trim comment start and end if any -// if (comment.endsWith("*/")) //$NON-NLS-1$ -// comment = comment.substring(0, comment.length() - 2); -// comment = comment.trim(); -// if (comment.startsWith("/*")) { //$NON-NLS-1$ -// if (comment.length() > 2 && comment.charAt(2) == '*') { -// comment = comment.substring(3); // remove '/**' -// } else { -// comment = comment.substring(2); // remove '/*' -// } -// } -// // return Strings.changeIndent(comment, 0, -// // CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter); -// return Strings.changeIndent(comment, 0, getTabWidth(), indentation, -// lineDelimiter); -// } - -// public static int getTabWidth() { -// Preferences preferences = WebUI.getDefault() -// .getPluginPreferences(); -// return preferences -// .getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); -// } - -// private String createTypeTags(IDocument document, DocumentCommand command, -// String indentation, String lineDelimiter, IType type) -// throws CoreException { -// String comment = CodeGeneration.getTypeComment(type -// .getCompilationUnit(), type.getTypeQualifiedName('.'), -// lineDelimiter); -// if (comment != null) { -// return prepareTemplateComment(comment.trim(), indentation, -// lineDelimiter); -// } -// return null; -// } - -// private String createMethodTags(IDocument document, -// DocumentCommand command, String indentation, String lineDelimiter, -// IMethod method) throws CoreException, BadLocationException { -// IRegion partition = TextUtilities.getPartition(document, fPartitioning, -// command.offset, false); -// ISourceRange sourceRange = method.getSourceRange(); -// if (sourceRange == null -// || sourceRange.getOffset() != partition.getOffset()) -// return null; -// -// // IMethod inheritedMethod= getInheritedMethod(method); -// // String comment= CodeGeneration.getMethodComment(method, -// // inheritedMethod, lineDelimiter); -// // if (comment != null) { -// // comment= comment.trim(); -// // boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$ -// // boolean isJavaDoc= partition.getLength() >= 3 && -// // document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ -// // if (javadocComment == isJavaDoc) { -// // return prepareTemplateComment(comment, indentation, lineDelimiter); -// // } -// // } -// return null; -// } - - /** - * Returns the method inherited from, null if method is newly - * defined. - */ - // private static IMethod getInheritedMethod(IMethod method) throws - // JavaModelException { - // IType declaringType= method.getDeclaringType(); - // ITypeHierarchy typeHierarchy= - // SuperTypeHierarchyCache.getTypeHierarchy(declaringType); - // return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, - // declaringType, - // method.getElementName(), method.getParameterTypes(), - // method.isConstructor()); - // } - protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) { - if (c.offset < 2 || d.getLength() == 0) { - return; - } - try { - if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$ - // modify document command - c.length++; - c.offset--; - } - } catch (BadLocationException excp) { - // stop work - } - } - - /** - * Guesses if the command operates within a newly created javadoc comment or - * not. If in doubt, it will assume that the javadoc is new. - */ - private static boolean isNewComment(IDocument document, int commandOffset, - String partitioning) { - - try { - int lineIndex = document.getLineOfOffset(commandOffset) + 1; - if (lineIndex >= document.getNumberOfLines()) - return true; - - IRegion line = document.getLineInformation(lineIndex); - ITypedRegion partition = TextUtilities.getPartition(document, - partitioning, commandOffset, false); - int partitionEnd = partition.getOffset() + partition.getLength(); - if (line.getOffset() >= partitionEnd) - return false; - - if (document.getLength() == partitionEnd) - return true; // partition goes to end of document - probably - // a new comment - - String comment = document.get(partition.getOffset(), partition - .getLength()); - if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$ - return true; // enclosed another comment -> probably a new - // comment - - return false; - - } catch (BadLocationException e) { - return false; - } - } - - private boolean isSmartMode() { - IWorkbenchPage page = WebUI.getActivePage(); - if (page != null) { - IEditorPart part = page.getActiveEditor(); - if (part instanceof ITextEditorExtension3) { - ITextEditorExtension3 extension = (ITextEditorExtension3) part; - return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; - } - } - return false; - } - - /* - * @see IAutoIndentStrategy#customizeDocumentCommand - */ - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - - if (!isSmartMode()) - return; - - try { - - if (command.text != null && command.length == 0) { - String[] lineDelimiters = document.getLegalLineDelimiters(); - int index = TextUtilities - .endsWith(lineDelimiters, command.text); - if (index > -1) { - // ends with line delimiter - if (lineDelimiters[index].equals(command.text)) - // just the line delimiter - jdocIndentAfterNewLine(document, command); - return; - } - } - - if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$ - jdocIndentForCommentEnd(document, command); - return; - } - - ITypedRegion partition = TextUtilities.getPartition(document, - fPartitioning, command.offset, true); - int partitionStart = partition.getOffset(); - int partitionEnd = partition.getLength() + partitionStart; - - String text = command.text; - int offset = command.offset; - int length = command.length; - - // partition change - final int PREFIX_LENGTH = "/*".length(); //$NON-NLS-1$ - final int POSTFIX_LENGTH = "*/".length(); //$NON-NLS-1$ - if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - - POSTFIX_LENGTH) - || text != null - && text.length() >= 2 - && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ - return; - - if (command.text == null || command.text.length() == 0) - jdocHandleBackspaceDelete(document, command); - - else if (command.text != null && command.length == 0 - && command.text.length() > 0) - jdocWrapParagraphOnInsert(document, command); - - } catch (BadLocationException e) { - WebUI.log(e); - } - } - - private void flushCommand(IDocument document, DocumentCommand command) - throws BadLocationException { - - if (!command.doit) - return; - - document.replace(command.offset, command.length, command.text); - - command.doit = false; - if (command.text != null) - command.offset += command.text.length(); - command.length = 0; - command.text = null; - } - - protected void jdocWrapParagraphOnInsert(IDocument document, - DocumentCommand command) throws BadLocationException { - - // Assert.isTrue(command.length == 0); - // Assert.isTrue(command.text != null && command.text.length() == 1); - - if (!getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) - return; - - int line = document.getLineOfOffset(command.offset); - IRegion region = document.getLineInformation(line); - int lineOffset = region.getOffset(); - int lineLength = region.getLength(); - - String lineContents = document.get(lineOffset, lineLength); - StringBuffer buffer = new StringBuffer(lineContents); - int start = command.offset - lineOffset; - int end = command.length + start; - buffer.replace(start, end, command.text); - - // handle whitespace - if (command.text != null && command.text.length() != 0 - && command.text.trim().length() == 0) { - - String endOfLine = document.get(command.offset, lineOffset - + lineLength - command.offset); - - // end of line - if (endOfLine.length() == 0) { - // move caret to next line - flushCommand(document, command); - - if (isLineTooShort(document, line)) { - int[] caretOffset = { command.offset }; - jdocWrapParagraphFromLine(document, line, caretOffset, - false); - command.offset = caretOffset[0]; - return; - } - - // move caret to next line if possible - if (line < document.getNumberOfLines() - 1 - && isJavaDocLine(document, line + 1)) { - String lineDelimiter = document.getLineDelimiter(line); - String nextLinePrefix = jdocExtractLinePrefix(document, - line + 1); - command.offset += lineDelimiter.length() - + nextLinePrefix.length(); - } - return; - - // inside whitespace at end of line - } else if (endOfLine.trim().length() == 0) { - // simply insert space - return; - } - } - - // change in prefix region - String prefix = jdocExtractLinePrefix(document, line); - boolean wrapAlways = command.offset >= lineOffset - && command.offset <= lineOffset + prefix.length(); - - // must insert the text now because it may include whitepace - flushCommand(document, command); - - if (wrapAlways - || calculateDisplayedWidth(buffer.toString()) > getMargin() - || isLineTooShort(document, line)) { - int[] caretOffset = { command.offset }; - jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways); - - if (!wrapAlways) - command.offset = caretOffset[0]; - } - } - - /** - * Method jdocWrapParagraphFromLine. - * - * @param document - * @param line - * @param always - */ - private void jdocWrapParagraphFromLine(IDocument document, int line, - int[] caretOffset, boolean always) throws BadLocationException { - - String indent = jdocExtractLinePrefix(document, line); - if (!always) { - if (!indent.trim().startsWith("*")) //$NON-NLS-1$ - return; - - if (indent.trim().startsWith("*/")) //$NON-NLS-1$ - return; - - if (!isLineTooLong(document, line) - && !isLineTooShort(document, line)) - return; - } - - boolean caretRelativeToParagraphOffset = false; - int caret = caretOffset[0]; - - int caretLine = document.getLineOfOffset(caret); - int lineOffset = document.getLineOffset(line); - int paragraphOffset = lineOffset + indent.length(); - if (paragraphOffset < caret) { - caret -= paragraphOffset; - caretRelativeToParagraphOffset = true; - } else { - caret -= lineOffset; - } - - StringBuffer buffer = new StringBuffer(); - int currentLine = line; - while (line == currentLine || isJavaDocLine(document, currentLine)) { - - if (buffer.length() != 0 - && !Character.isWhitespace(buffer - .charAt(buffer.length() - 1))) { - buffer.append(' '); - if (currentLine <= caretLine) { - // in this case caretRelativeToParagraphOffset is always - // true - ++caret; - } - } - - String string = getLineContents(document, currentLine); - buffer.append(string); - currentLine++; - } - String paragraph = buffer.toString(); - - if (paragraph.trim().length() == 0) - return; - - caretOffset[0] = caretRelativeToParagraphOffset ? caret : 0; - String delimiter = document.getLineDelimiter(0); - String wrapped = formatParagraph(paragraph, caretOffset, indent, - delimiter, getMargin()); - - int beginning = document.getLineOffset(line); - int end = document.getLineOffset(currentLine); - document.replace(beginning, end - beginning, wrapped.toString()); - - caretOffset[0] = caretRelativeToParagraphOffset ? caretOffset[0] - + beginning : caret + beginning; - } - - /** - * Line break iterator to handle whitespaces as first class citizens. - */ - private static class LineBreakIterator { - - private final String fString; - - private final BreakIterator fIterator = BreakIterator.getLineInstance(); - - private int fStart; - - private int fEnd; - - private int fBufferedEnd; - - public LineBreakIterator(String string) { - fString = string; - fIterator.setText(string); - } - - public int first() { - fBufferedEnd = -1; - fStart = fIterator.first(); - return fStart; - } - - public int next() { - - if (fBufferedEnd != -1) { - fStart = fEnd; - fEnd = fBufferedEnd; - fBufferedEnd = -1; - return fEnd; - } - - fStart = fEnd; - fEnd = fIterator.next(); - - if (fEnd == BreakIterator.DONE) - return fEnd; - - final String string = fString.substring(fStart, fEnd); - - // whitespace - if (string.trim().length() == 0) - return fEnd; - - final String word = string.trim(); - if (word.length() == string.length()) - return fEnd; - - // suspected whitespace - fBufferedEnd = fEnd; - return fStart + word.length(); - } - } - - /** - * Formats a paragraph, using break iterator. - * - * @param offset - * an offset within the paragraph, which will be updated with - * respect to formatting. - */ - private static String formatParagraph(String paragraph, int[] offset, - String prefix, String lineDelimiter, int margin) { - - LineBreakIterator iterator = new LineBreakIterator(paragraph); - - StringBuffer paragraphBuffer = new StringBuffer(); - StringBuffer lineBuffer = new StringBuffer(); - StringBuffer whiteSpaceBuffer = new StringBuffer(); - - int index = offset[0]; - int indexBuffer = -1; - - // line delimiter could be null - if (lineDelimiter == null) - lineDelimiter = ""; //$NON-NLS-1$ - - for (int start = iterator.first(), end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator - .next()) { - - String word = paragraph.substring(start, end); - - // word is whitespace - if (word.trim().length() == 0) { - whiteSpaceBuffer.append(word); - - // first word of line is always appended - } else if (lineBuffer.length() == 0) { - lineBuffer.append(prefix); - lineBuffer.append(whiteSpaceBuffer.toString()); - lineBuffer.append(word); - - } else { - String line = lineBuffer.toString() - + whiteSpaceBuffer.toString() + word.toString(); - - // margin exceeded - if (calculateDisplayedWidth(line) > margin) { - // flush line buffer and wrap paragraph - paragraphBuffer.append(lineBuffer.toString()); - paragraphBuffer.append(lineDelimiter); - lineBuffer.setLength(0); - lineBuffer.append(prefix); - lineBuffer.append(word); - - // flush index buffer - if (indexBuffer != -1) { - offset[0] = indexBuffer; - // correct for caret in whitespace at the end of line - if (whiteSpaceBuffer.length() != 0 && index < start - && index >= start - whiteSpaceBuffer.length()) - offset[0] -= (index - (start - whiteSpaceBuffer - .length())); - indexBuffer = -1; - } - - whiteSpaceBuffer.setLength(0); - - // margin not exceeded - } else { - lineBuffer.append(whiteSpaceBuffer.toString()); - lineBuffer.append(word); - whiteSpaceBuffer.setLength(0); - } - } - - if (index >= start && index < end) { - indexBuffer = paragraphBuffer.length() + lineBuffer.length() - + (index - start); - if (word.trim().length() != 0) - indexBuffer -= word.length(); - } - } - - // flush line buffer - paragraphBuffer.append(lineBuffer.toString()); - paragraphBuffer.append(lineDelimiter); - - // flush index buffer - if (indexBuffer != -1) - offset[0] = indexBuffer; - - // last position is not returned by break iterator - else if (offset[0] == paragraph.length()) - offset[0] = paragraphBuffer.length() - lineDelimiter.length(); - - return paragraphBuffer.toString(); - } - - private static IPreferenceStore getPreferenceStore() { - return WebUI.getDefault().getPreferenceStore(); - } - - /** - * Returns the displayed width of a string, taking in account the displayed - * tab width. The result can be compared against the print margin. - */ - private static int calculateDisplayedWidth(String string) { - - int tabWidth = getPreferenceStore() - .getInt( - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - if (tabWidth <= 0) { - tabWidth = 2; - } - int column = 0; - for (int i = 0; i < string.length(); i++) - if ('\t' == string.charAt(i)) - column += tabWidth - (column % tabWidth); - else - column++; - - return column; - } - - private String jdocExtractLinePrefix(IDocument d, int line) - throws BadLocationException { - - IRegion region = d.getLineInformation(line); - int lineOffset = region.getOffset(); - int index = findEndOfWhiteSpace(d, lineOffset, lineOffset - + d.getLineLength(line)); - if (d.getChar(index) == '*') { - index++; - if (index != lineOffset + region.getLength() - && d.getChar(index) == ' ') - index++; - } - return d.get(lineOffset, index - lineOffset); - } - - private String getLineContents(IDocument d, int line) - throws BadLocationException { - int offset = d.getLineOffset(line); - int length = d.getLineLength(line); - String lineDelimiter = d.getLineDelimiter(line); - if (lineDelimiter != null) - length = length - lineDelimiter.length(); - String lineContents = d.get(offset, length); - int trim = jdocExtractLinePrefix(d, line).length(); - return lineContents.substring(trim); - } - - private static String getLine(IDocument document, int line) - throws BadLocationException { - IRegion region = document.getLineInformation(line); - return document.get(region.getOffset(), region.getLength()); - } - - /** - * Returns true if the javadoc line is too short, - * false otherwise. - */ - private boolean isLineTooShort(IDocument document, int line) - throws BadLocationException { - - if (!isJavaDocLine(document, line + 1)) - return false; - - String nextLine = getLineContents(document, line + 1); - if (nextLine.trim().length() == 0) - return false; - - return true; - } - - /** - * Returns true if the line is too long, false - * otherwise. - */ - private boolean isLineTooLong(IDocument document, int line) - throws BadLocationException { - String lineContents = getLine(document, line); - return calculateDisplayedWidth(lineContents) > getMargin(); - } - - private static int getMargin() { - return getPreferenceStore() - .getInt( - AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); - } - - private static final String[] fgInlineTags = { - "", "", "", "", "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - }; - - private boolean isInlineTag(String string) { - for (int i = 0; i < fgInlineTags.length; i++) - if (string.startsWith(fgInlineTags[i])) - return true; - return false; - } - - /** - * returns true if the specified line is part of a paragraph and should be - * merged with the previous line. - */ - private boolean isJavaDocLine(IDocument document, int line) - throws BadLocationException { - - if (document.getNumberOfLines() < line) - return false; - - int offset = document.getLineOffset(line); - int length = document.getLineLength(line); - int firstChar = findEndOfWhiteSpace(document, offset, offset + length); - length -= firstChar - offset; - String lineContents = document.get(firstChar, length); - - String prefix = lineContents.trim(); - if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$ - return false; - - lineContents = lineContents.substring(1).trim().toLowerCase(); - - // preserve empty lines - if (lineContents.length() == 0) - return false; - - // preserve @TAGS - if (lineContents.startsWith("@")) //$NON-NLS-1$ - return false; - - // preserve HTML tags which are not inline - if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$ - return false; - - return true; - } - - protected void jdocHandleBackspaceDelete(IDocument document, - DocumentCommand c) { - - if (!getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) - return; - - try { - String text = document.get(c.offset, c.length); - int line = document.getLineOfOffset(c.offset); - int lineOffset = document.getLineOffset(line); - - // erase line delimiter - String lineDelimiter = document.getLineDelimiter(line); - if (lineDelimiter != null && lineDelimiter.equals(text)) { - - String prefix = jdocExtractLinePrefix(document, line + 1); - - // strip prefix if any - if (prefix.length() > 0) { - int length = document.getLineDelimiter(line).length() - + prefix.length(); - document.replace(c.offset, length, null); - - c.doit = false; - c.length = 0; - return; - } - - // backspace: beginning of a javadoc line - } else if (document.getChar(c.offset - 1) == '*' - && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - - lineOffset) { - - lineDelimiter = document.getLineDelimiter(line - 1); - String prefix = jdocExtractLinePrefix(document, line); - int length = (lineDelimiter != null ? lineDelimiter.length() - : 0) - + prefix.length(); - document.replace(c.offset - length + 1, length, null); - - c.doit = false; - c.offset -= length - 1; - c.length = 0; - return; - - } else { - document.replace(c.offset, c.length, null); - c.doit = false; - c.length = 0; - } - - } catch (BadLocationException e) { - WebUI.log(e); - } - - try { - int line = document.getLineOfOffset(c.offset); - int lineOffset = document.getLineOffset(line); - String prefix = jdocExtractLinePrefix(document, line); - boolean always = c.offset > lineOffset - && c.offset <= lineOffset + prefix.length(); - int[] caretOffset = { c.offset }; - jdocWrapParagraphFromLine(document, document - .getLineOfOffset(c.offset), caretOffset, always); - c.offset = caretOffset[0]; - - } catch (BadLocationException e) { - WebUI.log(e); - } - } - - /** - * Returns the compilation unit of the CompilationUnitEditor invoking the - * AutoIndentStrategy, might return null on error. - */ -// private static ICompilationUnit getCompilationUnit() { -// -// IWorkbenchWindow window = PlatformUI.getWorkbench() -// .getActiveWorkbenchWindow(); -// if (window == null) -// return null; -// -// IWorkbenchPage page = window.getActivePage(); -// if (page == null) -// return null; -// -// IEditorPart editor = page.getActiveEditor(); -// if (editor == null) -// return null; -// -// IWorkingCopyManager manager = WebUI.getDefault() -// .getWorkingCopyManager(); -// ICompilationUnit unit = manager.getWorkingCopy(editor.getEditorInput()); -// if (unit == null) -// return null; -// -// return unit; -// } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java deleted file mode 100644 index 2f5fa5a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java +++ /dev/null @@ -1,209 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.text.phpdoc; - -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ - -import java.util.Arrays; -//import java.util.Comparator; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; -import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -//import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.ui.IEditorPart; - -/** - * Simple PHPDoc completion processor. - */ -public class PHPDocCompletionProcessor implements IContentAssistProcessor { - -// private static class PHPDocCompletionProposalComparator implements -// Comparator { -// public int compare(Object o1, Object o2) { -// ICompletionProposal c1 = (ICompletionProposal) o1; -// ICompletionProposal c2 = (ICompletionProposal) o2; -// return c1.getDisplayString().compareTo(c2.getDisplayString()); -// } -// }; - - // private IEditorPart fEditor; - // private IWorkingCopyManager fManager; - private char[] fProposalAutoActivationSet; - - private PHPCompletionProposalComparator fComparator; - - private TemplateEngine fTemplateEngine; - - //private boolean fRestrictToMatchingCase; - - private IEditorPart fEditor; - - protected IWorkingCopyManager fManager; - - public PHPDocCompletionProcessor(IEditorPart editor) { - fEditor = editor; - fManager = WebUI.getDefault().getWorkingCopyManager(); - - // fEditor= editor; - // fManager= JavaPlugin.getDefault().getWorkingCopyManager(); - TemplateContextType contextType = WebUI.getDefault() - .getTemplateContextRegistry().getContextType("phpdoc"); //$NON-NLS-1$ - if (contextType != null) - fTemplateEngine = new TemplateEngine(contextType); - //fRestrictToMatchingCase = false; - - fComparator = new PHPCompletionProposalComparator(); - } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order - * true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * Tells this processor to restrict is proposals to those starting with - * matching cases. - * - * @param restrict - * true if proposals should be restricted - */ - public void restrictProposalsToMatchingCases(boolean restrict) { - //fRestrictToMatchingCase = restrict; - } - - /** - * @see IContentAssistProcessor#getErrorMessage() - */ - public String getErrorMessage() { - return null; - } - - /** - * @see IContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - return null; - } - - /** - * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet - * the activation set - */ - public void setCompletionProposalAutoActivationCharacters( - char[] activationSet) { - fProposalAutoActivationSet = activationSet; - } - - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, - int offset) { - return null; - } - - /** - * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, - int documentOffset) { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor - .getEditorInput()); - //IDocument document = viewer.getDocument(); - - IPHPCompletionProposal[] results = new IPHPCompletionProposal[0]; - - // try { - // if (unit != null) { - // - // int offset= documentOffset; - // int length= 0; - // - // Point selection= viewer.getSelectedRange(); - // if (selection.y > 0) { - // offset= selection.x; - // length= selection.y; - // } - // - // JavaDocCompletionEvaluator evaluator= new - // JavaDocCompletionEvaluator(unit, document, offset, length); - // evaluator.restrictProposalsToMatchingCases(fRestrictToMatchingCase); - // results= evaluator.computeProposals(); - // } - // } catch (JavaModelException e) { - // JavaPlugin.log(e); - // } - - if (fTemplateEngine != null) { - // try { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, documentOffset, unit); - // } catch (JavaModelException x) { - // } - - IPHPCompletionProposal[] templateResults = fTemplateEngine - .getResults(); - if (results.length == 0) { - results = templateResults; - } else { - // concatenate arrays - IPHPCompletionProposal[] total = new IPHPCompletionProposal[results.length - + templateResults.length]; - System.arraycopy(templateResults, 0, total, 0, - templateResults.length); - System.arraycopy(results, 0, total, templateResults.length, - results.length); - results = total; - } - } - - /* - * Order here and not in result collector to make sure that the order - * applies to all proposals and not just those of the compilation unit. - */ - return order(results); - } - - /** - * Order the given proposals. - */ - private IPHPCompletionProposal[] order(IPHPCompletionProposal[] proposals) { - Arrays.sort(proposals, fComparator); - return proposals; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java deleted file mode 100644 index 0b1f05f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java +++ /dev/null @@ -1,357 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpdt.internal.ui.text.spelling; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.DefaultSpellChecker; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckEngine; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellChecker; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellDictionary; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.PersistentSpellDictionary; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; - -/** - * Spell check engine for Java source spell checking. - * - * @since 3.0 - */ -public class SpellCheckEngine implements ISpellCheckEngine, - IPropertyChangeListener { - - /** The dictionary location */ - public static final String DICTIONARY_LOCATION = "dictionaries/"; //$NON-NLS-1$ - - /** The singleton spell checker instance */ - private static ISpellChecker fChecker = null; - - /** The singleton engine instance */ - private static ISpellCheckEngine fEngine = null; - - /** - * Returns the available locales for this spell check engine. - * - * @return The available locales for this engine - */ - public static Set getAvailableLocales() { - - URL url = null; - Locale locale = null; - InputStream stream = null; - - final Set result = new HashSet(); - try { - - final URL location = getDictionaryLocation(); - final Locale[] locales = Locale.getAvailableLocales(); - - for (int index = 0; index < locales.length; index++) { - - locale = locales[index]; - url = new URL( - location, - locale.toString().toLowerCase() - + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ - - try { - stream = url.openStream(); - if (stream != null) { - try { - result.add(locale); - } finally { - stream.close(); - } - } - } catch (IOException exception) { - // Do nothing - } - } - } catch (MalformedURLException exception) { - // Do nothing - } - result.add(getDefaultLocale()); - - return result; - } - - /** - * Returns the default locale for this engine. - * - * @return The default locale - */ - public static Locale getDefaultLocale() { - return Locale.US; - } - - /** - * Returns the dictionary location. - * - * @throws MalformedURLException - * if the URL could not be created - * @return The dictionary location, or null iff the location - * is not known - */ - public static URL getDictionaryLocation() throws MalformedURLException { - - final WebUI plugin = WebUI.getDefault(); - if (plugin != null) - return plugin.getBundle().getEntry("/" + DICTIONARY_LOCATION); //$NON-NLS-1$ - - return null; - } - - /** - * Returns the singleton instance of the spell check engine. - * - * @return The singleton instance of the spell check engine - */ - public static final synchronized ISpellCheckEngine getInstance() { - - if (fEngine == null) - fEngine = new SpellCheckEngine(); - - return fEngine; - } - - /** The registered locale insenitive dictionaries */ - private final Set fGlobalDictionaries = new HashSet(); - - /** The current locale */ - private Locale fLocale = null; - - /** The registered locale sensitive dictionaries */ - private final Map fLocaleDictionaries = new HashMap(); - - /** The preference store where to listen */ - private IPreferenceStore fPreferences = null; - - /** The user dictionary */ - private ISpellDictionary fUserDictionary = null; - - /** - * Creates a new spell check manager. - */ - private SpellCheckEngine() { - - fGlobalDictionaries.add(new TaskTagDictionary()); - fGlobalDictionaries.add(new HtmlTagDictionary()); - fGlobalDictionaries.add(new JavaDocTagDictionary()); - - try { - - Locale locale = null; - final URL location = getDictionaryLocation(); - - for (final Iterator iterator = getAvailableLocales().iterator(); iterator - .hasNext();) { - - locale = (Locale) iterator.next(); - fLocaleDictionaries.put(locale, new SpellReconcileDictionary( - locale, location)); - } - - } catch (MalformedURLException exception) { - // Do nothing - } - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#createSpellChecker(java.util.Locale,org.eclipse.jface.preference.IPreferenceStore) - */ - public final synchronized ISpellChecker createSpellChecker( - final Locale locale, final IPreferenceStore store) { - - if (fLocale != null && fLocale.equals(locale)) - return fChecker; - - if (fChecker == null) { - - fChecker = new DefaultSpellChecker(store); - store.addPropertyChangeListener(this); - - fPreferences = store; - - ISpellDictionary dictionary = null; - for (Iterator iterator = fGlobalDictionaries.iterator(); iterator - .hasNext();) { - - dictionary = (ISpellDictionary) iterator.next(); - fChecker.addDictionary(dictionary); - } - } - - ISpellDictionary dictionary = null; - if (fLocale != null) { - - dictionary = (ISpellDictionary) fLocaleDictionaries.get(fLocale); - if (dictionary != null) { - - fChecker.removeDictionary(dictionary); - dictionary.unload(); - } - } - fLocale = locale; - - dictionary = (ISpellDictionary) fLocaleDictionaries.get(locale); - if (dictionary == null) { - - if (!getDefaultLocale().equals(locale)) { - - if (fPreferences != null) - fPreferences.removePropertyChangeListener(this); - - fChecker = null; - fLocale = null; - } - - } else - fChecker.addDictionary(dictionary); - - if (fPreferences != null) - propertyChange(new PropertyChangeEvent( - this, - ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY, - null, - fPreferences - .getString(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY))); - - return fChecker; - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#getLocale() - */ - public final Locale getLocale() { - return fLocale; - } - - /* - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public final void propertyChange(final PropertyChangeEvent event) { - - if (fChecker != null - && event.getProperty().equals( - ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { - - if (fUserDictionary != null) { - - fChecker.removeDictionary(fUserDictionary); - fUserDictionary = null; - } - - final String file = (String) event.getNewValue(); - if (file.length() > 0) { - - try { - - final URL url = new URL("file", null, file); //$NON-NLS-1$ - InputStream stream = url.openStream(); - if (stream != null) { - try { - fUserDictionary = new PersistentSpellDictionary(url); - fChecker.addDictionary(fUserDictionary); - } finally { - stream.close(); - } - } - } catch (MalformedURLException exception) { - // Do nothing - } catch (IOException exception) { - // Do nothing - } - } - } - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) - */ - public synchronized final void registerDictionary( - final ISpellDictionary dictionary) { - - fGlobalDictionaries.add(dictionary); - - if (fChecker != null) - fChecker.addDictionary(dictionary); - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(java.util.Locale,net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) - */ - public synchronized final void registerDictionary(final Locale locale, - final ISpellDictionary dictionary) { - - fLocaleDictionaries.put(locale, dictionary); - - if (fChecker != null && fLocale != null && fLocale.equals(locale)) - fChecker.addDictionary(dictionary); - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#unload() - */ - public synchronized final void unload() { - - ISpellDictionary dictionary = null; - for (final Iterator iterator = fGlobalDictionaries.iterator(); iterator - .hasNext();) { - - dictionary = (ISpellDictionary) iterator.next(); - dictionary.unload(); - } - - for (final Iterator iterator = fLocaleDictionaries.values().iterator(); iterator - .hasNext();) { - - dictionary = (ISpellDictionary) iterator.next(); - dictionary.unload(); - } - - if (fPreferences != null) - fPreferences.removePropertyChangeListener(this); - - fUserDictionary = null; - fChecker = null; - } - - /* - * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#unregisterDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) - */ - public synchronized final void unregisterDictionary( - final ISpellDictionary dictionary) { - - fGlobalDictionaries.remove(dictionary); - fLocaleDictionaries.values().remove(dictionary); - - if (fChecker != null) - fChecker.removeDictionary(dictionary); - - dictionary.unload(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java deleted file mode 100644 index edf6209..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -//import java.util.WeakHashMap; - -import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Shell; - - -/** - * A PHP identifier proposal. - */ -public abstract class AbstractProposal implements IPHPCompletionProposal { - protected IRegion fSelectedRegion; // initialized by apply() - - protected final ITextViewer fViewer; - - protected ContextInformation fContextInfo; - - public AbstractProposal(ITextViewer viewer) { - fContextInfo = null; - fViewer = viewer; - } - - protected static String textToHTML(String string) { - StringBuffer buffer = new StringBuffer(string.length()); - buffer.append("
"); //$NON-NLS-1$
-
-		for (int i = 0; i != string.length(); i++) {
-			char ch = string.charAt(i);
-
-			switch (ch) {
-			case '&':
-				buffer.append("&"); //$NON-NLS-1$
-				break;
-
-			case '<':
-				buffer.append("<"); //$NON-NLS-1$
-				break;
-
-			case '>':
-				buffer.append(">"); //$NON-NLS-1$
-				break;
-
-			case '\t':
-				buffer.append("    "); //$NON-NLS-1$
-				break;
-
-			case '\n':
-				buffer.append("
"); //$NON-NLS-1$ - break; - - default: - buffer.append(ch); - break; - } - } - - buffer.append("
"); //$NON-NLS-1$ - return buffer.toString(); - } - - /* - * @see ICompletionProposal#getSelection(IDocument) - */ - public Point getSelection(IDocument document) { - return new Point(fSelectedRegion.getOffset(), fSelectedRegion - .getLength()); - } - - protected void handleException(CoreException e) { - WebUI.log(e); - } - - protected void openErrorDialog(BadLocationException e) { - Shell shell = fViewer.getTextWidget().getShell(); - MessageDialog.openError(shell, TemplateMessages - .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ - } - - public IContextInformation getContextInformation() { - return null; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java deleted file mode 100644 index 22cface..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -import java.util.ArrayList; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.swt.graphics.Point; - -public class BuiltInEngine { - - /** The context type. */ - private JavaContextType fContextType; - - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); - - /** - * Creates the template engine for a particular context type. See - * TemplateContext for supported context types. - */ - public BuiltInEngine(JavaContextType contextType) { - // Assert.isNotNull(contextType); - fContextType = contextType; - } - - /** - * Empties the collector. - * - * @param viewer - * the text viewer - * @param unit - * the compilation unit (may be null) - */ - public void reset() { - fProposals.clear(); - } - - /** - * Returns the array of matching templates. - */ - public IPHPCompletionProposal[] getResults() { - return (IPHPCompletionProposal[]) fProposals - .toArray(new IPHPCompletionProposal[fProposals.size()]); - } - - /** - * Inspects the context of the compilation unit around - * completionPosition and feeds the collector with proposals. - * - * @param viewer - * the text viewer - * @param completionPosition - * the context position in the document of the text viewer - * @param compilationUnit - * the compilation unit (may be null) - */ - public void complete(ITextViewer viewer, int completionPosition, - ArrayList identifiers, ICompilationUnit compilationUnit) - // hrows JavaModelException - { - IDocument document = viewer.getDocument(); - - // prohibit recursion - // if (LinkedPositionManager.hasActiveManager(document)) - // return; - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - Point selection = viewer.getSelectedRange(); - // remember selected text - String selectedText = null; - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - // ((CompilationUnitContextType) - // fContextType).setContextParameters(document, completionPosition, - // selection.y); //mpilationUnit); - // JavaContext context = (JavaContext) fContextType.createContext(); - JavaContext context = (JavaContext) fContextType.createContext( - document, completionPosition, selection.y, compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - int start = context.getStart(); - int end = context.getEnd(); - IRegion region = new Region(start, end - start); - - // Template[] templates= Templates.getInstance().getTemplates(); - String identifier = null; - int maxProposals = WebUI.MAX_PROPOSALS; - PHPElement element = null; - for (int i = 0; i != identifiers.size(); i++) { - element = (PHPElement) identifiers.get(i); - if (element instanceof PHPFunction) { - identifier = ((PHPFunction) element).getName(); - if (context.canEvaluate(identifier)) { - if (maxProposals-- < 0) { - return; - } - fProposals.add(new BuiltInProposal(identifier, - (PHPFunction) element, context, region, viewer)); - } - } - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java deleted file mode 100644 index f05e19d..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.swt.graphics.Image; - -// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -// import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; - -/** - * A PHP identifier proposal. - */ -public class BuiltInProposal extends AbstractProposal { - private final TemplateContext fContext; - - private final PHPFunction fFunction; - - private final IRegion fRegion; - - private final String fBuiltinFunctionName; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param context - * the context in which the template was requested. - * @param image - * the icon of the proposal. - */ - public BuiltInProposal(String functionName, PHPFunction function, - TemplateContext context, IRegion region, ITextViewer viewer) { - super(viewer); - fBuiltinFunctionName = functionName; - fFunction = function; - fContext = context; - // fViewer = viewer; - fRegion = region; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - // if (fTemplateBuffer == null) - // fTemplateBuffer= fContext.evaluate(fTemplate); - - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - - // insert template string - // String templateString = fTemplate; // - // fTemplateBuffer.getString(); - document.replace(start, end - start, fBuiltinFunctionName + "()"); - - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - // TemplatePosition[] variables= fTemplateBuffer.getVariables(); - // for (int i= 0; i != variables.length; i++) { - // TemplatePosition variable= variables[i]; - // - // if (variable.isResolved()) - // continue; - // - // int[] offsets= variable.getOffsets(); - // int length= variable.getLength(); - // - // for (int j= 0; j != offsets.length; j++) - // manager.addPosition(offsets[j] + start, length); - // } - - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(fBuiltinFunctionName.length() + start - + 1); - // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + - // start); - editor.enter(); - - fSelectedRegion = editor.getSelectedRegion(); - - } catch (BadLocationException e) { - WebUI.log(e); - openErrorDialog(e); - - } - // catch (CoreException e) { - // handleException(e); - // } - } - - public String getAdditionalProposalInfo() { - return fFunction.getHoverText(); - } - - public IContextInformation getContextInformation() { - if (fContextInfo == null) { - String contextInfoString = fFunction.getHoverText(); - if (contextInfoString != null && contextInfoString.length() > 0) { - // extract the parameter context information for the function: - int i0 = contextInfoString.indexOf('('); - int newline = contextInfoString.indexOf('\n'); - if (i0 >= 0 && (i0 < newline || newline < 0)) { - int i1 = contextInfoString.indexOf(')', i0 + 1); - if (i1 > 0) { - fContextInfo = new ContextInformation(null, - contextInfoString.substring(i0 + 1, i1)); - } else { - fContextInfo = new ContextInformation(null, - contextInfoString); - } - } else { - fContextInfo = new ContextInformation(null, - contextInfoString); - } - } - } - return fContextInfo; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - return fBuiltinFunctionName - + TemplateMessages.getString("TemplateProposal.delimiter") + fFunction.getUsage(); // $NON-NLS-1$ - // //$NON-NLS-1$ - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return PHPUiImages.get(PHPUiImages.IMG_BUILTIN); - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - - if (fContext instanceof JavaContext) { - JavaContext context = (JavaContext) fContext; - switch (context.getCharacterBeforeStart()) { - // high relevance after whitespace - case ' ': - case '\r': - case '\n': - case '\t': - return 50; - - default: - return 0; - } - } else { - return 50; - } - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java deleted file mode 100644 index f393c18..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.SortedMap; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.swt.graphics.Point; - -public class DeclarationEngine { - - /** The context type. */ - private JavaContextType fContextType; - - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); - - /** Token determines last which declarations are allowed for proposal */ - private int fLastSignificantToken; - - private IProject fProject; - - // private IFile fFile; - private String fFileName; - - /** - * Creates the template engine for a particular context type. See - * TemplateContext for supported context types. - */ - public DeclarationEngine(IProject project, JavaContextType contextType, - int lastSignificantToken, IFile file) { - // Assert.isNotNull(contextType); - fProject = project; - fContextType = contextType; - - fLastSignificantToken = lastSignificantToken; - // fFile = file; - if (file != null) { - fFileName = file.getProjectRelativePath().toString(); - } else { - fFileName = ""; - } - } - - /** - * Empties the collector. - * - * @param viewer - * the text viewer - * @param unit - * the compilation unit (may be null) - */ - public void reset() { - fProposals.clear(); - } - - /** - * Returns the array of matching templates. - */ - public IPHPCompletionProposal[] getResults() { - return (IPHPCompletionProposal[]) fProposals - .toArray(new IPHPCompletionProposal[fProposals.size()]); - } - - /** - * Inspects the context of the compilation unit around - * completionPosition and feeds the collector with proposals. - * - * @param viewer - * the text viewer - * @param completionPosition - * the context position in the document of the text viewer - * @param compilationUnit - * the compilation unit (may be null) - */ - public void completeObject(ITextViewer viewer, int completionPosition, - SortedMap map, ICompilationUnit compilationUnit) { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - - // remember selected text - String selectedText = null; - - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - JavaContext context = (JavaContext) fContextType.createContext( - document, completionPosition, selection.y, compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - - int start = context.getStart(); - int end = context.getEnd(); - String prefix = context.getKey(); - IRegion region = new Region(start, end - start); - - String identifier = null; - - SortedMap subMap = map.subMap(prefix, prefix + '\255'); - Iterator iter = subMap.keySet().iterator(); - PHPIdentifierLocation location; - ArrayList list; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - while (iter.hasNext()) { - identifier = (String) iter.next(); - if (context.canEvaluate(identifier)) { - list = (ArrayList) subMap.get(identifier); - for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list.get(i); - int type = location.getType(); - switch (fLastSignificantToken) { - case ITerminalSymbols.TokenNameMINUS_GREATER: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNameVariable: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses - // if (fFileName.equals(location.getFilename())) { - // continue; // for loop - // } - break; - case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses - // if (!fFileName.equals(location.getFilename())) { - // continue; // for loop - // } - break; - case ITerminalSymbols.TokenNamenew: - if (type != PHPIdentifierLocation.CLASS - && type != PHPIdentifierLocation.CONSTRUCTOR) { - continue; // for loop - } - break; - default: - if (type == PHPIdentifierLocation.METHOD - || type == PHPIdentifierLocation.CONSTRUCTOR - || type == PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - } - if (maxProposals-- < 0) { - return; - } - fProposals.add(new DeclarationProposal(fProject, - identifier, location, context, region, viewer)); - } - } - } - - } - - /** - * Inspects the context of the compilation unit around - * completionPosition and feeds the collector with proposals. - * - * @param viewer - * the text viewer - * @param completionPosition - * the context position in the document of the text viewer - * @param compilationUnit - * the compilation unit (may be null) - */ - public void complete(ITextViewer viewer, int completionPosition, - SortedMap map, ICompilationUnit compilationUnit) { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - - // remember selected text - String selectedText = null; - - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - // ((CompilationUnitContextType) - // fContextType).setContextParameters(document, completionPosition, - // selection.y); - - // CompilationUnitContext context = (CompilationUnitContext) - // fContextType.createContext(); - JavaContext context = (JavaContext) fContextType.createContext( - document, completionPosition, selection.y, compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - - int start = context.getStart(); - int end = context.getEnd(); - String prefix = context.getKey(); - IRegion region = new Region(start, end - start); - - String identifier = null; - - SortedMap subMap = map.subMap(prefix, prefix + '\255'); - Iterator iter = subMap.keySet().iterator(); - PHPIdentifierLocation location; - ArrayList list; - int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; - while (iter.hasNext()) { - identifier = (String) iter.next(); - if (context.canEvaluate(identifier)) { - list = (ArrayList) subMap.get(identifier); - for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list.get(i); - int type = location.getType(); - switch (fLastSignificantToken) { - case ITerminalSymbols.TokenNameMINUS_GREATER: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNameVariable: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses - if (fFileName.equals(location.getFilename())) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: - if (type != PHPIdentifierLocation.METHOD - && type != PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - // check all filenames of the subclasses - if (!fFileName.equals(location.getFilename())) { - continue; // for loop - } - break; - case ITerminalSymbols.TokenNamenew: - if (type != PHPIdentifierLocation.CLASS - && type != PHPIdentifierLocation.CONSTRUCTOR) { - continue; // for loop - } - break; - default: - if (type == PHPIdentifierLocation.METHOD - || type == PHPIdentifierLocation.CONSTRUCTOR - || type == PHPIdentifierLocation.VARIABLE) { - continue; // for loop - } - } - if (maxProposals-- < 0) { - return; - } - fProposals.add(new DeclarationProposal(fProject, - identifier, location, context, region, viewer)); - } - } - } - - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java deleted file mode 100644 index d08d6e8..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -import net.sourceforge.phpdt.internal.corext.phpdoc.PHPDocUtil; -import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.swt.graphics.Image; - -// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -// import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; - -/** - * A PHP identifier proposal. - */ -public class DeclarationProposal extends AbstractProposal { // implements - // IPHPCompletionProposal - // { - private IProject fProject; - - private final TemplateContext fContext; - - private final PHPIdentifierLocation fLocation; - - String fInfo; - - // private TemplateBuffer fTemplateBuffer; - // private String fOldText; - // private final Image fImage_fun; - // private final Image fImage_var; - private final IRegion fRegion; - - // private IRegion fSelectedRegion; // initialized by apply() - - private final String fIdentifierName; - - // private final ITextViewer fViewer; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param context - * the context in which the template was requested. - * @param image - * the icon of the proposal. - */ - public DeclarationProposal(IProject project, String identifierName, - PHPIdentifierLocation location, TemplateContext context, - IRegion region, ITextViewer viewer) { - super(viewer); - // Image image_fun, - // Image image_var) { - fProject = project; - fIdentifierName = identifierName; - fLocation = location; - fContext = context; - fRegion = region; - fInfo = null; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - // if (fTemplateBuffer == null) - // fTemplateBuffer= fContext.evaluate(fTemplate); - - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - - switch (fLocation.getType()) { - case PHPIdentifierLocation.FUNCTION: - document.replace(start, end - start, fIdentifierName + "()"); - break; - case PHPIdentifierLocation.CONSTRUCTOR: - document.replace(start, end - start, fIdentifierName + "()"); - break; - case PHPIdentifierLocation.METHOD: - document.replace(start, end - start, fIdentifierName + "()"); - break; - - default: - document.replace(start, end - start, fIdentifierName); - } - - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - // TemplatePosition[] variables= fTemplateBuffer.getVariables(); - // for (int i= 0; i != variables.length; i++) { - // TemplatePosition variable= variables[i]; - // - // if (variable.isResolved()) - // continue; - // - // int[] offsets= variable.getOffsets(); - // int length= variable.getLength(); - // - // for (int j= 0; j != offsets.length; j++) - // manager.addPosition(offsets[j] + start, length); - // } - - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - switch (fLocation.getType()) { - case PHPIdentifierLocation.FUNCTION: - editor - .setFinalCaretOffset(fIdentifierName.length() + start - + 1); - break; - case PHPIdentifierLocation.CONSTRUCTOR: - editor - .setFinalCaretOffset(fIdentifierName.length() + start - + 1); - break; - case PHPIdentifierLocation.METHOD: - editor - .setFinalCaretOffset(fIdentifierName.length() + start - + 1); - break; - - default: - editor.setFinalCaretOffset(fIdentifierName.length() + start); - } - editor.enter(); - - fSelectedRegion = editor.getSelectedRegion(); - - } catch (BadLocationException e) { - WebUI.log(e); - openErrorDialog(e); - - } - // catch (CoreException e) { - // handleException(e); - // } - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - if (fInfo == null) { - fInfo = computeProposalInfo(); - } - return fInfo; - } - - private String computeProposalInfo() { - StringBuffer hoverInfoBuffer = new StringBuffer(); - // String workspaceLocation = - // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); - String workspaceLocation; - if (fProject != null) { - workspaceLocation = fProject.getLocation().toString() + '/'; - } else { - // should never happen? - workspaceLocation = WebUI.getWorkspace().getRoot() - .getFullPath().toString(); - } - String filename = workspaceLocation + fLocation.getFilename(); - PHPDocUtil.appendPHPDoc(hoverInfoBuffer, filename, fLocation); - return hoverInfoBuffer.toString(); - } - - public IContextInformation getContextInformation() { - if (fContextInfo == null) { - if (fLocation != null) { - fInfo = fLocation.getUsage(); - if (fInfo != null) { - // extract the parameter context information for the - // function: - int i0 = fInfo.indexOf('('); - int newline = fInfo.indexOf('\n'); - if (i0 >= 0 && (i0 < newline || newline < 0)) { - int i1 = fInfo.indexOf(')', i0 + 1); - if (i1 > 0) { - - fContextInfo = new ContextInformation(null, fInfo - .substring(i0 + 1, i1)); - } else { - fContextInfo = new ContextInformation(null, fInfo); - } - } else { - fContextInfo = new ContextInformation(null, fInfo); - } - } - } - } - return fContextInfo; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - String workspaceLocation; - String workspaceName; - if (fProject != null) { - workspaceLocation = fProject.getFullPath().toString() + '/'; - workspaceName = fProject.getName().toString() + '/'; - } else { - // should never happen? - workspaceLocation = WebUI.getWorkspace().getRoot() - .getFullPath().toString(); - workspaceName = workspaceLocation; - } - String filename = fLocation.getFilename(); - String usage = PHPDocUtil.getUsage(workspaceLocation + filename, fLocation); - String result = fIdentifierName - + TemplateMessages.getString("TemplateProposal.delimiter"); - if (usage.length() > 0) { - result += usage - + TemplateMessages.getString("TemplateProposal.delimiter"); - } - result += workspaceName + filename; - return result; - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - switch (fLocation.getType()) { - case PHPIdentifierLocation.FUNCTION: - return PHPUiImages.get(PHPUiImages.IMG_FUN); - case PHPIdentifierLocation.CLASS: - return PHPUiImages.get(PHPUiImages.IMG_CLASS); - case PHPIdentifierLocation.CONSTRUCTOR: - return PHPUiImages.get(PHPUiImages.IMG_CLASS); - case PHPIdentifierLocation.METHOD: - return PHPUiImages.get(PHPUiImages.IMG_FUN); - case PHPIdentifierLocation.DEFINE: - return PHPUiImages.get(PHPUiImages.IMG_DEFINE); - case PHPIdentifierLocation.VARIABLE: - return PHPUiImages.get(PHPUiImages.IMG_VAR); - case PHPIdentifierLocation.GLOBAL_VARIABLE: - return PHPUiImages.get(PHPUiImages.IMG_VAR); - } - return PHPUiImages.get(PHPUiImages.IMG_FUN); - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - - if (fContext instanceof JavaContext) { - JavaContext context = (JavaContext) fContext; - switch (context.getCharacterBeforeStart()) { - // high relevance after whitespace - case ' ': - case '\r': - case '\n': - case '\t': - return 80; - case '>': // -> - case ':': // :: - return 85; - default: - return 0; - } - } else { - return 80; - } - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java deleted file mode 100644 index 0d67c8a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.text.template; - -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.swt.graphics.Image; - -/** - * A PHP local identifier proposal. - */ -public class LocalVariableProposal extends AbstractProposal { - - private final String fIdentifierName; - - private final IRegion fRegion; - - private final int fRelevance; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param image - * the icon of the proposal. - */ - public LocalVariableProposal(String identifierName, IRegion region, - ITextViewer viewer) { - this(identifierName, region, viewer, 99); - } - - public LocalVariableProposal(String identifierName, IRegion region, - ITextViewer viewer, int relevance) { - super(viewer); - fIdentifierName = identifierName; - fRegion = region; - fRelevance = relevance; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - // if (fTemplateBuffer == null) - // fTemplateBuffer= fContext.evaluate(fTemplate); - - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - - document.replace(start, end - start, fIdentifierName); - - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(fIdentifierName.length() + start); - editor.enter(); - - fSelectedRegion = editor.getSelectedRegion(); - - } catch (BadLocationException e) { - WebUI.log(e); - openErrorDialog(e); - - } - // catch (CoreException e) { - // handleException(e); - // } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (obj instanceof LocalVariableProposal) { - return fIdentifierName - .equals(((LocalVariableProposal) obj).fIdentifierName); - } - return false; - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - StringBuffer hoverInfoBuffer = new StringBuffer(); - if (fRelevance > 95) { - hoverInfoBuffer.append("function source variable -"); - } else { - hoverInfoBuffer.append("editor source variable -"); - } - hoverInfoBuffer.append(fIdentifierName); - return hoverInfoBuffer.toString(); - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - return fIdentifierName; // $NON-NLS-1$ //$NON-NLS-1$ - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return PHPUiImages.get(PHPUiImages.IMG_VAR); - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - return fRelevance; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fIdentifierName.hashCode(); - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java deleted file mode 100644 index a7af0d6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ -package net.sourceforge.phpdt.internal.ui.text.template; - -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.swt.graphics.Image; - -/** - * A PHP identifier proposal. - */ -public class SQLProposal extends AbstractProposal { - private final TemplateContext fContext; - - private final Image fImage_var; - - private final IRegion fRegion; - - private final String fColumnName; - - private final String fTableName; - - private int fRelevance; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param context - * the context in which the template was requested. - * @param image - * the icon of the proposal. - */ - public SQLProposal(String tableName, TemplateContext context, - IRegion region, ITextViewer viewer, Image image_var) { - super(viewer); - fTableName = tableName; - fColumnName = null; - fContext = context; - fImage_var = image_var; - fRegion = region; - fRelevance = 0; - } - - public SQLProposal(String tableName, String columnName, - TemplateContext context, IRegion region, ITextViewer viewer, - Image image_var) { - super(viewer); - fTableName = tableName; - fColumnName = columnName; - fContext = context; - fImage_var = image_var; - fRegion = region; - fRelevance = 0; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - try { - int start = fRegion.getOffset(); - int end = fRegion.getOffset() + fRegion.getLength(); - String resultString = fTableName; - if (fColumnName != null) { - resultString = fColumnName; - } - // insert template string - document.replace(start, end - start, resultString); - // translate positions - LinkedPositionManager manager = new LinkedPositionManager(document); - LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); - editor.setFinalCaretOffset(resultString.length() + start); - editor.enter(); - fSelectedRegion = editor.getSelectedRegion(); - } catch (BadLocationException e) { - WebUI.log(e); - openErrorDialog(e); - } - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - if (fColumnName == null) { - return textToHTML(fTableName); - } - return fColumnName + " (Table: " + fTableName + ")"; - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - if (fColumnName == null) { - return fTableName; - } - return fColumnName + " (Table: " + fTableName + ")"; // $NON-NLS-1$ - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return fImage_var; - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - return fRelevance; - } - - /** - * @param relevance - * The relevance to set. - */ - public void setRelevance(int relevance) { - fRelevance = relevance; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java deleted file mode 100644 index f1d9ee5..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java +++ /dev/null @@ -1,171 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.template.contentassist; - -import java.util.ArrayList; - -import net.sourceforge.phpdt.core.ICompilationUnit; -//incastrix -//import net.sourceforge.phpdt.internal.corext.Assert; -import org.eclipse.core.runtime.Assert; -import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContext; -import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.templates.GlobalTemplateVariables; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.swt.graphics.Point; - -public class TemplateEngine { - - private static final String $_LINE_SELECTION = "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$ - - private static final String $_WORD_SELECTION = "${" + GlobalTemplateVariables.WordSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$ - - /** The context type. */ - private TemplateContextType fContextType; - - /** The result proposals. */ - private ArrayList fProposals = new ArrayList(); - - /** - * Creates the template engine for a particular context type. See - * TemplateContext for supported context types. - */ - public TemplateEngine(TemplateContextType contextType) { - Assert.isNotNull(contextType); - fContextType = contextType; - } - - /** - * Empties the collector. - */ - public void reset() { - fProposals.clear(); - } - - /** - * Returns the array of matching templates. - */ - public TemplateProposal[] getResults() { - return (TemplateProposal[]) fProposals - .toArray(new TemplateProposal[fProposals.size()]); - } - - /** - * Inspects the context of the compilation unit around - * completionPosition and feeds the collector with proposals. - * - * @param viewer - * the text viewer - * @param completionPosition - * the context position in the document of the text viewer - * @param compilationUnit - * the compilation unit (may be null) - */ - public void complete(ITextViewer viewer, int completionPosition, - ICompilationUnit compilationUnit) { - IDocument document = viewer.getDocument(); - - if (!(fContextType instanceof CompilationUnitContextType)) - return; - - Point selection = viewer.getSelectedRange(); - - // remember selected text - String selectedText = null; - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - CompilationUnitContext context = ((CompilationUnitContextType) fContextType) - .createContext(document, completionPosition, selection.y, - compilationUnit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - int start = context.getStart(); - int end = context.getEnd(); - IRegion region = new Region(start, end - start); - - Template[] templates = WebUI.getDefault().getTemplateStore() - .getTemplates(); - - if (selection.y == 0) { - for (int i = 0; i != templates.length; i++) - if (context.canEvaluate(templates[i])) - fProposals.add(new TemplateProposal(templates[i], context, - region, PHPUiImages - .get(PHPUiImages.IMG_OBJS_TEMPLATE))); - - } else { - - if (context.getKey().length() == 0) - context.setForceEvaluation(true); - - boolean multipleLinesSelected = areMultipleLinesSelected(viewer); - - for (int i = 0; i != templates.length; i++) { - Template template = templates[i]; - if (context.canEvaluate(template) - && template.getContextTypeId().equals( - context.getContextType().getId()) - && (!multipleLinesSelected - && template.getPattern().indexOf( - $_WORD_SELECTION) != -1 || (multipleLinesSelected && template - .getPattern().indexOf($_LINE_SELECTION) != -1))) { - fProposals.add(new TemplateProposal(templates[i], context, - region, PHPUiImages - .get(PHPUiImages.IMG_OBJS_TEMPLATE))); - } - } - } - } - - /** - * Returns true if one line is completely selected or if - * multiple lines are selected. Being completely selected means that all - * characters except the new line characters are selected. - * - * @return true if one or multiple lines are selected - * @since 2.1 - */ - private boolean areMultipleLinesSelected(ITextViewer viewer) { - if (viewer == null) - return false; - - Point s = viewer.getSelectedRange(); - if (s.y == 0) - return false; - - try { - - IDocument document = viewer.getDocument(); - int startLine = document.getLineOfOffset(s.x); - int endLine = document.getLineOfOffset(s.x + s.y); - IRegion line = document.getLineInformation(startLine); - return startLine != endLine - || (s.x == line.getOffset() && s.y == line.getLength()); - - } catch (BadLocationException x) { - return false; - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java deleted file mode 100644 index 420c91b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java +++ /dev/null @@ -1,479 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.template.contentassist; - -import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContext; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.EditorHighlightingSynchronizer; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.MessageDialog; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; -import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.link.ILinkedModeListener; -import org.eclipse.jface.text.link.LinkedModeModel; -import org.eclipse.jface.text.link.LinkedModeUI; -import org.eclipse.jface.text.link.LinkedPosition; -import org.eclipse.jface.text.link.LinkedPositionGroup; -import org.eclipse.jface.text.link.ProposalPosition; -import org.eclipse.jface.text.templates.DocumentTemplateContext; -import org.eclipse.jface.text.templates.GlobalTemplateVariables; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateBuffer; -import org.eclipse.jface.text.templates.TemplateContext; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.text.templates.TemplateVariable; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; - -/** - * A template proposal. - */ -public class TemplateProposal implements IPHPCompletionProposal, - ICompletionProposalExtension2, ICompletionProposalExtension3 { - - private final Template fTemplate; - - private final TemplateContext fContext; - - private final Image fImage; - - private IRegion fRegion; - - private int fRelevance; - - private IRegion fSelectedRegion; // initialized by apply() - - private String fDisplayString; - - /** - * Creates a template proposal with a template and its context. - * - * @param template - * the template - * @param context - * the context in which the template was requested - * @param region - * the region this proposal applies to - * @param image - * the icon of the proposal - */ - public TemplateProposal(Template template, TemplateContext context, - IRegion region, Image image) { - Assert.isNotNull(template); - Assert.isNotNull(context); - Assert.isNotNull(region); - - fTemplate = template; - fContext = context; - fImage = image; - fRegion = region; - - fDisplayString = null; - - if (context instanceof JavaContext) { - switch (((JavaContext) context).getCharacterBeforeStart()) { - // high relevance after whitespace - case ' ': - case '\r': - case '\n': - case '\t': - fRelevance = 90; - break; - default: - fRelevance = 0; - } - } else { - fRelevance = 90; - } - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public final void apply(IDocument document) { - // not called anymore - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, - * char, int, int) - */ - public void apply(ITextViewer viewer, char trigger, int stateMask, - int offset) { - - try { - - fContext.setReadOnly(false); - TemplateBuffer templateBuffer; - try { - templateBuffer = fContext.evaluate(fTemplate); - } catch (TemplateException e1) { - fSelectedRegion = fRegion; - return; - } - - int start = getReplaceOffset(); - int end = getReplaceEndOffset(); - end = Math.max(end, offset); - - // insert template string - IDocument document = viewer.getDocument(); - String templateString = templateBuffer.getString(); - document.replace(start, end - start, templateString); - - // translate positions - LinkedModeModel model = new LinkedModeModel(); - TemplateVariable[] variables = templateBuffer.getVariables(); - - MultiVariableGuess guess = fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext) - .getMultiVariableGuess() - : null; - - boolean hasPositions = false; - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - - if (variable.isUnambiguous()) - continue; - - LinkedPositionGroup group = new LinkedPositionGroup(); - - int[] offsets = variable.getOffsets(); - int length = variable.getLength(); - - LinkedPosition first; - if (guess != null && variable instanceof MultiVariable) { - first = new VariablePosition(document, offsets[0] + start, - length, guess, (MultiVariable) variable); - guess.addSlave((VariablePosition) first); - } else { - String[] values = variable.getValues(); - ICompletionProposal[] proposals = new ICompletionProposal[values.length]; - for (int j = 0; j < values.length; j++) { - ensurePositionCategoryInstalled(document, model); - Position pos = new Position(offsets[0] + start, length); - document.addPosition(getCategory(), pos); - proposals[j] = new PositionBasedCompletionProposal( - values[j], pos, length); - } - - if (proposals.length > 1) - first = new ProposalPosition(document, offsets[0] - + start, length, proposals); - else - first = new LinkedPosition(document, - offsets[0] + start, length); - } - - for (int j = 0; j != offsets.length; j++) - if (j == 0) - group.addPosition(first); - else - group.addPosition(new LinkedPosition(document, - offsets[j] + start, length)); - - model.addGroup(group); - hasPositions = true; - } - - if (hasPositions) { - model.forceInstall(); - PHPEditor editor = getJavaEditor(); - if (editor != null) { - model - .addLinkingListener(new EditorHighlightingSynchronizer( - editor)); - } - - LinkedModeUI ui = new EditorLinkedModeUI(model, viewer); - ui.setExitPosition(viewer, getCaretOffset(templateBuffer) - + start, 0, Integer.MAX_VALUE); - ui.enter(); - - fSelectedRegion = ui.getSelectedRegion(); - } else - fSelectedRegion = new Region(getCaretOffset(templateBuffer) - + start, 0); - - } catch (BadLocationException e) { - WebUI.log(e); - openErrorDialog(viewer.getTextWidget().getShell(), e); - fSelectedRegion = fRegion; - } catch (BadPositionCategoryException e) { - WebUI.log(e); - openErrorDialog(viewer.getTextWidget().getShell(), e); - fSelectedRegion = fRegion; - } - - } - - /** - * Returns the currently active java editor, or null if it - * cannot be determined. - * - * @return the currently active java editor, or null - */ - private PHPEditor getJavaEditor() { - IEditorPart part = WebUI.getActivePage().getActiveEditor(); - if (part instanceof PHPEditor) - return (PHPEditor) part; - else - return null; - } - - /** - * Returns the offset of the range in the document that will be replaced by - * applying this template. - * - * @return the offset of the range in the document that will be replaced by - * applying this template - */ - private int getReplaceOffset() { - int start; - if (fContext instanceof DocumentTemplateContext) { - DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; - start = docContext.getStart(); - } else { - start = fRegion.getOffset(); - } - return start; - } - - /** - * Returns the end offset of the range in the document that will be replaced - * by applying this template. - * - * @return the end offset of the range in the document that will be replaced - * by applying this template - */ - private int getReplaceEndOffset() { - int end; - if (fContext instanceof DocumentTemplateContext) { - DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; - end = docContext.getEnd(); - } else { - end = fRegion.getOffset() + fRegion.getLength(); - } - return end; - } - - private void ensurePositionCategoryInstalled(final IDocument document, - LinkedModeModel model) { - if (!document.containsPositionCategory(getCategory())) { - document.addPositionCategory(getCategory()); - final InclusivePositionUpdater updater = new InclusivePositionUpdater( - getCategory()); - document.addPositionUpdater(updater); - - model.addLinkingListener(new ILinkedModeListener() { - - /* - * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, - * int) - */ - public void left(LinkedModeModel environment, int flags) { - try { - document.removePositionCategory(getCategory()); - } catch (BadPositionCategoryException e) { - // ignore - } - document.removePositionUpdater(updater); - } - - public void suspend(LinkedModeModel environment) { - } - - public void resume(LinkedModeModel environment, int flags) { - } - }); - } - } - - private String getCategory() { - return "TemplateProposalCategory_" + toString(); //$NON-NLS-1$ - } - - private int getCaretOffset(TemplateBuffer buffer) { - - TemplateVariable[] variables = buffer.getVariables(); - for (int i = 0; i != variables.length; i++) { - TemplateVariable variable = variables[i]; - if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) - return variable.getOffsets()[0]; - } - - return buffer.getString().length(); - } - - /* - * @see ICompletionProposal#getSelection(IDocument) - */ - public Point getSelection(IDocument document) { - return new Point(fSelectedRegion.getOffset(), fSelectedRegion - .getLength()); - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - try { - fContext.setReadOnly(true); - TemplateBuffer templateBuffer; - try { - templateBuffer = fContext.evaluate(fTemplate); - } catch (TemplateException e1) { - return null; - } - - return templateBuffer.getString(); - - } catch (BadLocationException e) { - handleException(WebUI.getActiveWorkbenchShell(), - new CoreException(new Status(IStatus.ERROR, - WebUI.getPluginId(), IStatus.OK, "", e))); //$NON-NLS-1$ - return null; - } - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - if (fDisplayString == null) { - fDisplayString = fTemplate.getName() - + TemplateContentAssistMessages - .getString("TemplateProposal.delimiter") + fTemplate.getDescription(); //$NON-NLS-1$ - } - return fDisplayString; - } - -// public void setDisplayString(String displayString) { -// fDisplayString = displayString; -// } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return fImage; - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - - private void openErrorDialog(Shell shell, Exception e) { - MessageDialog.openError(shell, TemplateContentAssistMessages - .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ - } - - private void handleException(Shell shell, CoreException e) { - ExceptionHandler.handle(e, shell, TemplateContentAssistMessages - .getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ - } - - /* - * @see IJavaCompletionProposal#getRelevance() - */ - public int getRelevance() { - return fRelevance; - } - -// public void setRelevance(int relevance) { -// fRelevance = relevance; -// } - -// public Template getTemplate() { -// return fTemplate; -// } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator() - */ - public IInformationControlCreator getInformationControlCreator() { - return new TemplateInformationControlCreator(); - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, - * boolean) - */ - public void selected(ITextViewer viewer, boolean smartToggle) { - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) - */ - public void unselected(ITextViewer viewer) { - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, - * int, org.eclipse.jface.text.DocumentEvent) - */ - public boolean validate(IDocument document, int offset, DocumentEvent event) { - try { - int replaceOffset = getReplaceOffset(); - if (offset >= replaceOffset) { - String content = document.get(replaceOffset, offset - - replaceOffset); - return fTemplate.getName().startsWith(content); - } - } catch (BadLocationException e) { - // concurrent modification - ignore - } - return false; - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementString() - */ - public CharSequence getPrefixCompletionText(IDocument document, - int completionOffset) { - return fTemplate.getName(); - } - - /* - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementOffset() - */ - public int getPrefixCompletionStart(IDocument document, int completionOffset) { - return getReplaceOffset(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java deleted file mode 100644 index 54ec6b3..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.text.template.preferences; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.templates.TemplateVariableResolver; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Shell; - -/** - * A proposal for insertion of template variables. - */ -public class TemplateVariableProposal implements ICompletionProposal { - - private TemplateVariableResolver fVariable; - - private int fOffset; - - private int fLength; - - private ITextViewer fViewer; - - private Point fSelection; - - /** - * Creates a template variable proposal. - * - * @param variable - * the template variable - * @param offset - * the offset to replace - * @param length - * the length to replace - * @param viewer - * the viewer - */ - public TemplateVariableProposal(TemplateVariableResolver variable, - int offset, int length, ITextViewer viewer) { - fVariable = variable; - fOffset = offset; - fLength = length; - fViewer = viewer; - } - - /* - * @see ICompletionProposal#apply(IDocument) - */ - public void apply(IDocument document) { - - try { - String variable = fVariable.getType().equals("dollar") ? "$$" : "${" + fVariable.getType() + '}'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - document.replace(fOffset, fLength, variable); - fSelection = new Point(fOffset + variable.length(), 0); - - } catch (BadLocationException e) { - WebUI.log(e); - - Shell shell = fViewer.getTextWidget().getShell(); - MessageDialog - .openError( - shell, - TemplatePreferencesMessages - .getString("TemplateVariableProposal.error.title"), e.getMessage()); //$NON-NLS-1$ - } - } - - /* - * @see ICompletionProposal#getSelection(IDocument) - */ - public Point getSelection(IDocument document) { - return fSelection; - } - - /* - * @see ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - return null; - } - - /* - * @see ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - return fVariable.getType() + " - " + fVariable.getDescription(); //$NON-NLS-1$ - } - - /* - * @see ICompletionProposal#getImage() - */ - public Image getImage() { - return null; - } - - /* - * @see ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java deleted file mode 100644 index baceffd..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.util; - -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.Shell; - -public class ExceptionHandler { - private static ExceptionHandler fgInstance = new ExceptionHandler(); - - public static void log(Throwable t, String message) { - WebUI.getDefault().getLog().log( - new Status(IStatus.ERROR, WebUI.PLUGIN_ID, - IStatus.ERROR, message, t)); - } - -// public static void handle(CoreException e, String title, String message) { -// handle(e, WebUI.getActiveWorkbenchShell(), title, message); -// } - - public static void handle(CoreException e, Shell parent, String title, - String message) { - fgInstance.perform(e, parent, title, message); - } - -// public static void handle(InvocationTargetException e, String title, -// String message) { -// handle(e, WebUI.getActiveWorkbenchShell(), title, message); -// } - - public static void handle(InvocationTargetException e, Shell parent, - String title, String message) { - fgInstance.perform(e, parent, title, message); - } - - protected void perform(CoreException e, Shell shell, String title, - String message) { - WebUI.log(e); - IStatus status = e.getStatus(); - if (status != null) { - ErrorDialog.openError(shell, title, message, status); - } else { - displayMessageDialog(e, e.getMessage(), shell, title, message); - } - } - - protected void perform(InvocationTargetException e, Shell shell, - String title, String message) { - Throwable target = e.getTargetException(); - if (target instanceof CoreException) { - perform((CoreException) target, shell, title, message); - } else { - WebUI.log(e); - if (e.getMessage() != null && e.getMessage().length() > 0) { - displayMessageDialog(e, e.getMessage(), shell, title, message); - } else { - displayMessageDialog(e, target.getMessage(), shell, title, - message); - } - } - } - - private void displayMessageDialog(Throwable t, String exceptionMessage, - Shell shell, String title, String message) { - StringWriter msg = new StringWriter(); - if (message != null) { - msg.write(message); - msg.write("\n\n"); - } - if (exceptionMessage == null || exceptionMessage.length() == 0) - msg.write(PHPUIMessages - .getString("ExceptionDialog.seeErrorLogMessage")); - else - msg.write(exceptionMessage); - MessageDialog.openError(shell, title, msg.toString()); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java deleted file mode 100644 index 7b83cd0..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.util; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.dialogs.ElementListSelectionDialog; -import org.eclipse.ui.model.IWorkbenchAdapter; - -public class PHPFileSelector extends ResourceSelector { - static class FileLabelProvider extends LabelProvider { - /** - * Returns the implementation of IWorkbenchAdapter for the given object. - * - * @param o - * the object to look up. - * @return IWorkbenchAdapter or null if the adapter is - * not defined or the object is not adaptable. - */ - protected final IWorkbenchAdapter getAdapter(Object o) { - if (!(o instanceof IAdaptable)) { - return null; - } - return (IWorkbenchAdapter) ((IAdaptable) o) - .getAdapter(IWorkbenchAdapter.class); - } - - /* - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element instanceof IFile) { - // query the element for its label - IWorkbenchAdapter adapter = getAdapter(element); - if (adapter == null) { - return ""; //$NON-NLS-1$ - } - String filename = adapter.getLabel(element); - IPath path = ((IFile) element).getFullPath(); - String filePathname = path != null ? path.toString() : ""; //$NON-NLS-1$ - return filename + " (" + filePathname + ")"; - } - return super.getText(element); - } - } - - protected PHPProjectSelector phpProjectSelector; - - public PHPFileSelector(Composite parent, PHPProjectSelector aProjectSelector) { - super(parent); - Assert.isNotNull(aProjectSelector); - phpProjectSelector = aProjectSelector; - - browseDialogTitle = "File Selection"; - } - - protected Object[] getPHPFiles() { - IProject phpProject = phpProjectSelector.getSelection(); - if (phpProject == null) - return new Object[0]; - - PHPElementVisitor visitor = new PHPElementVisitor(); - try { - phpProject.accept(visitor); - } catch (CoreException e) { - WebUI.log(e); - } - return visitor.getCollectedPHPFiles(); - } - - public IFile getSelection() { - String fileName = getSelectionText(); - if (fileName != null && !fileName.equals("")) { - IPath filePath = new Path(fileName); - IProject project = phpProjectSelector.getSelection(); - if (project != null && project.exists(filePath)) - return project.getFile(filePath); - } - - return null; - } - - protected void handleBrowseSelected() { - // ElementListSelectionDialog dialog = new - // ElementListSelectionDialog(getShell(), new WorkbenchLabelProvider()); - ElementListSelectionDialog dialog = new ElementListSelectionDialog( - getShell(), new FileLabelProvider()); - - dialog.setTitle(browseDialogTitle); - dialog.setMessage(browseDialogMessage); - dialog.setElements(getPHPFiles()); - - if (dialog.open() == ElementListSelectionDialog.OK) { - textField.setText(((IResource) dialog.getFirstResult()) - .getProjectRelativePath().toString()); - } - } - - protected String validateResourceSelection() { - IFile selection = getSelection(); - return selection == null ? EMPTY_STRING : selection - .getProjectRelativePath().toString(); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java deleted file mode 100644 index 30ce20f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Created on 09.08.2003 - * - */ - -/*duplicated incastrix*/ -package net.sourceforge.phpdt.internal.ui.util; - -import java.io.File; -import java.util.List; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.ui.IEditorDescriptor; -import org.eclipse.ui.IEditorRegistry; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; - -public class PHPFileUtil { - // private static String[] PHP_EXTENSIONS = null; - - public final static String[] SMARTY_EXTENSIONS = { "tpl" }; - - public static boolean isPHPFile(IFile file) { - return isPHPFileName(file.getFullPath().toString()); - } - - // public final static String getFileExtension(String name) { - // int index = name.lastIndexOf('.'); - // if (index == -1) - // return null; - // if (index == (name.length() - 1)) - // return null; //$NON-NLS-1$ - // return name.substring(index + 1); - // } - - /** - * Returns true iff str.toLowerCase().endsWith(".php") implementation is not - * creating extra strings. - */ - public final static boolean isPHPFileName(String name) { - - // avoid handling a file without base name, e.g. ".php", which is a - // valid - // Eclipse resource name - File file = new File(name); - if (file.getName().startsWith(".")) { - return false; - } - IWorkbench workbench = PlatformUI.getWorkbench(); - IEditorRegistry registry = workbench.getEditorRegistry(); - IEditorDescriptor[] descriptors = registry.getEditors(name); - - for (int i = 0; i < descriptors.length; i++) { - if (descriptors[i].getId().equals(WebUI.EDITOR_ID)) { - return true; - } - } - // String extension = getFileExtension(name); - // if (extension == null) { - // return false; - // } - // extension = extension.toLowerCase(); - // PHP_EXTENSIONS = getExtensions(); - // if (PHP_EXTENSIONS == null) { - // return false; - // } - // for (int i = 0; i < PHP_EXTENSIONS.length; i++) { - // if (extension.equals(PHP_EXTENSIONS[i])) { - // return true; - // } - // } - return false; - } - - /** - * Returns true iff the file extension is a valid PHP Unit name - * implementation is not creating extra strings. - */ -// public final static boolean isValidPHPUnitName(String filename) { -// return PHPFileUtil.isPHPFileName(filename); -// } - - /** - * @return Returns the PHP extensions. - */ - // public static String[] getExtensions() { - // if (PHP_EXTENSIONS == null) { - // ArrayList list = new ArrayList(); - // final IPreferenceStore store = - // PHPeclipsePlugin.getDefault().getPreferenceStore(); - // String extensions = - // store.getString(PHPeclipsePlugin.PHP_EXTENSION_PREFS); - // extensions = extensions.trim(); - // if (extensions.length() != 0) { - // StringTokenizer tokenizer = new StringTokenizer(extensions, " ,;:/-|"); - // String token; - // while (tokenizer.hasMoreTokens()) { - // token = tokenizer.nextToken(); - // if (token != null && token.length() >= 1) { - // list.add(token); - // } - // } - // if (list.size() != 0) { - // PHP_EXTENSIONS = new String[list.size()]; - // for (int i = 0; i < list.size(); i++) { - // PHP_EXTENSIONS[i] = (String) list.get(i); - // } - // } - // } - // } - // return PHP_EXTENSIONS; - // } - /** - * @param php_extensions - * The PHP extensions to set. - */ - // public static void setExtensions(String[] php_extensions) { - // PHP_EXTENSIONS = php_extensions; - // } - /** - * Creata the file for the given absolute file path - * - * @param absoluteFilePath - * @param project - * @return the file for the given absolute file path or null - * if no existing file can be found - */ -// public static IFile createFile(IPath absoluteFilePath, IProject project) { -// if (absoluteFilePath == null || project == null) { -// return null; -// } -// -// String projectPath = project.getFullPath().toString(); -// String filePath = absoluteFilePath.toString().substring( -// projectPath.length() + 1); -// return project.getFile(filePath); -// -// } - - /** - * Determine the path of an include name string - * - * @param includeNameString - * @param resource - * @param project - * @return the path for the given include filename or null if - * no existing file can be found - */ - public static IPath determineFilePath(String includeNameString, - IResource resource, IProject project) { - IPath documentRootPath = ProjectPrefUtil.getDocumentRoot(project); - IPath resourcePath = resource.getProjectRelativePath(); - - IPath path = null; - - // script location based - path = project.getFullPath().append(resourcePath.removeLastSegments(1)) - .append(includeNameString); - //path = - if (fileExists(path, false)) { - return path; - } - // project root based - path = project.getFullPath().append(includeNameString); - if (fileExists(path, false)) { - return path; - } - - // DocumentRoot (absolute path) based - path = documentRootPath.append(includeNameString); - if (fileExists(path, true)) { - return path; - } - - // IncludePaths settings (absolute path) based - List includePaths = ProjectPrefUtil.getIncludePaths(project); - if (includePaths.size() > 0) { - for (int i = 0; i < includePaths.size(); i++) { - path = new Path(includePaths.get(i).toString()) - .append(includeNameString); - if (fileExists(path, true)) { - return path; - } - } - } - return null; - } - - private static boolean fileExists(IPath path, boolean absolute) { - File file = path.toFile(); - if (file.exists()) { - return true; - } - if (!absolute) { - IFile ifile = FileBuffers.getWorkspaceFileAtLocation(path); - if (ifile != null) { - IResource resource = ifile; - if (resource.exists()) { - return true; - } - } - } - return false; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java deleted file mode 100644 index 034d691..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.sourceforge.phpdt.internal.ui.util; - -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.resources.IProject; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.dialogs.ElementListSelectionDialog; -import org.eclipse.ui.model.WorkbenchLabelProvider; - -public class PHPProjectSelector extends ResourceSelector { - - public PHPProjectSelector(Composite parent) { - super(parent); - - browseDialogTitle = "Project Selection"; - } - - public IProject getSelection() { - String projectName = getSelectionText(); - if (projectName != null && !projectName.equals("")) - return WebUI.getWorkspace().getRoot().getProject( - projectName); - - return null; - } - - protected void handleBrowseSelected() { - ElementListSelectionDialog dialog = new ElementListSelectionDialog( - getShell(), new WorkbenchLabelProvider()); - dialog.setTitle(browseDialogTitle); - dialog.setMessage(browseDialogMessage); - dialog.setElements(JavaCore.getPHPProjects()); - - if (dialog.open() == ElementListSelectionDialog.OK) { - textField.setText(((IProject) dialog.getFirstResult()).getName()); - } - } - - protected String validateResourceSelection() { - IProject project = getSelection(); - return project == null ? EMPTY_STRING : project.getName(); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java deleted file mode 100644 index 865baec..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java +++ /dev/null @@ -1,462 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.viewsupport; - -import net.sourceforge.phpdt.core.Flags; -import net.sourceforge.phpdt.core.IField; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IMethod; -//import net.sourceforge.phpdt.core.IPackageFragmentRoot; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.ui.PHPUIMessages; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.ui.JavaElementImageDescriptor; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jface.resource.ImageDescriptor; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -//import org.eclipse.ui.ISharedImages; -//import org.eclipse.ui.ide.IDE.SharedImages; -import org.eclipse.ui.model.IWorkbenchAdapter; - -/** - * Default strategy of the Java plugin for the construction of Java element - * icons. - */ -public class JavaElementImageProvider { - - /** - * Flags for the JavaImageLabelProvider: Generate images with overlays. - */ - public final static int OVERLAY_ICONS = 0x1; - - /** - * Generate small sized images. - */ - public final static int SMALL_ICONS = 0x2; - - /** - * Use the 'light' style for rendering types. - */ - public final static int LIGHT_TYPE_ICONS = 0x4; - - public static final Point SMALL_SIZE = new Point(16, 16); - - public static final Point BIG_SIZE = new Point(22, 16); - - private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; - - private static ImageDescriptor DESC_OBJ_PROJECT; - -// private static ImageDescriptor DESC_OBJ_FOLDER; -// { -// ISharedImages images = WebUI.getDefault().getWorkbench() -// .getSharedImages(); -// DESC_OBJ_PROJECT_CLOSED = images -// .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT_CLOSED); -// DESC_OBJ_PROJECT = images -// .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT); -// DESC_OBJ_FOLDER = images -// .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); -// } - - private ImageDescriptorRegistry fRegistry; - - public JavaElementImageProvider() { - fRegistry = null; // lazy initialization - } - - /** - * Returns the icon for a given element. The icon depends on the element - * type and element properties. If configured, overlay icons are constructed - * for ISourceReferences. - * - * @param flags - * Flags as defined by the JavaImageLabelProvider - */ - public Image getImageLabel(Object element, int flags) { - return getImageLabel(computeDescriptor(element, flags)); - } - - private Image getImageLabel(ImageDescriptor descriptor) { - if (descriptor == null) - return null; - return getRegistry().get(descriptor); - } - - private ImageDescriptorRegistry getRegistry() { - if (fRegistry == null) { - fRegistry = WebUI.getImageDescriptorRegistry(); - } - return fRegistry; - } - - private ImageDescriptor computeDescriptor(Object element, int flags) { - if (element instanceof IJavaElement) { - return getJavaImageDescriptor((IJavaElement) element, flags); - } else if (element instanceof IFile) { - IFile file = (IFile) element; - if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$ - return getCUResourceImageDescriptor(file, flags); // image for - // a CU not - // on the - // build - // path - } - return getWorkbenchImageDescriptor(file, flags); - } else if (element instanceof IAdaptable) { - return getWorkbenchImageDescriptor((IAdaptable) element, flags); - } - return null; - } - - private static boolean showOverlayIcons(int flags) { - return (flags & OVERLAY_ICONS) != 0; - } - - private static boolean useSmallSize(int flags) { - return (flags & SMALL_ICONS) != 0; - } - - private static boolean useLightIcons(int flags) { - return (flags & LIGHT_TYPE_ICONS) != 0; - } - - /** - * Returns an image descriptor for a compilatio unit not on the class path. - * The descriptor includes overlays, if specified. - */ - public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor( - PHPUiImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); - } - - /** - * Returns an image descriptor for a java element. The descriptor includes - * overlays, if specified. - */ - public ImageDescriptor getJavaImageDescriptor(IJavaElement element, - int flags) { - int adornmentFlags = computeJavaAdornmentFlags(element, flags); - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor(getBaseImageDescriptor(element, - flags), adornmentFlags, size); - } - - /** - * Returns an image descriptor for a IAdaptable. The descriptor includes - * overlays, if specified (only error ticks apply). Returns - * null if no image could be found. - */ - public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, - int flags) { - IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) adaptable - .getAdapter(IWorkbenchAdapter.class); - if (wbAdapter == null) { - return null; - } - ImageDescriptor descriptor = wbAdapter.getImageDescriptor(adaptable); - if (descriptor == null) { - return null; - } - - Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; - return new JavaElementImageDescriptor(descriptor, 0, size); - } - - // ---- Computation of base image key - // ------------------------------------------------- - - /** - * Returns an image descriptor for a java element. This is the base image, - * no overlays. - */ - public ImageDescriptor getBaseImageDescriptor(IJavaElement element, - int renderFlags) { - IType type = null; - boolean isInterface = false; - try { - switch (element.getElementType()) { - case IJavaElement.INITIALIZER: - return PHPUiImages.DESC_MISC_PRIVATE; // 23479 - case IJavaElement.METHOD: - IMember member = (IMember) element; - type = member.getDeclaringType(); - isInterface = (type != null) - && member.getDeclaringType().isInterface(); - return getMethodImageDescriptor(isInterface, member.getFlags()); - case IJavaElement.FIELD: - IField field = (IField) element; - return getFieldImageDescriptor(field.getDeclaringType() - .isInterface(), field.getFlags()); - - case IJavaElement.PACKAGE_DECLARATION: - return PHPUiImages.DESC_OBJS_PACKDECL; - - case IJavaElement.IMPORT_DECLARATION: - return PHPUiImages.DESC_OBJS_IMPDECL; - - case IJavaElement.IMPORT_CONTAINER: - return PHPUiImages.DESC_OBJS_IMPCONT; - - case IJavaElement.TYPE: { - type = (IType) element; - isInterface = type.isInterface(); - - if (useLightIcons(renderFlags)) { - return isInterface ? PHPUiImages.DESC_OBJS_INTERFACEALT - : PHPUiImages.DESC_OBJS_CLASSALT; - } - boolean isInner = type.getDeclaringType() != null; - return getTypeImageDescriptor(isInterface, isInner, type - .getFlags()); - } - - case IJavaElement.PACKAGE_FRAGMENT_ROOT: { - //IPackageFragmentRoot root = (IPackageFragmentRoot) element; - // if (root.isArchive()) { - // IPath attach= root.getSourceAttachmentPath(); - // if (root.isExternal()) { - // if (attach == null) { - // return PHPUiImages.DESC_OBJS_EXTJAR; - // } else { - // return PHPUiImages.DESC_OBJS_EXTJAR_WSRC; - // } - // } else { - // if (attach == null) { - // return PHPUiImages.DESC_OBJS_JAR; - // } else { - // return PHPUiImages.DESC_OBJS_JAR_WSRC; - // } - // } - // } else { - return PHPUiImages.DESC_OBJS_PACKFRAG_ROOT; - // } - } - - case IJavaElement.PACKAGE_FRAGMENT: - return getPackageFragmentIcon(element, renderFlags); - - case IJavaElement.COMPILATION_UNIT: - return PHPUiImages.DESC_OBJS_CUNIT; - - case IJavaElement.CLASS_FILE: - /* - * this is too expensive for large packages try { IClassFile - * cfile= (IClassFile)element; if (cfile.isClass()) return - * PHPUiImages.IMG_OBJS_CFILECLASS; return - * PHPUiImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // - * fall through; } - */ - return PHPUiImages.DESC_OBJS_CFILE; - - case IJavaElement.JAVA_PROJECT: - IJavaProject jp = (IJavaProject) element; - if (jp.getProject().isOpen()) { - IProject project = jp.getProject(); - IWorkbenchAdapter adapter = (IWorkbenchAdapter) project - .getAdapter(IWorkbenchAdapter.class); - if (adapter != null) { - ImageDescriptor result = adapter - .getImageDescriptor(project); - if (result != null) - return result; - } - return DESC_OBJ_PROJECT; - } - return DESC_OBJ_PROJECT_CLOSED; - - case IJavaElement.JAVA_MODEL: - return PHPUiImages.DESC_OBJS_JAVA_MODEL; - } - - Assert.isTrue(false, PHPUIMessages - .getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ - return null; //$NON-NLS-1$ - - } catch (JavaModelException e) { - if (e.isDoesNotExist()) - return PHPUiImages.DESC_OBJS_UNKNOWN; - PHPeclipsePlugin.log(e); - return PHPUiImages.DESC_OBJS_GHOST; - } - } - - protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, - int renderFlags) throws JavaModelException { - // IPackageFragment fragment= (IPackageFragment)element; - // boolean containsJavaElements= false; - // try { - // containsJavaElements= fragment.hasChildren(); - // } catch(JavaModelException e) { - // // assuming no children; - // } - // if(!containsJavaElements && (fragment.getNonJavaResources().length > - // 0)) - // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; - // else if (!containsJavaElements) - // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE; - return PHPUiImages.DESC_OBJS_PACKAGE; - } - - public void dispose() { - } - - // ---- Methods to compute the adornments flags - // --------------------------------- - - private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { - int flags = 0; - if (showOverlayIcons(renderFlags) && element instanceof IMember) { - try { - IMember member = (IMember) element; - - if (element.getElementType() == IJavaElement.METHOD - && ((IMethod) element).isConstructor()) - flags |= JavaElementImageDescriptor.CONSTRUCTOR; - - int modifiers = member.getFlags(); - if (Flags.isAbstract(modifiers) && confirmAbstract(member)) - flags |= JavaElementImageDescriptor.ABSTRACT; - if (Flags.isFinal(modifiers) || isInterfaceField(member)) - flags |= JavaElementImageDescriptor.FINAL; - // if (Flags.isSynchronized(modifiers) && - // confirmSynchronized(member)) - // flags |= JavaElementImageDescriptor.SYNCHRONIZED; - if (Flags.isStatic(modifiers) || isInterfaceField(member)) - flags |= JavaElementImageDescriptor.STATIC; - - // if (member.getElementType() == IJavaElement.TYPE) { - // if (JavaModelUtil.hasMainMethod((IType) member)) { - // flags |= JavaElementImageDescriptor.RUNNABLE; - // } - // } - } catch (JavaModelException e) { - // do nothing. Can't compute runnable adornment or get flags - } - } - return flags; - } - - private static boolean confirmAbstract(IMember element) - throws JavaModelException { - // never show the abstract symbol on interfaces or members in interfaces - if (element.getElementType() == IJavaElement.TYPE) { - return ((IType) element).isClass(); - } - return element.getDeclaringType().isClass(); - } - - private static boolean isInterfaceField(IMember element) - throws JavaModelException { - // always show the final && static symbol on interface fields - if (element.getElementType() == IJavaElement.FIELD) { - return element.getDeclaringType().isInterface(); - } - return false; - } - -// private static boolean confirmSynchronized(IJavaElement member) { -// // Synchronized types are allowed but meaningless. -// return member.getElementType() != IJavaElement.TYPE; -// } - - public static ImageDescriptor getMethodImageDescriptor( - boolean isInInterface, int flags) { - if (Flags.isPublic(flags) || isInInterface) - return PHPUiImages.DESC_MISC_PUBLIC; - if (Flags.isProtected(flags)) - return PHPUiImages.DESC_MISC_PROTECTED; - if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_MISC_PRIVATE; - - return PHPUiImages.DESC_MISC_DEFAULT; - } - - public static ImageDescriptor getFieldImageDescriptor( - boolean isInInterface, int flags) { - if (Flags.isPublic(flags) || isInInterface) - return PHPUiImages.DESC_FIELD_PUBLIC; - if (Flags.isProtected(flags)) - return PHPUiImages.DESC_FIELD_PROTECTED; - if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_FIELD_PRIVATE; - - return PHPUiImages.DESC_FIELD_DEFAULT; - } - - public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, - boolean isInner, int flags) { - if (isInner) { - if (isInterface) { - return getInnerInterfaceImageDescriptor(flags); - } else { - return getInnerClassImageDescriptor(flags); - } - } else { - if (isInterface) { - return getInterfaceImageDescriptor(flags); - } else { - return getClassImageDescriptor(flags); - } - } - } - - private static ImageDescriptor getClassImageDescriptor(int flags) { - if (Flags.isPublic(flags) || Flags.isProtected(flags) - || Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_CLASS; - else - return PHPUiImages.DESC_OBJS_CLASS_DEFAULT; - } - - private static ImageDescriptor getInnerClassImageDescriptor(int flags) { - if (Flags.isPublic(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PUBLIC; - else if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PRIVATE; - else if (Flags.isProtected(flags)) - return PHPUiImages.DESC_OBJS_INNER_CLASS_PROTECTED; - else - return PHPUiImages.DESC_OBJS_INNER_CLASS_DEFAULT; - } - - private static ImageDescriptor getInterfaceImageDescriptor(int flags) { - if (Flags.isPublic(flags) || Flags.isProtected(flags) - || Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INTERFACE; - else - return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; - } - - private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) { - if (Flags.isPublic(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; - else if (Flags.isPrivate(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; - else if (Flags.isProtected(flags)) - return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; - else - return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java deleted file mode 100644 index 77c29e7..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.viewsupport; - -import java.util.HashSet; - -import net.sourceforge.phpdt.internal.ui.util.SWTUtil; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.CompilationUnitAnnotationModelEvent; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IMarkerDelta; -import org.eclipse.core.resources.IProject; -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.runtime.CoreException; -import org.eclipse.jface.text.source.AnnotationModelEvent; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelListener; -import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; -//incastrix -//import org.eclipse.jface.util.ListenerList; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.swt.widgets.Display; - -/** - * Listens to resource deltas and filters for marker changes of type - * IMarker.PROBLEM Viewers showing error ticks should register as listener to - * this type. - */ -public class ProblemMarkerManager implements IResourceChangeListener, - IAnnotationModelListener, IAnnotationModelListenerExtension { - - /** - * Visitors used to look if the element change delta containes a marker - * change. - */ - private static class ProjectErrorVisitor implements IResourceDeltaVisitor { - - private HashSet fChangedElements; - - public ProjectErrorVisitor(HashSet changedElements) { - fChangedElements = changedElements; - } - - public boolean visit(IResourceDelta delta) throws CoreException { - IResource res = delta.getResource(); - if (res instanceof IProject - && delta.getKind() == IResourceDelta.CHANGED) { - try { - IProject project = (IProject) res; - if (!project.isAccessible() - || !project - .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { - // only track open Java projects - return false; - } - } catch (CoreException e) { - PHPeclipsePlugin.log(e); - return false; - } - } - checkInvalidate(delta, res); - return true; - } - - private void checkInvalidate(IResourceDelta delta, IResource resource) { - int kind = delta.getKind(); - if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED - || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { - // invalidate the resource and all parents - while (resource.getType() != IResource.ROOT - && fChangedElements.add(resource)) { - resource = resource.getParent(); - } - } - } - - private boolean isErrorDelta(IResourceDelta delta) { - if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) { - IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); - for (int i = 0; i < markerDeltas.length; i++) { - if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) { - int kind = markerDeltas[i].getKind(); - if (kind == IResourceDelta.ADDED - || kind == IResourceDelta.REMOVED) - return true; - int severity = markerDeltas[i].getAttribute( - IMarker.SEVERITY, -1); - int newSeverity = markerDeltas[i].getMarker() - .getAttribute(IMarker.SEVERITY, -1); - if (newSeverity != severity) - return true; - } - } - } - return false; - } - } - - private ListenerList fListeners; - - public ProblemMarkerManager() { - fListeners = new ListenerList(); - } - - /* - * @see IResourceChangeListener#resourceChanged - */ - public void resourceChanged(IResourceChangeEvent event) { - HashSet changedElements = new HashSet(); - - try { - IResourceDelta delta = event.getDelta(); - if (delta != null) - delta.accept(new ProjectErrorVisitor(changedElements)); - } catch (CoreException e) { - PHPeclipsePlugin.log(e.getStatus()); - } - - if (!changedElements.isEmpty()) { - IResource[] changes = (IResource[]) changedElements - .toArray(new IResource[changedElements.size()]); - fireChanges(changes, true); - } - } - - /* - * (non-Javadoc) - * - * @see IAnnotationModelListener#modelChanged(IAnnotationModel) - */ - public void modelChanged(IAnnotationModel model) { - // no action - } - - /* - * (non-Javadoc) - * - * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) - */ - public void modelChanged(AnnotationModelEvent event) { - if (event instanceof CompilationUnitAnnotationModelEvent) { - CompilationUnitAnnotationModelEvent cuEvent = (CompilationUnitAnnotationModelEvent) event; - if (cuEvent.includesProblemMarkerAnnotationChanges()) { - IResource[] changes = new IResource[] { cuEvent - .getUnderlyingResource() }; - fireChanges(changes, false); - } - } - } - - /** - * Adds a listener for problem marker changes. - */ - public void addListener(IProblemChangedListener listener) { - if (fListeners.isEmpty()) { - PHPeclipsePlugin.getWorkspace().addResourceChangeListener(this); - WebUI.getDefault().getCompilationUnitDocumentProvider() - .addGlobalAnnotationModelListener(this); - } - fListeners.add(listener); - } - - /** - * Removes a IProblemChangedListener. - */ - public void removeListener(IProblemChangedListener listener) { - fListeners.remove(listener); - if (fListeners.isEmpty()) { - PHPeclipsePlugin.getWorkspace().removeResourceChangeListener(this); - WebUI.getDefault().getCompilationUnitDocumentProvider() - .removeGlobalAnnotationModelListener(this); - } - } - - private void fireChanges(final IResource[] changes, - final boolean isMarkerChange) { - Display display = SWTUtil.getStandardDisplay(); - if (display != null && !display.isDisposed()) { - display.asyncExec(new Runnable() { - public void run() { - Object[] listeners = fListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) { - IProblemChangedListener curr = (IProblemChangedListener) listeners[i]; - curr.problemsChanged(changes, isMarkerChange); - } - } - }); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java deleted file mode 100644 index 1245765..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.wizards; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.ui.wizards.NewClassWizardPage; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; - -public class NewClassCreationWizard extends NewElementWizard { - - private NewClassWizardPage fPage; - - public NewClassCreationWizard() { - super(); - setDefaultPageImageDescriptor(PHPUiImages.DESC_WIZBAN_NEWCLASS); - setDialogSettings(WebUI.getDefault().getDialogSettings()); - setWindowTitle(NewWizardMessages - .getString("NewClassCreationWizard.title")); //$NON-NLS-1$ - } - - /* - * @see Wizard#createPages - */ - public void addPages() { - super.addPages(); - fPage = new NewClassWizardPage(); - addPage(fPage); - fPage.init(getSelection()); - } - - /* - * (non-Javadoc) - * - * @see net.sourceforge.phpdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor) - */ - protected void finishPage(IProgressMonitor monitor) - throws InterruptedException, CoreException { - fPage.createType(monitor); // use the full progress monitor - ICompilationUnit cu = JavaModelUtil.toOriginal(fPage.getCreatedType() - .getCompilationUnit()); - if (cu != null) { - IResource resource = cu.getResource(); - selectAndReveal(resource); - openResource((IFile) resource); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.wizard.IWizard#performFinish() - */ - public boolean performFinish() { - // warnAboutTypeCommentDeprecation(); - return super.performFinish(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java deleted file mode 100644 index f6f0882..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.internal.ui.wizards; - -import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.internal.ui.actions.WorkbenchRunnableAdapter; -import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; - -public abstract class NewElementWizard extends Wizard implements INewWizard { - - private IWorkbench fWorkbench; - - private IStructuredSelection fSelection; - - public NewElementWizard() { - setNeedsProgressMonitor(true); - } - - protected void openResource(final IFile resource) { - final IWorkbenchPage activePage = WebUI.getActivePage(); - if (activePage != null) { - final Display display = getShell().getDisplay(); - if (display != null) { - display.asyncExec(new Runnable() { - public void run() { - try { - IDE.openEditor(activePage, resource, true); - } catch (PartInitException e) { - PHPeclipsePlugin.log(e); - } - } - }); - } - } - } - - /** - * Subclasses should override to perform the actions of the wizard. This - * method is run in the wizard container's context as a workspace runnable. - */ - protected void finishPage(IProgressMonitor monitor) - throws InterruptedException, CoreException { - } - - protected void handleFinishException(Shell shell, - InvocationTargetException e) { - String title = NewWizardMessages - .getString("NewElementWizard.op_error.title"); //$NON-NLS-1$ - String message = NewWizardMessages - .getString("NewElementWizard.op_error.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, shell, title, message); - } - - /* - * @see Wizard#performFinish - */ - public boolean performFinish() { - IWorkspaceRunnable op = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException, - OperationCanceledException { - try { - finishPage(monitor); - } catch (InterruptedException e) { - throw new OperationCanceledException(e.getMessage()); - } - } - }; - try { - getContainer().run(false, true, new WorkbenchRunnableAdapter(op)); - } catch (InvocationTargetException e) { - handleFinishException(getShell(), e); - return false; - } catch (InterruptedException e) { - return false; - } - return true; - } - - // protected void warnAboutTypeCommentDeprecation() { - // String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED; - // if (OptionalMessageDialog.isDialogEnabled(key)) { - // Templates templates= Templates.getInstance(); - // boolean isOldWorkspace= templates.getTemplates("filecomment").length > 0 - // && templates.getTemplates("typecomment").length > 0; - // //$NON-NLS-1$ //$NON-NLS-2$ - // if (!isOldWorkspace) { - // OptionalMessageDialog.setDialogEnabled(key, false); - // } - // String title= - // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.title"); - // //$NON-NLS-1$ - // String message= - // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.message"); - // //$NON-NLS-1$ - // OptionalMessageDialog.open(key, getShell(), title, - // OptionalMessageDialog.getDefaultImage(), message, - // OptionalMessageDialog.INFORMATION, new String[] { - // IDialogConstants.OK_LABEL }, 0); - // } - // } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, - * org.eclipse.jface.viewers.IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection currentSelection) { - fWorkbench = workbench; - fSelection = currentSelection; - } - - public IStructuredSelection getSelection() { - return fSelection; - } - - public IWorkbench getWorkbench() { - return fWorkbench; - } - - protected void selectAndReveal(IResource newResource) { - BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench - .getActiveWorkbenchWindow()); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java deleted file mode 100644 index 97b2ef2..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright (c) 2005 by Leif Frenzel. All rights reserved. -// See http://leiffrenzel.de -// modified for phpeclipse.de project by axelcl -package net.sourceforge.phpdt.ltk.ui.actions; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.core.SourceMethod; -import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; -import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; -import net.sourceforge.phpdt.ltk.core.RenameIdentifierRefactoring; -import net.sourceforge.phpdt.ltk.core.RenameLocalVariableDelegate; -import net.sourceforge.phpdt.ltk.core.RenamePHPProcessor; -import net.sourceforge.phpdt.ltk.ui.UITexts; -import net.sourceforge.phpdt.ltk.ui.wizards.RenameLocalVariableWizard; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; -import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.texteditor.ITextEditor; - -public class RenameLocalVariable implements IEditorActionDelegate { - - private ISelection selection; - - private IEditorPart targetEditor; - - private boolean onPHPFile; - - private RenameIdentifierInfo info = new RenameIdentifierInfo(); - - public void setActiveEditor(final IAction action, - final IEditorPart targetEditor) { - this.targetEditor = targetEditor; - onPHPFile = false; - IFile file = getFile(); - - if (file != null && PHPFileUtil.isPHPFile(file)) { - onPHPFile = true; - } - } - - public void run(final IAction action) { - if (!onPHPFile) { - refuse(); - } else { - if (selection != null && selection instanceof ITextSelection) { - String word = null; - Point point = null; - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - PHPEditor editor = (PHPEditor) targetEditor; - if (editor != null) { - ITextSelection textSelection = (ITextSelection) editor - .getSelectionProvider().getSelection(); - IDocument doc = editor.getDocumentProvider() - .getDocument(editor.getEditorInput()); - int pos = textSelection.getOffset(); - point = PHPWordExtractor.findWord(doc, pos); - if (point != null) { - try { - word = doc.get(point.x, point.y); - IWorkingCopyManager manager = WebUI - .getDefault().getWorkingCopyManager(); - ICompilationUnit unit = manager - .getWorkingCopy(editor.getEditorInput()); - SourceMethod method = (SourceMethod) findEnclosingElement( - point.x, unit, IJavaElement.METHOD); - if (word == null || word.charAt(0) != '$' - || method == null - || !(method instanceof SourceMethod)) { - refuseLocalVariable(); - } else { - applySelection((ITextSelection) selection, - word, point, method); - if (saveAll()) { - openWizard(); - } - } - } catch (BadLocationException e) { - } - } - } - } - } - } - } - - /** - * Returns the enclosing element of a particular element type, - * null if no enclosing element of that type exists. - */ - public IJavaElement findEnclosingElement(int start, ICompilationUnit cu, - int elementType) { - if (cu == null) - return null; - - try { - IJavaElement element = cu.getElementAt(start); - if (element == null) { - element = cu; - } - - return element.getAncestor(elementType); - - } catch (JavaModelException e) { - return null; - } - } - - public void selectionChanged(final IAction action, - final ISelection selection) { - this.selection = selection; - } - - // helping methods - // //////////////// - - private void applySelection(final ITextSelection textSelection, - String word, Point point, SourceMethod method) { - if (word != null) { - info.setOldName(word); - info.setNewName(word); - info.setOffset(point.x); - } else { - info.setOldName(textSelection.getText()); - info.setNewName(textSelection.getText()); - info.setOffset(textSelection.getOffset()); - } - info.setMethod(method); - info.setSourceFile(getFile()); - } - - private void refuseLocalVariable() { - String title = UITexts.renameLocalVariable_refuseDlg_title; - String message = UITexts.renameLocalVariable_refuseDlg_message; - MessageDialog.openInformation(getShell(), title, message); - } - - private void refuse() { - String title = UITexts.renameProperty_refuseDlg_title; - String message = UITexts.renameProperty_refuseDlg_message; - MessageDialog.openInformation(getShell(), title, message); - } - - private static boolean saveAll() { - IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - return IDE.saveAllEditors(new IResource[] { workspaceRoot }, false); - } - - private void openWizard() { - RenameLocalVariableDelegate delegate = new RenameLocalVariableDelegate( - info); - RefactoringProcessor processor = new RenamePHPProcessor(info, delegate); - RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring( - processor); - RenameLocalVariableWizard wizard = new RenameLocalVariableWizard(ref, - info); - RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation( - wizard); - try { - String titleForFailedChecks = ""; //$NON-NLS-1$ - op.run(getShell(), titleForFailedChecks); - } catch (final InterruptedException irex) { - // operation was cancelled - } - } - - private Shell getShell() { - Shell result = null; - if (targetEditor != null) { - result = targetEditor.getSite().getShell(); - } else { - result = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - } - return result; - } - - private final IFile getFile() { - IFile result = null; - if (targetEditor instanceof ITextEditor) { - ITextEditor editor = (ITextEditor) targetEditor; - IEditorInput input = editor.getEditorInput(); - if (input instanceof IFileEditorInput) { - result = ((IFileEditorInput) input).getFile(); - } - } - return result; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java deleted file mode 100644 index 600dd68..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) 2005 by Leif Frenzel. All rights reserved. -// See http://leiffrenzel.de -package net.sourceforge.phpdt.ltk.ui.wizards; - -import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; -import net.sourceforge.phpdt.ltk.ui.UITexts; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.ltk.ui.refactoring.UserInputWizardPage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -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.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; - -/** - *

- * the input page for the Rename Property refactoring, where users can control - * the effects of the refactoring; to be shown in the wizard. - *

- * - *

- * We let the user enter the new name for the property, and we let her decide - * whether other property files in the bundle should be affected, and whether - * the operation is supposed to span the entire workspace or only the current - * project. - *

- * - */ -public class RenameIdentifierPage extends UserInputWizardPage { - - private static final String DS_KEY = RenameIdentifierPage.class.getName(); - - private static final String DS_UPDATE_BUNDLE = "UPDATE_BUNDLE"; //$NON-NLS-1$ - - private static final String DS_ALL_PROJECTS = "ALL_PROJECTS"; //$NON-NLS-1$ - - private final RenameIdentifierInfo info; - - private IDialogSettings dialogSettings; - - private Text txtNewName; - - private Button cbUpdateBundle; - - private Button cbAllProjects; - - public RenameIdentifierPage(final RenameIdentifierInfo info) { - super(RenameIdentifierPage.class.getName()); - this.info = info; - initDialogSettings(); - } - - // interface methods of UserInputWizardPage - // ///////////////////////////////////////// - - public void createControl(final Composite parent) { - Composite composite = createRootComposite(parent); - setControl(composite); - - createLblNewName(composite); - createTxtNewName(composite); - createCbUpdateBundle(composite); - createCbAllProjects(composite); - - validate(); - } - - // UI creation methods - // //////////////////// - - private Composite createRootComposite(final Composite parent) { - Composite result = new Composite(parent, SWT.NONE); - GridLayout gridLayout = new GridLayout(2, false); - gridLayout.marginWidth = 10; - gridLayout.marginHeight = 10; - result.setLayout(gridLayout); - initializeDialogUnits(result); - Dialog.applyDialogFont(result); - return result; - } - - private void createLblNewName(final Composite composite) { - Label lblNewName = new Label(composite, SWT.NONE); - lblNewName.setText(UITexts.renamePropertyInputPage_lblNewName); - } - - private void createTxtNewName(Composite composite) { - txtNewName = new Text(composite, SWT.BORDER); - txtNewName.setText(info.getOldName()); - txtNewName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - txtNewName.selectAll(); - txtNewName.addKeyListener(new KeyAdapter() { - public void keyReleased(final KeyEvent e) { - info.setNewName(txtNewName.getText()); - validate(); - } - }); - } - - private void createCbUpdateBundle(final Composite composite) { - String texts = UITexts.renamePropertyInputPage_cbUpdateBundle; - cbUpdateBundle = createCheckbox(composite, texts); - cbUpdateBundle.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(final SelectionEvent event) { - boolean selected = cbUpdateBundle.getSelection(); - dialogSettings.put(DS_UPDATE_BUNDLE, selected); - info.setUpdateProject(selected); - } - }); - initUpdateBundleOption(); - } - - private void createCbAllProjects(final Composite composite) { - String text = UITexts.renamePropertyInputPage_cbAllProjects; - cbAllProjects = createCheckbox(composite, text); - cbAllProjects.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(final SelectionEvent event) { - boolean selected = cbAllProjects.getSelection(); - dialogSettings.put(DS_ALL_PROJECTS, selected); - info.setAllProjects(selected); - // for demonstration purposes, we enforce the preview for - // refactorings - // that span the entire workspace - getRefactoringWizard().setForcePreviewReview(selected); - } - }); - initAllProjectsOption(); - } - - private Button createCheckbox(final Composite composite, final String text) { - Button result = new Button(composite, SWT.CHECK); - result.setText(text); - - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - gridData.horizontalSpan = 2; - result.setLayoutData(gridData); - - return result; - } - - // helping methods - // //////////////// - - private void initDialogSettings() { - IDialogSettings ds = WebUI.getDefault().getDialogSettings(); - dialogSettings = ds.getSection(DS_KEY); - if (dialogSettings == null) { - dialogSettings = ds.addNewSection(DS_KEY); - // init default values - dialogSettings.put(DS_UPDATE_BUNDLE, true); - dialogSettings.put(DS_ALL_PROJECTS, false); - } - } - - private void validate() { - String txt = txtNewName.getText(); - setPageComplete(txt.length() > 0 && !txt.equals(info.getOldName())); - } - - private void initUpdateBundleOption() { - boolean updateRefs = dialogSettings.getBoolean(DS_UPDATE_BUNDLE); - cbUpdateBundle.setSelection(updateRefs); - info.setUpdateProject(updateRefs); - } - - private void initAllProjectsOption() { - boolean allProjects = dialogSettings.getBoolean(DS_ALL_PROJECTS); - cbAllProjects.setSelection(allProjects); - info.setAllProjects(allProjects); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java deleted file mode 100644 index c1b741f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) 2005 by Leif Frenzel. All rights reserved. -// See http://leiffrenzel.de -package net.sourceforge.phpdt.ltk.ui.wizards; - -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; -import net.sourceforge.phpdt.ltk.ui.UITexts; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.ltk.ui.refactoring.UserInputWizardPage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -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.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; - -/** - *

- * the input page for the Rename Property refactoring, where users can control - * the effects of the refactoring; to be shown in the wizard. - *

- * - *

- * We let the user enter the new name for the property, and we let her decide - * whether other property files in the bundle should be affected, and whether - * the operation is supposed to span the entire workspace or only the current - * project. - *

- * - */ -public class RenameLocalVariablePage extends UserInputWizardPage { - - private static final String DS_KEY = RenameLocalVariablePage.class - .getName(); - - private static final String DS_RENAME_DQ_STRINGS = "RENAME_DQ_STRINGS"; //$NON-NLS-1$ - - private static final String DS_RENAME_PHPDOC = "RENAME_PHPDOC"; //$NON-NLS-1$ - - private static final String DS_RENAME_OTHER_COMMENTS = "RENAME_OTHER_COMMENTS"; //$NON-NLS-1$ - - private final RenameIdentifierInfo info; - - private IDialogSettings dialogSettings; - - private Text txtNewName; - - private Button cbRenameDQStrings; - - private Button cbRenamePHPdoc; - - private Button cbRenameOtherComments; - - public RenameLocalVariablePage(final RenameIdentifierInfo info) { - super(RenameLocalVariablePage.class.getName()); - this.info = info; - initDialogSettings(); - } - - public void createControl(final Composite parent) { - Composite composite = createRootComposite(parent); - setControl(composite); - - createLblNewName(composite); - createTxtNewName(composite); - createCbDQStrings(composite); - createCbPHPdoc(composite); - createCbOtherComments(composite); - - validate(); - - // TODO check if we can leave this step out in the future - getRefactoringWizard().setForcePreviewReview(true); - } - - private Composite createRootComposite(final Composite parent) { - Composite result = new Composite(parent, SWT.NONE); - GridLayout gridLayout = new GridLayout(2, false); - gridLayout.marginWidth = 10; - gridLayout.marginHeight = 10; - result.setLayout(gridLayout); - initializeDialogUnits(result); - Dialog.applyDialogFont(result); - return result; - } - - private void createLblNewName(final Composite composite) { - Label lblNewName = new Label(composite, SWT.NONE); - lblNewName.setText(UITexts.renamePropertyInputPage_lblNewName); - } - - private void createTxtNewName(Composite composite) { - txtNewName = new Text(composite, SWT.BORDER); - txtNewName.setText(info.getOldName()); - txtNewName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - txtNewName.selectAll(); - txtNewName.addKeyListener(new KeyAdapter() { - public void keyReleased(final KeyEvent e) { - info.setNewName(txtNewName.getText()); - validate(); - } - }); - } - - private void createCbDQStrings(final Composite composite) { - String texts = UITexts.renameLocalVariable_cbDQStrings; - cbRenameDQStrings = createCheckbox(composite, texts); - cbRenameDQStrings.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(final SelectionEvent event) { - boolean selected = cbRenameDQStrings.getSelection(); - dialogSettings.put(DS_RENAME_DQ_STRINGS, selected); - info.setRenameDQString(selected); - } - }); - initDQStringsOption(); - } - - private void createCbPHPdoc(final Composite composite) { - String texts = UITexts.renameLocalVariable_cbPHPdoc; - cbRenamePHPdoc = createCheckbox(composite, texts); - cbRenamePHPdoc.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(final SelectionEvent event) { - boolean selected = cbRenamePHPdoc.getSelection(); - dialogSettings.put(DS_RENAME_PHPDOC, selected); - info.setRenamePHPdoc(selected); - } - }); - initPHPdocOption(); - } - - private void createCbOtherComments(final Composite composite) { - String texts = UITexts.renameLocalVariable_cbOtherDoc; - cbRenameOtherComments = createCheckbox(composite, texts); - cbRenameOtherComments.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(final SelectionEvent event) { - boolean selected = cbRenameOtherComments.getSelection(); - dialogSettings.put(DS_RENAME_OTHER_COMMENTS, selected); - info.setRenameOtherComments(selected); - } - }); - initOtherCommentsOption(); - } - - private Button createCheckbox(final Composite composite, final String text) { - Button result = new Button(composite, SWT.CHECK); - result.setText(text); - - GridData gridData = new GridData(GridData.FILL_HORIZONTAL); - gridData.horizontalSpan = 2; - result.setLayoutData(gridData); - - return result; - } - - private void initDialogSettings() { - IDialogSettings ds = WebUI.getDefault().getDialogSettings(); - dialogSettings = ds.getSection(DS_KEY); - if (dialogSettings == null) { - dialogSettings = ds.addNewSection(DS_KEY); - // init default values - dialogSettings.put(DS_RENAME_DQ_STRINGS, true); - dialogSettings.put(DS_RENAME_PHPDOC, true); - dialogSettings.put(DS_RENAME_OTHER_COMMENTS, true); - } - } - - private static boolean isVariable(String txt) { - if (txt.length() <= 1) { - return false; - } - if (txt.charAt(0) != '$') { - return false; - } - for (int i = 1; i < txt.length(); i++) { - if (!Scanner.isPHPIdentifierPart(txt.charAt(i))) { - return false; - } - } - return true; - } - - private void validate() { - String txt = txtNewName.getText(); - //Scanner s; - setPageComplete(isVariable(txt) && !txt.equals(info.getOldName())); - } - - private void initDQStringsOption() { - boolean refs = dialogSettings.getBoolean(DS_RENAME_DQ_STRINGS); - cbRenameDQStrings.setSelection(refs); - info.setRenameDQString(refs); - } - - private void initPHPdocOption() { - boolean refs = dialogSettings.getBoolean(DS_RENAME_PHPDOC); - cbRenamePHPdoc.setSelection(refs); - info.setRenamePHPdoc(refs); - } - - private void initOtherCommentsOption() { - boolean refs = dialogSettings.getBoolean(DS_RENAME_OTHER_COMMENTS); - cbRenameOtherComments.setSelection(refs); - info.setRenameOtherComments(refs); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementSorter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementSorter.java deleted file mode 100644 index f9476e1..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementSorter.java +++ /dev/null @@ -1,353 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui; - -import java.text.Collator; - -import net.sourceforge.phpdt.core.Flags; -import net.sourceforge.phpdt.core.IField; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IMethod; -import net.sourceforge.phpdt.core.IPackageFragment; -import net.sourceforge.phpdt.core.IPackageFragmentRoot; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.core.Signature; -import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; -import net.sourceforge.phpdt.internal.corext.util.JdtFlags; -import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.viewers.ContentViewer; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.ui.model.IWorkbenchAdapter; - -/** - * Sorter for Java elements. Ordered by element category, then by element name. - * Package fragment roots are sorted as ordered on the classpath. - * - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * @since 2.0 - */ -public class JavaElementSorter extends ViewerSorter { - - private static final int PROJECTS = 1; - - private static final int PACKAGEFRAGMENTROOTS = 2; - - private static final int PACKAGEFRAGMENT = 3; - - private static final int COMPILATIONUNITS = 4; - - private static final int CLASSFILES = 5; - - private static final int RESOURCEFOLDERS = 7; - - private static final int RESOURCES = 8; - - private static final int STORAGE = 9; - - private static final int PACKAGE_DECL = 10; - - private static final int IMPORT_CONTAINER = 11; - - private static final int IMPORT_DECLARATION = 12; - - // Includes all categories ordered using the OutlineSortOrderPage: - // types, initializers, methods & fields - private static final int MEMBERSOFFSET = 15; - - private static final int JAVAELEMENTS = 50; - - private static final int OTHERS = 51; - - private MembersOrderPreferenceCache fMemberOrderCache; - - /** - * Constructor. - */ - public JavaElementSorter() { - super(null); // delay initialization of collator - fMemberOrderCache = WebUI.getDefault() - .getMemberOrderPreferenceCache(); - } - - /** - * @deprecated Bug 22518. Method never used: does not override - * ViewerSorter#isSorterProperty(Object, String). Method could - * be removed, but kept for API compatibility. - */ -// public boolean isSorterProperty(Object element, Object property) { -// return true; -// } - - /* - * @see ViewerSorter#category - */ - public int category(Object element) { - if (element instanceof IJavaElement) { - try { - IJavaElement je = (IJavaElement) element; - - switch (je.getElementType()) { - case IJavaElement.METHOD: { - IMethod method = (IMethod) je; - if (method.isConstructor()) { - return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); - } - int flags = method.getFlags(); - if (Flags.isStatic(flags)) - return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX); - else - return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); - } - case IJavaElement.FIELD: { - int flags = ((IField) je).getFlags(); - if (Flags.isStatic(flags)) - return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX); - else - return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); - } - // case IJavaElement.INITIALIZER : - // { - // int flags= ((IInitializer) je).getFlags(); - // if (Flags.isStatic(flags)) - // return - // getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); - // else - // return - // getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); - // } - case IJavaElement.TYPE: - return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); - case IJavaElement.PACKAGE_DECLARATION: - return PACKAGE_DECL; - case IJavaElement.IMPORT_CONTAINER: - return IMPORT_CONTAINER; - case IJavaElement.IMPORT_DECLARATION: - return IMPORT_DECLARATION; - case IJavaElement.PACKAGE_FRAGMENT: - IPackageFragment pack = (IPackageFragment) je; - if (pack.getParent().getResource() instanceof IProject) { - return PACKAGEFRAGMENTROOTS; - } - return PACKAGEFRAGMENT; - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - return PACKAGEFRAGMENTROOTS; - case IJavaElement.JAVA_PROJECT: - return PROJECTS; - case IJavaElement.CLASS_FILE: - return CLASSFILES; - case IJavaElement.COMPILATION_UNIT: - return COMPILATIONUNITS; - } - - } catch (JavaModelException e) { - if (!e.isDoesNotExist()) - PHPeclipsePlugin.log(e); - } - return JAVAELEMENTS; - } else if (element instanceof IFile) { - return RESOURCES; - } else if (element instanceof IProject) { - return PROJECTS; - } else if (element instanceof IContainer) { - return RESOURCEFOLDERS; - } else if (element instanceof IStorage) { - return STORAGE; - } - // else if (element instanceof ClassPathContainer) { - // return PACKAGEFRAGMENTROOTS; - // } - return OTHERS; - } - - private int getMemberCategory(int kind) { - int offset = fMemberOrderCache.getCategoryIndex(kind); - return offset + MEMBERSOFFSET; - } - - /* - * @see ViewerSorter#compare - */ - public int compare(Viewer viewer, Object e1, Object e2) { - int cat1 = category(e1); - int cat2 = category(e2); - - if (cat1 != cat2) - return cat1 - cat2; - - if (cat1 == PROJECTS) { - IWorkbenchAdapter a1 = (IWorkbenchAdapter) ((IAdaptable) e1) - .getAdapter(IWorkbenchAdapter.class); - IWorkbenchAdapter a2 = (IWorkbenchAdapter) ((IAdaptable) e2) - .getAdapter(IWorkbenchAdapter.class); - return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2)); - } - - if (cat1 == PACKAGEFRAGMENTROOTS) { - IPackageFragmentRoot root1 = getPackageFragmentRoot(e1); - IPackageFragmentRoot root2 = getPackageFragmentRoot(e2); - if (root1 == null) { - if (root2 == null) { - return 0; - } else { - return 1; - } - } else if (root2 == null) { - return -1; - } - if (!root1.getPath().equals(root2.getPath())) { - int p1 = getClassPathIndex(root1); - int p2 = getClassPathIndex(root2); - if (p1 != p2) { - return p1 - p2; - } - } - e1 = root1; // normalize classpath container to root - e2 = root2; - } - // non - java resources are sorted using the label from the viewers - // label provider - if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS - || cat1 == STORAGE || cat1 == OTHERS) { - return compareWithLabelProvider(viewer, e1, e2); - } - - if (e1 instanceof IMember) { - if (fMemberOrderCache.isSortByVisibility()) { - try { - int flags1 = JdtFlags.getVisibilityCode((IMember) e1); - int flags2 = JdtFlags.getVisibilityCode((IMember) e2); - int vis = fMemberOrderCache.getVisibilityIndex(flags1) - - fMemberOrderCache.getVisibilityIndex(flags2); - if (vis != 0) { - return vis; - } - } catch (JavaModelException ignore) { - } - } - } - - String name1 = ((IJavaElement) e1).getElementName(); - String name2 = ((IJavaElement) e2).getElementName(); - - if (e1 instanceof IType) { // handle anonymous types - if (name1.length() == 0) { - if (name2.length() == 0) { - try { - return getCollator().compare( - ((IType) e1).getSuperclassName(), - ((IType) e2).getSuperclassName()); - } catch (JavaModelException e) { - return 0; - } - } else { - return 1; - } - } else if (name2.length() == 0) { - return -1; - } - } - - int cmp = getCollator().compare(name1, name2); - if (cmp != 0) { - return cmp; - } - - if (e1 instanceof IMethod) { - String[] params1 = ((IMethod) e1).getParameterTypes(); - String[] params2 = ((IMethod) e2).getParameterTypes(); - int len = Math.min(params1.length, params2.length); - for (int i = 0; i < len; i++) { - cmp = getCollator().compare(Signature.toString(params1[i]), - Signature.toString(params2[i])); - if (cmp != 0) { - return cmp; - } - } - return params1.length - params2.length; - } - return 0; - } - - private IPackageFragmentRoot getPackageFragmentRoot(Object element) { - // if (element instanceof ClassPathContainer) { - // // return first package fragment root from the container - // ClassPathContainer cp= (ClassPathContainer)element; - // Object[] roots= cp.getPackageFragmentRoots(); - // if (roots.length > 0) - // return (IPackageFragmentRoot)roots[0]; - // // non resolvable - return null - // return null; - // } - return JavaModelUtil.getPackageFragmentRoot((IJavaElement) element); - } - - private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) { - if (viewer == null || !(viewer instanceof ContentViewer)) { - IBaseLabelProvider prov = ((ContentViewer) viewer) - .getLabelProvider(); - if (prov instanceof ILabelProvider) { - ILabelProvider lprov = (ILabelProvider) prov; - String name1 = lprov.getText(e1); - String name2 = lprov.getText(e2); - if (name1 != null && name2 != null) { - return getCollator().compare(name1, name2); - } - } - } - return 0; // can't compare - } - - private int getClassPathIndex(IPackageFragmentRoot root) { - try { - IPath rootPath = root.getPath(); - IPackageFragmentRoot[] roots = root.getJavaProject() - .getPackageFragmentRoots(); - for (int i = 0; i < roots.length; i++) { - if (roots[i].getPath().equals(rootPath)) { - return i; - } - } - } catch (JavaModelException e) { - } - - return Integer.MAX_VALUE; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ViewerSorter#getCollator() - */ - public final Collator getCollator() { - if (collator == null) { - collator = Collator.getInstance(); - } - return collator; - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaUI.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaUI.java deleted file mode 100644 index e4f597c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaUI.java +++ /dev/null @@ -1,809 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui; - -import net.sourceforge.phpdt.core.IBufferFactory; -//import net.sourceforge.phpdt.core.IJavaElement; -//import net.sourceforge.phpdt.core.IWorkingCopy; -//import net.sourceforge.phpdt.core.JavaCore; -//import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.phpeditor.EditorUtility; -//import net.sourceforge.phpeclipse.ui.WebUI; - -//import org.eclipse.ui.IEditorPart; -//import org.eclipse.ui.ISharedImages; -//import org.eclipse.ui.PartInitException; -//import org.eclipse.ui.internal.SharedImages; -//import org.eclipse.ui.texteditor.IDocumentProvider; - -/** - * Central access point for the Java UI plug-in (id - * "net.sourceforge.phpdt.ui"). This class provides static - * methods for: - *
    - *
  • creating various kinds of selection dialogs to present a collection of - * Java elements to the user and let them make a selection.
  • - *
  • opening a Java editor on a compilation unit.
  • - *
- *

- * This class provides static methods and fields only; it is not intended to be - * instantiated or subclassed by clients. - *

- */ -public final class JavaUI { - -// private static ISharedImages fgSharedImages = null; - - private JavaUI() { - // prevent instantiation of JavaUI. - } - - /** - * The id of the Java plugin (value "net.sourceforge.phpdt.ui"). - */ - // public static final String ID_PLUGIN= "net.sourceforge.phpdt.ui"; - // //$NON-NLS-1$ - /** - * The id of the Java perspective (value - * "net.sourceforge.phpdt.ui.JavaPerspective"). - */ - public static final String ID_PERSPECTIVE= - "net.sourceforge.phpdt.ui.JavaPerspective"; //$NON-NLS-1$ - /** - * The id of the Java hierarchy perspective (value - * "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"). - */ - // public static final String ID_HIERARCHYPERSPECTIVE= - // "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ - /** - * The id of the Java action set (value - * "net.sourceforge.phpdt.ui.JavaActionSet"). - */ - // public static final String ID_ACTION_SET= - // "net.sourceforge.phpdt.ui.JavaActionSet"; //$NON-NLS-1$ - /** - * The id of the Java Element Creation action set (value - * "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"). - * - * @since 2.0 - */ - // public static final String ID_ELEMENT_CREATION_ACTION_SET= - // "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ - /** - * The id of the Java Coding action set (value - * "net.sourceforge.phpdt.ui.CodingActionSet"). - * - * @since 2.0 - */ - // public static final String ID_CODING_ACTION_SET= - // "net.sourceforge.phpdt.ui.CodingActionSet"; //$NON-NLS-1$ - /** - * The id of the Java action set for open actions (value - * "net.sourceforge.phpdt.ui.A_OpenActionSet"). - * - * @since 2.0 - */ - // public static final String ID_OPEN_ACTION_SET= - // "net.sourceforge.phpdt.ui.A_OpenActionSet"; //$NON-NLS-1$ - /** - * The id of the Java Search action set (value - * net.sourceforge.phpdt.ui.SearchActionSet"). - * - * @since 2.0 - */ - // public static final String ID_SEARCH_ACTION_SET= - // "net.sourceforge.phpdt.ui.SearchActionSet"; //$NON-NLS-1$ - /** - * The editor part id of the editor that presents Java compilation units - * (value "net.sourceforge.phpdt.ui.CompilationUnitEditor"). - */ - // public static final String ID_CU_EDITOR= - // "net.sourceforge.phpdt.ui.PHPUnitEditor"; //$NON-NLS-1$ - /** - * The editor part id of the editor that presents Java binary class files - * (value "net.sourceforge.phpdt.ui.ClassFileEditor"). - */ - // public static final String ID_CF_EDITOR= - // "net.sourceforge.phpdt.ui.ClassFileEditor"; //$NON-NLS-1$ - /** - * The editor part id of the code snippet editor (value - * "net.sourceforge.phpdt.ui.SnippetEditor"). - */ - // public static final String ID_SNIPPET_EDITOR= - // "net.sourceforge.phpdt.ui.SnippetEditor"; //$NON-NLS-1$ - /** - * The view part id of the Packages view (value - * "net.sourceforge.phpdt.ui.PackageExplorer"). - *

- * When this id is used to access a view part with - * IWorkbenchPage.findView or showView, the - * returned IViewPart can be safely cast to an - * IPackagesViewPart. - *

- * - * @see IPackagesViewPart - * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) - * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) - */ - public static final String ID_PACKAGES = "net.sourceforge.phpdt.ui.PackageExplorer"; //$NON-NLS-1$ - - /** - * The view part id of the type hierarchy part. (value - * "net.sourceforge.phpdt.ui.TypeHierarchy"). - *

- * When this id is used to access a view part with - * IWorkbenchPage.findView or showView, the - * returned IViewPart can be safely cast to an - * ITypeHierarchyViewPart. - *

- * - * @see ITypeHierarchyViewPart - * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) - * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) - */ - public static final String ID_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.TypeHierarchy"; //$NON-NLS-1$ - - /** - * The id of the Java Browsing Perspective (value - * "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"). - * - * @since 2.0 - */ - // public static String ID_BROWSING_PERSPECTIVE= - // "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ - /** - * The view part id of the Java Browsing Projects view (value - * "net.sourceforge.phpdt.ui.ProjectsView"). - * - * @since 2.0 - */ - // public static String ID_PROJECTS_VIEW= - // "net.sourceforge.phpdt.ui.ProjectsView"; //$NON-NLS-1$ - /** - * The view part id of the Java Browsing Packages view (value - * "net.sourceforge.phpdt.ui.PackagesView"). - * - * @since 2.0 - */ - // public static String ID_PACKAGES_VIEW= - // "net.sourceforge.phpdt.ui.PackagesView"; //$NON-NLS-1$ - /** - * The view part id of the Java Browsing Types view (value - * "net.sourceforge.phpdt.ui.TypesView"). - * - * @since 2.0 - */ - // public static String ID_TYPES_VIEW= "net.sourceforge.phpdt.ui.TypesView"; - // //$NON-NLS-1$ - /** - * The view part id of the Java Browsing Members view (value - * "net.sourceforge.phpdt.ui.MembersView"). - * - * @since 2.0 - */ - // public static String ID_MEMBERS_VIEW= - // "net.sourceforge.phpdt.ui.MembersView"; //$NON-NLS-1$ - /** - * The class org.eclipse.debug.core.model.IProcess allows attaching String - * properties to processes. The Java UI contributes a property page for - * IProcess that will show the contents of the property with this key. The - * intent of this property is to show the command line a process was - * launched with. - * - * @deprecated - */ - // public final static String ATTR_CMDLINE= - // "net.sourceforge.phpdt.ui.launcher.cmdLine"; //$NON-NLS-1$ - /** - * Returns the shared images for the Java UI. - * - * @return the shared images manager - */ -// public static ISharedImages getSharedImages() { -// if (fgSharedImages == null) -// fgSharedImages = new SharedImages(); -// -// return fgSharedImages; -// } - - /** - * Creates a selection dialog that lists all packages of the given Java - * project. The caller is responsible for opening the dialog with - * Window.open, and subsequently extracting the selected - * package (of type IPackageFragment) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param project - * the Java project - * @param style - * flags defining the style of the dialog; the valid flags are: - * IJavaElementSearchConstants.CONSIDER_BINARIES, - * indicating that packages from binary package fragment roots - * should be included in addition to those from source package - * fragment roots; - * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, - * indicating that packages from required projects should be - * included as well. - * @param filter - * the initial pattern to filter the set of packages. For example - * "com" shows all packages starting with "com". The meta - * character '?' representing any character and '*' representing - * any string are supported. Clients can pass an empty string if - * no filtering is required. - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - * - * @since 2.0 - */ - // public static SelectionDialog createPackageDialog(Shell parent, - // IJavaProject project, int style, String filter) throws JavaModelException - // { - // Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | - // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == - // (IJavaElementSearchConstants.CONSIDER_BINARIES | - // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); - // - // IPackageFragmentRoot[] roots= null; - // if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != - // 0) { - // roots= project.getAllPackageFragmentRoots(); - // } else { - // roots= project.getPackageFragmentRoots(); - // } - // - // List consideredRoots= null; - // if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { - // consideredRoots= Arrays.asList(roots); - // } else { - // consideredRoots= new ArrayList(roots.length); - // for (int i= 0; i < roots.length; i++) { - // IPackageFragmentRoot root= roots[i]; - // if (root.getKind() != IPackageFragmentRoot.K_BINARY) - // consideredRoots.add(root); - // - // } - // } - // - // int flags= JavaElementLabelProvider.SHOW_DEFAULT; - // if (consideredRoots.size() > 1) - // flags= flags | JavaElementLabelProvider.SHOW_ROOT; - // - // List packages= new ArrayList(); - // Iterator iter= consideredRoots.iterator(); - // while(iter.hasNext()) { - // IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); - // packages.addAll(Arrays.asList(root.getChildren())); - // } - // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, - // new JavaElementLabelProvider(flags)); - // dialog.setIgnoreCase(false); - // dialog.setElements(packages.toArray()); // XXX inefficient - // dialog.setFilter(filter); - // return dialog; - // } - /** - * Creates a selection dialog that lists all packages of the given Java - * project. The caller is responsible for opening the dialog with - * Window.open, and subsequently extracting the selected - * package (of type IPackageFragment) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param project - * the Java project - * @param style - * flags defining the style of the dialog; the valid flags are: - * IJavaElementSearchConstants.CONSIDER_BINARIES, - * indicating that packages from binary package fragment roots - * should be included in addition to those from source package - * fragment roots; - * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, - * indicating that packages from required projects should be - * included as well. - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - */ - // public static SelectionDialog createPackageDialog(Shell parent, - // IJavaProject project, int style) throws JavaModelException { - // return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$ - // } - /** - * Creates a selection dialog that lists all packages under the given - * package fragment root. The caller is responsible for opening the dialog - * with Window.open, and subsequently extracting the - * selected package (of type IPackageFragment) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param root - * the package fragment root - * @param filter - * the initial pattern to filter the set of packages. For example - * "com" shows all packages starting with "com". The meta - * character '?' representing any character and '*' representing - * any string are supported. Clients can pass an empty string if - * no filtering is required. - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - * - * @since 2.0 - */ - // public static SelectionDialog createPackageDialog(Shell parent, - // IPackageFragmentRoot root, String filter) throws JavaModelException { - // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, - // new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); - // dialog.setIgnoreCase(false); - // dialog.setElements(root.getChildren()); - // dialog.setFilter(filter); - // return dialog; - // } - /** - * Creates a selection dialog that lists all packages under the given - * package fragment root. The caller is responsible for opening the dialog - * with Window.open, and subsequently extracting the - * selected package (of type IPackageFragment) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param root - * the package fragment root - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - */ - // public static SelectionDialog createPackageDialog(Shell parent, - // IPackageFragmentRoot root) throws JavaModelException { - // return createPackageDialog(parent, root, ""); //$NON-NLS-1$ - // } - /** - * Creates a selection dialog that lists all types in the given scope. The - * caller is responsible for opening the dialog with - * Window.open, and subsequently extracting the selected - * type(s) (of type IType) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param context - * the runnable context used to show progress when the dialog is - * being populated - * @param scope - * the scope that limits which types are included - * @param style - * flags defining the style of the dialog; the only valid values - * are IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection - * true if multiple selection is allowed - * @param filter - * the initial pattern to filter the set of types. For example - * "Abstract" shows all types starting with "abstract". The meta - * character '?' representing any character and '*' representing - * any string are supported. Clients can pass an empty string if - * no filtering is required. - * @exception JavaModelException - * if the selection dialog could not be opened - * - * @since 2.0 - */ - // public static SelectionDialog createTypeDialog(Shell parent, - // IRunnableContext context, IJavaSearchScope scope, int style, boolean - // multipleSelection, String filter) throws JavaModelException { - // int elementKinds= 0; - // if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { - // elementKinds= IJavaSearchConstants.TYPE; - // } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { - // elementKinds= IJavaSearchConstants.INTERFACE; - // } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { - // elementKinds= IJavaSearchConstants.CLASS; - // } else { - // Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ - // } - // if (multipleSelection) { - // MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, - // context, elementKinds, scope); - // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); - // //$NON-NLS-1$ - // dialog.setFilter(filter); - // return dialog; - // } else { - // TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, - // elementKinds, scope); - // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); - // //$NON-NLS-1$ - // dialog.setFilter(filter); - // return dialog; - // } - // } - /** - * Creates a selection dialog that lists all types in the given scope. The - * caller is responsible for opening the dialog with - * Window.open, and subsequently extracting the selected - * type(s) (of type IType) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param context - * the runnable context used to show progress when the dialog is - * being populated - * @param scope - * the scope that limits which types are included - * @param style - * flags defining the style of the dialog; the only valid values - * are IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection - * true if multiple selection is allowed - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - */ - // public static SelectionDialog createTypeDialog(Shell parent, - // IRunnableContext context, IJavaSearchScope scope, int style, boolean - // multipleSelection) throws JavaModelException { - // return createTypeDialog(parent, context, scope, style, multipleSelection, - // "");//$NON-NLS-1$ - // } - /** - * Creates a selection dialog that lists all types in the given scope - * containing a standard main method. The caller is - * responsible for opening the dialog with Window.open, and - * subsequently extracting the selected type(s) (of type IType) - * via SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param context - * the runnable context used to show progress when the dialog is - * being populated - * @param scope - * the scope that limits which types are included - * @param style - * flags defining the style of the dialog; the only valid values - * are IJavaElementSearchConstants.CONSIDER_BINARIES, - * CONSIDER_EXTERNAL_JARS, or their bitwise OR, - * or 0 - * @param multipleSelection - * true if multiple selection is allowed - * @param filter - * the initial pattern to filter the set of types containg a main - * method. For example "App" shows all types starting with "app". - * The meta character '?' representing any character and '*' - * representing any string are supported. Clients can pass an - * empty string if no filtering is required. - * @return a new selection dialog - * - * @since 2.0 - */ - // public static SelectionDialog createMainTypeDialog(Shell parent, - // IRunnableContext context, IJavaSearchScope scope, int style, boolean - // multipleSelection, String filter) { - // if (multipleSelection) { - // MultiMainTypeSelectionDialog dialog= new - // MultiMainTypeSelectionDialog(parent, context, scope, style); - // dialog.setFilter(filter); - // return dialog; - // } else { - // MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, - // context, scope, style); - // dialog.setFilter(filter); - // return dialog; - // } - // } - /** - * Creates a selection dialog that lists all types in the given scope - * containing a standard main method. The caller is - * responsible for opening the dialog with Window.open, and - * subsequently extracting the selected type(s) (of type IType) - * via SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param context - * the runnable context used to show progress when the dialog is - * being populated - * @param scope - * the scope that limits which types are included - * @param style - * flags defining the style of the dialog; the only valid values - * are IJavaElementSearchConstants.CONSIDER_BINARIES, - * CONSIDER_EXTERNAL_JARS, or their bitwise OR, - * or 0 - * @param multipleSelection - * true if multiple selection is allowed - * @return a new selection dialog - */ - // public static SelectionDialog createMainTypeDialog(Shell parent, - // IRunnableContext context, IJavaSearchScope scope, int style, boolean - // multipleSelection) { - // return createMainTypeDialog(parent, context, scope, style, - // multipleSelection, "");//$NON-NLS-1$ - // } - /** - * Creates a selection dialog that lists all types in the given project. The - * caller is responsible for opening the dialog with - * Window.open, and subsequently extracting the selected - * type(s) (of type IType) via - * SelectionDialog.getResult. - * - * @param parent - * the parent shell of the dialog to be created - * @param context - * the runnable context used to show progress when the dialog is - * being populated - * @param project - * the Java project - * @param style - * flags defining the style of the dialog; the only valid values - * are IJavaElementSearchConstants.CONSIDER_CLASSES, - * CONSIDER_INTERFACES, or their bitwise OR - * (equivalent to CONSIDER_TYPES) - * @param multipleSelection - * true if multiple selection is allowed - * @return a new selection dialog - * @exception JavaModelException - * if the selection dialog could not be opened - */ - // public static SelectionDialog createTypeDialog(Shell parent, - // IRunnableContext context, IProject project, int style, boolean - // multipleSelection) throws JavaModelException { - // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new - // IJavaProject[] { JavaCore.create(project) }); - // return createTypeDialog(parent, context, scope, style, - // multipleSelection); - // } - /** - * Opens a Java editor on the given Java element. The element can be a - * compilation unit or class file. If there already is an open Java editor - * for the given element, it is returned. - * - * @param element - * the input element; either a compilation unit (ICompilationUnit) - * or a class file (
IClassFile) - * @return the editor, or null if wrong element type or - * opening failed - * @exception PartInitException - * if the editor could not be initialized - * @exception JavaModelException - * if this element does not exist or if an exception occurs - * while accessing its underlying resource - */ -// public static IEditorPart openInEditor(IJavaElement element) -// throws JavaModelException, PartInitException { -// return EditorUtility.openInEditor(element); -// } - - /** - * Reveals the source range of the given source reference element in the - * given editor. No checking is done if the editor displays a compilation - * unit or class file that contains the given source reference. The editor - * simply reveals the source range denoted by the given source reference. - * - * @param part - * the editor displaying the compilation unit or class file - * @param element - * the source reference element defining the source range to be - * revealed - * - * @deprecated use revealInEditor(IEditorPart, IJavaElement) - * instead - */ - // public static void revealInEditor(IEditorPart part, ISourceReference - // element) { - // if (element instanceof IJavaElement) - // revealInEditor(part, (IJavaElement) element); - // } - /** - * Reveals the given java element in the given editor. If the element is not - * an instance of ISourceReference this method result in a - * NOP. If it is a source reference no checking is done if the editor - * displays a compilation unit or class file that contains the source - * reference element. The editor simply reveals the source range denoted by - * the given element. - * - * @param part - * the editor displaying a compilation unit or class file - * @param element - * the element to be revealed - * - * @since 2.0 - */ - // public static void revealInEditor(IEditorPart part, IJavaElement element) - // { - // EditorUtility.revealInEditor(part, element); - // } - /** - * Returns the working copy manager for the Java UI plug-in. - * - * @return the working copy manager for the Java UI plug-in - */ -// public static IWorkingCopyManager getWorkingCopyManager() { -// return WebUI.getDefault().getWorkingCopyManager(); -// } - - /** - * Answers the shared working copies currently registered for the Java - * plug-in. Note that the returned array can include working copies that are - * not on the class path of a Java project. - * - * @return the list of shared working copies - * - * @see net.sourceforge.phpdt.core.JavaCore#getSharedWorkingCopies(net.sourceforge.phpdt.core.IBufferFactory) - * @since 2.0 - */ -// public static IWorkingCopy[] getSharedWorkingCopies() { -// return JavaCore.getSharedWorkingCopies(getBufferFactory()); -// } - - /** - * Answers the shared working copies that are on the class path of a Java - * project currently registered for the Java plug-in. - * - * - * @return the list of shared working copies - * - * @see #getSharedWorkingCopies() - * @since 2.1 - */ - // public static IWorkingCopy[] getSharedWorkingCopiesOnClasspath() { - // IWorkingCopy[] wcs= getSharedWorkingCopies(); - // List result= new ArrayList(wcs.length); - // for (int i = 0; i < wcs.length; i++) { - // IWorkingCopy wc= wcs[i]; - // if (wc instanceof IJavaElement) { - // IJavaElement je= (IJavaElement)wc; - // if (je.getJavaProject().isOnClasspath(je)) { - // result.add(wc); - // } - // } - // } - // return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]); - // } - /** - * Returns the BufferFactory for the Java UI plug-in. - * - * @return the BufferFactory for the Java UI plug-in - * - * @see net.sourceforge.phpdt.core.IBufferFactory - * @since 2.0 - * @deprecated {@link IBufferFactory} has been replaced by - * {@link net.sourceforge.phpdt.core.WorkingCopyOwner}. The - * Java UI plug-in uses the primary working copy owner - * that can be accessed with null in API's that - * require an owner - */ - public static IBufferFactory getBufferFactory() { - return PHPeclipsePlugin.getDefault().getBufferFactory(); - } - - /** - * Returns the DocumentProvider used for Java compilation units. - * - * @return the DocumentProvider for Java compilation units. - * - * @see IDocumentProvider - * @since 2.0 - */ -// public static IDocumentProvider getDocumentProvider() { -// return WebUI.getDefault() -// .getCompilationUnitDocumentProvider(); -// } - - /** - * Sets the Javadoc location for an archive with the given path. - * - * @param archivePath - * the path of the library; this can be an workspace path or an - * external path in case of an external library. - * @param url - * The Javadoc location to set. This location should contain - * index.html and a file 'package-list'. null - * clears the current documentation location. - * - * @since 2.0 - */ - // public static void setLibraryJavadocLocation(IPath archivePath, URL url) - // { - // JavaDocLocations.setLibraryJavadocLocation(archivePath, url); - // } - /** - * Returns the Javadoc location for an archive or null if no - * location is available. - * - * @param archivePath - * the path of the library. This can be an workspace path or an - * external path in case of an external library. - * - * @since 2.0 - */ - // public static URL getLibraryJavadocLocation(IPath archivePath) { - // return JavaDocLocations.getLibraryJavadocLocation(archivePath); - // } - /** - * Sets the Javadoc location for a Java project. This location is used for - * all types located in the project's source folders. - * - * @param project - * the project - * @param url - * The Javadoc location to set. This location should contain - * index.html and a file 'package-list'. null - * clears the current documentation location. - * - * @since 2.1 - */ - // public static void setProjectJavadocLocation(IJavaProject project, URL - // url) { - // JavaDocLocations.setProjectJavadocLocation(project, url); - // } - /** - * Returns the Javadoc location for a Java project or null if - * no location is available. This location is used for all types located in - * the project's source folders. - * - * @param project - * the project - * - * @since 2.1 - */ - // public static URL getProjectJavadocLocation(IJavaProject project) { - // return JavaDocLocations.getProjectJavadocLocation(project); - // } - /** - * Returns the Javadoc base URL for an element. The base location contains - * the index file. This location doesn't have to exist. Returns - * null if no javadoc location has been attached to the - * element's library or project. Example of a returned URL is http://www. - * junit. org/junit/javadoc. - * - * @param The - * element for which the doc URL is requested. - * - * @since 2.0 - */ - // public static URL getJavadocBaseLocation(IJavaElement element) throws - // JavaModelException { - // return JavaDocLocations.getJavadocBaseLocation(element); - // } - /** - * Returns the Javadoc URL for an element. Example of a returned URL is - * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html. - * This returned location doesn't have to exist. Returns null - * if no javadoc location has been attached to the element's library or - * project. - * - * @param The - * element for which the doc URL is requested. - * @param includeAnchor - * If set, the URL contains an anchor for member references: - * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult). - * Note that this involves type resolving and is a more expensive - * call than without anchor. - * - * @since 2.0 - */ - // public static URL getJavadocLocation(IJavaElement element, boolean - // includeAnchor) throws JavaModelException { - // return JavaDocLocations.getJavadocLocation(element, includeAnchor); - // } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java deleted file mode 100644 index 8418417..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java +++ /dev/null @@ -1,224 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui; - -import net.sourceforge.phpdt.core.Flags; -import net.sourceforge.phpdt.core.IMethod; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.IDecoration; -import org.eclipse.jface.viewers.ILabelDecorator; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ILightweightLabelDecorator; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; - -/** - * LabelDecorator that decorates an method's image with override or implements - * overlays. The viewer using this decorator is responsible for updating the - * images on element changes. - * - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * @since 2.0 - */ -public class OverrideIndicatorLabelDecorator implements ILabelDecorator, - ILightweightLabelDecorator { - - private ImageDescriptorRegistry fRegistry; - - private boolean fUseNewRegistry = false; - - /** - * Creates a decorator. The decorator creates an own image registry to cache - * images. - */ -// public OverrideIndicatorLabelDecorator() { -// this(null); -// fUseNewRegistry = true; -// } - - /* - * Creates decorator with a shared image registry. - * - * @param registry The registry to use or null to use the - * Java plugin's image registry. - */ - /** - * Note: This constructor is for internal use only. Clients should not call - * this constructor. - */ - public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) { - fRegistry = registry; - } - - private ImageDescriptorRegistry getRegistry() { - if (fRegistry == null) { - fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() - : WebUI.getImageDescriptorRegistry(); - } - return fRegistry; - } - - /* - * (non-Javadoc) - * - * @see ILabelDecorator#decorateText(String, Object) - */ - public String decorateText(String text, Object element) { - return text; - } - - /* - * (non-Javadoc) - * - * @see ILabelDecorator#decorateImage(Image, Object) - */ - public Image decorateImage(Image image, Object element) { - int adornmentFlags = computeAdornmentFlags(element); - if (adornmentFlags != 0) { - ImageDescriptor baseImage = new ImageImageDescriptor(image); - Rectangle bounds = image.getBounds(); - return getRegistry().get( - new JavaElementImageDescriptor(baseImage, adornmentFlags, - new Point(bounds.width, bounds.height))); - } - return image; - } - - /** - * Note: This method is for internal use only. Clients should not call this - * method. - */ - public int computeAdornmentFlags(Object element) { - if (element instanceof IMethod) { - if (!PreferenceConstants.getPreferenceStore().getBoolean( - PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) { - return 0; - } - - try { - IMethod method = (IMethod) element; - // if (!method.getJavaProject().isOnClasspath(method)) { - // return 0; - // } - - int flags = method.getFlags(); - IType type = method.getDeclaringType();// jsurfer INSERT - if (type != null && type.isClass() && !method.isConstructor() - && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) { - return getOverrideIndicators(method); - } - } catch (JavaModelException e) { - if (!e.isDoesNotExist()) { - PHPeclipsePlugin.log(e); - } - } - } - return 0; - } - - /** - * Note: This method is for internal use only. Clients should not call this - * method. - */ - protected int getOverrideIndicators(IMethod method) - throws JavaModelException { - //IType type = method.getDeclaringType(); - // ITypeHierarchy hierarchy= - // SuperTypeHierarchyCache.getTypeHierarchy(type); - // if (hierarchy != null) { - // return findInHierarchy(type, hierarchy, method.getElementName(), - // method.getParameterTypes()); - // } - return 0; - } - - /** - * Note: This method is for internal use only. Clients should not call this - * method. - */ - // protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, - // String name, String[] paramTypes) throws JavaModelException { - // IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, - // type, name, paramTypes, false); - // if (impl != null) { - // IMethod overridden= - // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, - // paramTypes, false); - // if (overridden != null) { - // return JavaElementImageDescriptor.OVERRIDES; - // } else { - // return JavaElementImageDescriptor.IMPLEMENTS; - // } - // } - // return 0; - // } - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#addListener(ILabelProviderListener) - */ - public void addListener(ILabelProviderListener listener) { - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#dispose() - */ - public void dispose() { - if (fRegistry != null && fUseNewRegistry) { - fRegistry.dispose(); - } - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#isLabelProperty(Object, String) - */ - public boolean isLabelProperty(Object element, String property) { - return true; - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#removeListener(ILabelProviderListener) - */ - public void removeListener(ILabelProviderListener listener) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, - * org.eclipse.jface.viewers.IDecoration) - */ - public void decorate(Object element, IDecoration decoration) { - int adornmentFlags = computeAdornmentFlags(element); - if (adornmentFlags != 0) { - decoration.addOverlay(PHPUiImages.DESC_OVR_OVERRIDES); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/PreferenceConstants.java deleted file mode 100644 index 692d10b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/PreferenceConstants.java +++ /dev/null @@ -1,3071 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2002 International Business Machines Corp. and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v05.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ -package net.sourceforge.phpdt.ui; - -import net.sourceforge.phpdt.core.IClasspathEntry; -import net.sourceforge.phpdt.internal.ui.text.spelling.SpellCheckEngine; -import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys; -import net.sourceforge.phpeclipse.IPreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -// -// import org.phpeclipse.phpdt.internal.ui.JavaPlugin; -// import -// org.phpeclipse.phpdt.internal.ui.preferences.NewJavaProjectPreferencePage; - -/** - * Preference constants used in the JDT-UI preference store. Clients should only - * read the JDT-UI preference store using these values. Clients are not allowed - * to modify the preference store programmatically. - * - * @since 2.0 - */ -public class PreferenceConstants { - - private PreferenceConstants() { - } - - /** - * A named preference that controls return type rendering of methods in the - * UI. - *

- * Value is of type Boolean: if true return - * types are rendered - *

- */ - public static final String APPEARANCE_METHOD_RETURNTYPE = "net.sourceforge.phpdt.ui.methodreturntype"; //$NON-NLS-1$ - - /** - * A named preference that controls if override indicators are rendered in - * the UI. - *

- * Value is of type Boolean: if true override - * indicators are rendered - *

- */ - public static final String APPEARANCE_OVERRIDE_INDICATOR = "net.sourceforge.phpdt.ui.overrideindicator"; //$NON-NLS-1$ - - /** - * A named preference that defines the pattern used for package name - * compression. - *

- * Value is of type String. For example foe the given - * package name 'net.sourceforge.phpdt' pattern '.' will compress it to - * '..jdt', '1~' to 'o~.e~.jdt'. - *

- */ - public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW = "PackagesView.pkgNamePatternForPackagesView"; //$NON-NLS-1$ - - /** - * A named preference that controls if package name compression is turned on - * or off. - *

- * Value is of type Boolean. - *

- * - * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW - */ - public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES = "net.sourceforge.phpdt.ui.compresspackagenames"; //$NON-NLS-1$ - - /** - * A named preference that controls if empty inner packages are folded in - * the hierarchical mode of the package explorer. - *

- * Value is of type Boolean: if true empty - * inner packages are folded. - *

- * - * @since 2.1 - */ - public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER = "net.sourceforge.phpdt.ui.flatPackagesInPackageExplorer"; //$NON-NLS-1$ - - /** - * A named preference that defines how member elements are ordered by the - * Java views using the JavaElementSorter. - *

- * Value is of type String: A comma separated list of the - * following entries. Each entry must be in the list, no duplication. List - * order defines the sort order. - *

    - *
  • T : Types
  • - *
  • C : Constructors
  • - *
  • I : Initializers
  • - *
  • M : Methods
  • - *
  • F : Fields
  • - *
  • SI : Static Initializers
  • - *
  • SM : Static Methods
  • - *
  • SF : Static Fields
  • - *
- *

- * - * @since 2.1 - */ - public static final String APPEARANCE_MEMBER_SORT_ORDER = "outlinesortoption"; //$NON-NLS-1$ - - /** - * A named preference that defines how member elements are ordered by - * visibility in the Java views using the JavaElementSorter. - *

- * Value is of type String: A comma separated list of the - * following entries. Each entry must be in the list, no duplication. List - * order defines the sort order. - *

    - *
  • B : Public
  • - *
  • V : Private
  • - *
  • R : Protected
  • - *
  • D : Default
  • - *
- *

- * - * @since 3.0 - */ - public static final String APPEARANCE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.visibility.order"; //$NON-NLS-1$ - - /** - * A named preferences that controls if Java elements are also sorted by - * visibility. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.enable.visibility.order"; //$NON-NLS-1$ - - /** - * A named preference that controls if prefix removal during setter/getter - * generation is turned on or off. - *

- * Value is of type Boolean. - *

- */ - public static final String CODEGEN_USE_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.enable"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of prefixes to be removed from a - * local variable to compute setter and gettter names. - *

- * Value is of type String: comma separated list of prefixed - *

- * - * @see #CODEGEN_USE_GETTERSETTER_PREFIX - */ - public static final String CODEGEN_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.list"; //$NON-NLS-1$ - - /** - * A named preference that controls if suffix removal during setter/getter - * generation is turned on or off. - *

- * Value is of type Boolean. - *

- */ - public static final String CODEGEN_USE_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.enable"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of suffixes to be removed from a - * local variable to compute setter and getter names. - *

- * Value is of type String: comma separated list of suffixes - *

- * - * @see #CODEGEN_USE_GETTERSETTER_SUFFIX - */ - public static final String CODEGEN_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the keyword "this" will be added - * automatically to field accesses in generated methods. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String CODEGEN_KEYWORD_THIS = "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ - - /** - * A named preference that controls whether to use the prefix "is" or the - * prefix "get" for automatically created getters which return a boolean - * field. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String CODEGEN_IS_FOR_GETTERS = "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ - - /** - * A named preference that defines the preferred variable names for - * exceptions in catch clauses. - *

- * Value is of type String. - *

- * - * @since 3.0 - */ - public static final String CODEGEN_EXCEPTION_VAR_NAME = "org.eclipse.jdt.ui.exception.name"; //$NON-NLS-1$ - - /** - * A named preference that controls if comment stubs will be added - * automatically to newly created types and methods. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public static final String CODEGEN_ADD_COMMENTS = "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ - - /** - * A name preference that controls if a JavaDoc stub gets added to newly - * created types and methods. - *

- * Value is of type Boolean. - *

- * - * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). - */ - // public static final String CODEGEN__JAVADOC_STUBS = CODEGEN_ADD_COMMENTS; - // //$NON-NLS-1$ - /** - * A named preference that controls if a non-phpdoc comment gets added to - * methods generated via the "Override Methods" operation. - *

- * Value is of type Boolean. - *

- */ - public static final String CODEGEN__NON_JAVADOC_COMMENTS = "net.sourceforge.phpdt.ui.seecomments"; //$NON-NLS-1$ - - /** - * A named preference that controls if a file comment gets added to newly - * created files. - *

- * Value is of type Boolean. - *

- */ - public static final String CODEGEN__FILE_COMMENTS = "net.sourceforge.phpdt.ui.filecomments"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of comma separated package names. - * The list specifies the import order used by the "Organize Imports" - * opeation. - *

- * Value is of type String: semicolon separated list of - * package names - *

- */ - // public static final String ORGIMPORTS_IMPORTORDER = - // "net.sourceforge.phpdt.ui.importorder"; //$NON-NLS-1$ - /** - * A named preference that specifies the number of imports added before a - * star-import declaration is used. - *

- * Value is of type Int: positive value specifing the number - * of non star-import is used - *

- */ - public static final String ORGIMPORTS_ONDEMANDTHRESHOLD = "net.sourceforge.phpdt.ui.ondemandthreshold"; //$NON-NLS-1$ - - /** - * A named preferences that controls if types that start with a lower case - * letters get added by the "Organize Import" operation. - *

- * Value is of type Boolean. - *

- */ - public static final String ORGIMPORTS_IGNORELOWERCASE = "net.sourceforge.phpdt.ui.ignorelowercasenames"; //$NON-NLS-1$ - - /** - * A named preference that speficies whether children of a compilation unit - * are shown in the package explorer. - *

- * Value is of type Boolean. - *

- */ - public static final String SHOW_CU_CHILDREN = "net.sourceforge.phpdt.ui.packages.cuchildren"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the package explorer's selection - * is linked to the active editor. - *

- * Value is of type Boolean. - *

- */ - public static final String LINK_PACKAGES_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the hierarchy view's selection - * is linked to the active editor. - *

- * Value is of type Boolean. - *

- */ - public static final String LINK_TYPEHIERARCHY_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the browsing view's selection is - * linked to the active editor. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public static final String LINK_BROWSING_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether new projects are generated using - * source and output folder. - *

- * Value is of type Boolean. if true new - * projects are created with a source and output folder. If - * false source and output folder equals to the project. - *

- */ - public static final String SRCBIN_FOLDERS_IN_NEWPROJ = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ - - /** - * A named preference that specifies the source folder name used when - * creating a new Java project. Value is inactive if - * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. - *

- * Value is of type String. - *

- * - * @see #SRCBIN_FOLDERS_IN_NEWPROJ - */ - public static final String SRCBIN_SRCNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ - - /** - * A named preference that specifies the output folder name used when - * creating a new Java project. Value is inactive if - * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. - *

- * Value is of type String. - *

- * - * @see #SRCBIN_FOLDERS_IN_NEWPROJ - */ - public static final String SRCBIN_BINNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ - - /** - * A named preference that holds a list of possible JRE libraries used by - * the New Java Project wizard. An library consists of a description and an - * arbitrary number of IClasspathEntrys, that will represent - * the JRE on the new project's classpath. - *

- * Value is of type String: a semicolon separated list of - * encoded JRE libraries. NEWPROJECT_JRELIBRARY_INDEX defines - * the currently used library. Clients should use the method - * encodeJRELibrary to encode a JRE library into a string and - * the methods decodeJRELibraryDescription(String) and - * decodeJRELibraryClasspathEntries(String) - * to decode the description and the array of classpath entries from an - * encoded string. - *

- * - * @see #NEWPROJECT_JRELIBRARY_INDEX - * @see #encodeJRELibrary(String, IClasspathEntry[]) - * @see #decodeJRELibraryDescription(String) - * @see #decodeJRELibraryClasspathEntries(String) - */ - public static final String NEWPROJECT_JRELIBRARY_LIST = "net.sourceforge.phpdt.ui.wizards.jre.list"; //$NON-NLS-1$ - - /** - * A named preferences that specifies the current active JRE library. - *

- * Value is of type Int: an index into the list of possible - * JRE libraries. - *

- * - * @see #NEWPROJECT_JRELIBRARY_LIST - */ - public static final String NEWPROJECT_JRELIBRARY_INDEX = "net.sourceforge.phpdt.ui.wizards.jre.index"; //$NON-NLS-1$ - - /** - * A named preference that controls if a new type hierarchy gets opened in a - * new type hierarchy perspective or inside the type hierarchy view part. - *

- * Value is of type String: possible values are - * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE - * or - * OPEN_TYPE_HIERARCHY_IN_VIEW_PART. - *

- * - * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE - * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART - */ - public static final String OPEN_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.openTypeHierarchy"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * OPEN_TYPE_HIERARCHY. - * - * @see #OPEN_TYPE_HIERARCHY - */ - public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE = "perspective"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * OPEN_TYPE_HIERARCHY. - * - * @see #OPEN_TYPE_HIERARCHY - */ - public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART = "viewPart"; //$NON-NLS-1$ - - /** - * A named preference that controls the behaviour when double clicking on a - * container in the packages view. - *

- * Value is of type String: possible values are - * DOUBLE_CLICK_GOES_INTO - * or - * DOUBLE_CLICK_EXPANDS. - *

- * - * @see #DOUBLE_CLICK_EXPANDS - * @see #DOUBLE_CLICK_GOES_INTO - */ - public static final String DOUBLE_CLICK = "packageview.doubleclick"; //$NON-NLS-1$ - - /** - * A string value used by the named preference DOUBLE_CLICK. - * - * @see #DOUBLE_CLICK - */ - public static final String DOUBLE_CLICK_GOES_INTO = "packageview.gointo"; //$NON-NLS-1$ - - /** - * A string value used by the named preference DOUBLE_CLICK. - * - * @see #DOUBLE_CLICK - */ - public static final String DOUBLE_CLICK_EXPANDS = "packageview.doubleclick.expands"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Java views update their - * presentation while editing or when saving the content of an editor. - *

- * Value is of type String: possible values are - * UPDATE_ON_SAVE - * or - * UPDATE_WHILE_EDITING. - *

- * - * @see #UPDATE_ON_SAVE - * @see #UPDATE_WHILE_EDITING - */ - public static final String UPDATE_JAVA_VIEWS = "JavaUI.update"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * UPDATE_JAVA_VIEWS - * - * @see #UPDATE_JAVA_VIEWS - */ - public static final String UPDATE_ON_SAVE = "JavaUI.update.onSave"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * UPDATE_JAVA_VIEWS - * - * @see #UPDATE_JAVA_VIEWS - */ - public static final String UPDATE_WHILE_EDITING = "JavaUI.update.whileEditing"; //$NON-NLS-1$ - - /** - * A named preference that holds the path of the Javadoc command used by the - * Javadoc creation wizard. - *

- * Value is of type String. - *

- */ - public static final String JAVADOC_COMMAND = "command"; //$NON-NLS-1$ - - /** - * A named preference that defines whether hint to make hover sticky should - * be shown. - * - * @see JavaUI - * @since 3.0 - */ - public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE = "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ - - /** - * A named preference that defines the key for the hover modifiers. - * - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_TEXT_HOVER_MODIFIERS = "hoverModifiers"; //$NON-NLS-1$ - - /** - * The id of the best match hover contributed for extension point - * javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_BESTMATCH_HOVER = "net.sourceforge.phpdt.ui.BestMatchHover"; //$NON-NLS-1$ - - /** - * The id of the source code hover contributed for extension point - * javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_SOURCE_HOVER = "net.sourceforge.phpdt.ui.JavaSourceHover"; //$NON-NLS-1$ - - /** - * The id of the problem hover contributed for extension point - * javaEditorTextHovers. - * - * @since 2.1 - */ - public static String ID_PROBLEM_HOVER = "net.sourceforge.phpdt.ui.ProblemHover"; //$NON-NLS-1$ - - /** - * A named preference that controls whether bracket matching highlighting is - * turned on or off. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_MATCHING_BRACKETS = "matchingBrackets"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to highlight matching - * brackets. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_MATCHING_BRACKETS_COLOR = "matchingBracketsColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the current line highlighting is - * turned on or off. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_CURRENT_LINE = "currentLine"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to highlight the current - * line. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_CURRENT_LINE_COLOR = "currentLineColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the print margin is turned on or - * off. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PRINT_MARGIN = "printMargin"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render the print margin. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PRINT_MARGIN_COLOR = "printMarginColor"; //$NON-NLS-1$ - - /** - * Print margin column. Int value. - */ - public final static String EDITOR_PRINT_MARGIN_COLUMN = "printMarginColumn"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used for the find/replace scope. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_FIND_SCOPE_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; - - /** - * A named preference that specifies if the editor uses spaces for tabs. - *

- * Value is of type Boolean. If true spaces - * instead of tabs are used in the editor. If false the - * editor inserts a tab character when pressing the tab key. - *

- */ - public final static String EDITOR_SPACES_FOR_TABS = "spacesForTabs"; //$NON-NLS-1$ - - /** - * A named preference that holds the number of spaces used per tab in the - * editor. - *

- * Value is of type Int: positive int value specifying the - * number of spaces per tab. - *

- */ - public final static String EDITOR_TAB_WIDTH = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; // "net.sourceforge.phpdt.ui.editor.tab.width"; - - // //$NON-NLS-1$ - - /** - * A named preference that controls whether the outline view selection - * should stay in sync with with the element at the current cursor position. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE = "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ - - /** - * A named preference that controls if correction indicators are shown in - * the UI. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_CORRECTION_INDICATION = "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows problem - * indicators in text (squiggly lines). - *

- * Value is of type Boolean. - *

- */ - // public final static String EDITOR_PROBLEM_INDICATION = - // "problemIndication"; //$NON-NLS-1$ - /** - * A named preference that holds the color used to render problem - * indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_PROBLEM_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - // public final static String EDITOR_PROBLEM_INDICATION_COLOR = - // "problemIndicationColor"; //$NON-NLS-1$ - /** - * PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; A named preference - * that controls whether the editor shows warning indicators in text - * (squiggly lines). - *

- * Value is of type Boolean. - *

- */ - // public final static String EDITOR_WARNING_INDICATION = - // "warningIndication"; //$NON-NLS-1$ - /** - * A named preference that holds the color used to render warning - * indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_WARNING_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - // public final static String EDITOR_WARNING_INDICATION_COLOR = - // "warningIndicationColor"; //$NON-NLS-1$ - /** - * A named preference that controls whether the editor shows task indicators - * in text (squiggly lines). - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_TASK_INDICATION = "taskIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render task indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_TASK_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_TASK_INDICATION_COLOR = "taskIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows bookmark - * indicators in text (squiggly lines). - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION = "bookmarkIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render bookmark - * indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_BOOKMARK_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION_COLOR = "bookmarkIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows search - * indicators in text (squiggly lines). - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION = "searchResultIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render search indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_SEARCH_RESULT_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR = "searchResultIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the editor shows unknown - * indicators in text (squiggly lines). - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION = "othersIndication"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render unknown - * indicators. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see #EDITOR_UNKNOWN_INDICATION - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION_COLOR = "othersIndicationColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows error - * indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER = "errorIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows warning - * indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER = "warningIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows task - * indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER = "taskIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows - * bookmark indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER = "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows search - * result indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the overview ruler shows unknown - * indicators. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER = "othersIndicationInOverviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is - * enabled in PHP mode - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_CLOSE_STRINGS_DQ_PHP = "closeStringsPHPDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is - * enabled in PHP mode - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_CLOSE_STRINGS_SQ_PHP = "closeStringsPHPSQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close brackets' feature is - * enabled in PHP mode - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACKETS_PHP = "closeBracketsPHP"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap words' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_WRAP_WORDS = "wrapWords"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap strings' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_WRAP_STRINGS_DQ = "wrapStringsDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'escape strings' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_ESCAPE_STRINGS_DQ = "escapeStringsDQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'wrap strings' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_WRAP_STRINGS_SQ = "wrapStringsSQ"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'escape strings' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_ESCAPE_STRINGS_SQ = "escapeStringsSQ"; //$NON-NLS-1$ - - /** - * A named preference that controls if content assist inserts the common - * prefix of all proposals before presenting choices. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String CODEASSIST_PREFIX_COMPLETION = "content_assist_prefix_completion"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close braces' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACES = "closeBraces"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close php docs' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_JAVADOCS = "closeJavaDocs"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'add JavaDoc tags' feature - * is enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_ADD_JAVADOC_TAGS = "addJavaDocTags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'format Javadoc tags' - * feature is enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_FORMAT_JAVADOCS = "formatJavaDocs"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'smart paste' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SMART_PASTE = "smartPaste"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close strings' feature is - * enabled in HTML mode - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_STRINGS_HTML = "closeStringsHTML"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'close brackets' feature is - * enabled in HTML mode - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_CLOSE_BRACKETS_HTML = "closeBracketsHTML"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the 'smart home-end' feature is - * enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SMART_HOME_END = AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; - - /** - * A named preference that controls whether the 'sub-word navigation' - * feature is enabled. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_SUB_WORD_NAVIGATION = "subWordNavigation"; //$NON-NLS-1$ - - /** - * A named preference that controls if temporary problems are evaluated and - * shown in the UI. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = "handleTemporaryProblems"; //$NON-NLS-1$ - - /** - * A named preference that controls if the overview ruler is shown in the - * UI. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_OVERVIEW_RULER = "overviewRuler"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render linked positions - * inside code templates. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_LINKED_POSITION_COLOR = "linkedPositionColor"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used as the text foreground. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_FOREGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; - - /** - * A named preference that describes if the system default foreground color - * is used as the text foreground. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_FOREGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; - - /** - * A named preference that holds the color used as the text background. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_BACKGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; - - /** - * A named preference that describes if the system default background color - * is used as the text foreground. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_BACKGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; - - /** - * Preference key suffix for bold text style preference keys. - */ - public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ - - /** - * Preference key suffix for bold text style preference keys. - */ - public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ - - /** - * A named preference that holds the color used to render multi line - * comments. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_MULTI_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_MULTILINE_COMMENT; - - /** - * The symbolic font name for the Java editor text font (value - * "net.sourceforge.phpdt.ui.editors.textfont"). - * - * @since 2.1 - */ - public final static String EDITOR_TEXT_FONT = "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ - - /** - * A named preference that controls whether multi line comments are rendered - * in bold. - *

- * Value is of type Boolean. If true multi - * line comments are rendered in bold. If false the are - * rendered using no font style attribute. - *

- */ - public final static String EDITOR_MULTI_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_MULTILINE_COMMENT - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render single line - * comments. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_SINGLELINE_COMMENT; - - /** - * A named preference that controls whether sinle line comments are rendered - * in bold. - *

- * Value is of type Boolean. If true single - * line comments are rendered in bold. If false the are - * rendered using no font style attribute. - *

- */ - public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_SINGLELINE_COMMENT - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render operators and - * brackets. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_COLOR = IPreferenceConstants.PHP_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are - * rendered in bold. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_BOLD = IPreferenceConstants.PHP_OPERATOR - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are - * rendered in italic. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_OPERATOR_ITALIC = IPreferenceConstants.PHP_OPERATOR - + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render operators and - * brackets. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = IPreferenceConstants.PHP_BRACE_OPERATOR; - - /** - * A named preference that controls whether operators and brackets are - * rendered in bold. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = IPreferenceConstants.PHP_BRACE_OPERATOR - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether operators and brackets are - * rendered in italic. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = IPreferenceConstants.PHP_BRACE_OPERATOR - + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render the 'return' - * keyword. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = IPreferenceConstants.PHP_KEYWORD_RETURN; - - /** - * A named preference that controls whether 'return' keyword is rendered in - * bold. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = IPreferenceConstants.PHP_KEYWORD_RETURN - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that controls whether 'return' keyword is rendered in - * italic. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = IPreferenceConstants.PHP_KEYWORD_RETURN - + EDITOR_ITALIC_SUFFIX; - - /** - * A named preference that holds the color used to render php start and stop - * tags. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_TAG_COLOR = IPreferenceConstants.PHP_TAG; - - /** - * A named preference that controls whether php start and stop tags are - * rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_TAG_BOLD = IPreferenceConstants.PHP_TAG - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php keywords. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVA_KEYWORD_COLOR = IPreferenceConstants.PHP_KEYWORD; - - /** - * A named preference that controls whether keywords are rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVA_KEYWORD_BOLD = IPreferenceConstants.PHP_KEYWORD - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render predefined php - * function names. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_FUNCTIONNAME_COLOR = IPreferenceConstants.PHP_FUNCTIONNAME; - - /** - * A named preference that controls whether function names are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_FUNCTIONNAME_BOLD = IPreferenceConstants.PHP_FUNCTIONNAME - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php variables with - * prefix '$_'. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_VARIABLE_DOLLAR_COLOR = IPreferenceConstants.PHP_VARIABLE_DOLLAR; - - /** - * A named preference that controls whether variables with prefix '$_' are - * rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_VARIABLE_DOLLAR_BOLD = IPreferenceConstants.PHP_VARIABLE_DOLLAR - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php variables. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_VARIABLE_COLOR = IPreferenceConstants.PHP_VARIABLE; - - /** - * A named preference that controls whether variables are rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_VARIABLE_BOLD = IPreferenceConstants.PHP_VARIABLE - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php constants. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_CONSTANT_COLOR = IPreferenceConstants.PHP_CONSTANT; - - /** - * A named preference that controls whether constants are rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_CONSTANT_BOLD = IPreferenceConstants.PHP_CONSTANT - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php types. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_PHP_TYPE_COLOR = IPreferenceConstants.PHP_TYPE; - - /** - * A named preference that controls whether types are rendered in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_PHP_TYPE_BOLD = IPreferenceConstants.PHP_TYPE - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render string constants. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_STRING_COLOR_DQ = IPreferenceConstants.PHP_STRING_DQ; - - /** - * A named preference that controls whether string constants are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_STRING_BOLD_DQ = IPreferenceConstants.PHP_STRING_DQ - + EDITOR_BOLD_SUFFIX; - - public final static String EDITOR_STRING_COLOR_SQ = IPreferenceConstants.PHP_STRING_SQ; - - /** - * A named preference that controls whether string constants are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_STRING_BOLD_SQ = IPreferenceConstants.PHP_STRING_SQ - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render php default text. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVA_DEFAULT_COLOR = IPreferenceConstants.PHP_DEFAULT; - - /** - * A named preference that controls whether Java default text is rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVA_DEFAULT_BOLD = IPreferenceConstants.PHP_DEFAULT - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render task tags. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_TASK_TAG_COLOR = IPreferenceConstants.TASK_TAG; - - /** - * A named preference that controls whether task tags are rendered in bold. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String EDITOR_TASK_TAG_BOLD = IPreferenceConstants.TASK_TAG - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc keywords. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_KEYWORD_COLOR = IPreferenceConstants.PHPDOC_KEYWORD; - - /** - * A named preference that controls whether phpdoc keywords are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVADOC_KEYWORD_BOLD = IPreferenceConstants.PHPDOC_KEYWORD - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc tags. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_TAG_COLOR = IPreferenceConstants.PHPDOC_TAG; - - /** - * A named preference that controls whether phpdoc tags are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVADOC_TAG_BOLD = IPreferenceConstants.PHPDOC_TAG - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc links. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_LINKS_COLOR = IPreferenceConstants.PHPDOC_LINK; - - /** - * A named preference that controls whether phpdoc links are rendered in - * bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVADOC_LINKS_BOLD = IPreferenceConstants.PHPDOC_LINK - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used to render phpdoc default - * text. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String EDITOR_JAVADOC_DEFAULT_COLOR = IPreferenceConstants.PHPDOC_DEFAULT; - - /** - * A named preference that controls whether phpdoc default text is rendered - * in bold. - *

- * Value is of type Boolean. - *

- */ - public final static String EDITOR_JAVADOC_DEFAULT_BOLD = IPreferenceConstants.PHPDOC_DEFAULT - + EDITOR_BOLD_SUFFIX; - - /** - * A named preference that holds the color used for 'linked-mode' underline. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String EDITOR_LINK_COLOR = "linkColor"; //$NON-NLS-1$ - - /** - * A named preference that controls whether hover tooltips in the editor are - * turned on or off. - *

- * Value is of type Boolean. - *

- */ - public static final String EDITOR_SHOW_HOVER = "net.sourceforge.phpdt.ui.editor.showHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when no control key is - * pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_NONE_HOVER = "noneHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the - * CTRL modifier key is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI - * @since 2.1 - */ - public static final String EDITOR_CTRL_HOVER = "ctrlHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the - * SHIFT modifier key is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_SHIFT_HOVER = "shiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the - * CTRL + ALT modifier keys is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_ALT_HOVER = "ctrlAltHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the - * CTRL + ALT + SHIFT modifier keys is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_ALT_SHIFT_HOVER = "ctrlAltShiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the - * CTRL + SHIFT modifier keys is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_CTRL_SHIFT_HOVER = "ctrlShiftHover"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover shown when the ALT - * modifier key is pressed. - *

- * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID, - * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a - * hover contributed as phpEditorTextHovers. - *

- * - * @see #EDITOR_NO_HOVER_CONFIGURED_ID - * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID - * @see JavaUI ID_*_HOVER - * @since 2.1 - */ - public static final String EDITOR_ALT_SHIFT_HOVER = "altShiftHover"; //$NON-NLS-1$ - - /** - * A string value used by the named preferences for hover configuration to - * descibe that no hover should be shown for the given key modifiers. - * - * @since 2.1 - */ - public static final String EDITOR_NO_HOVER_CONFIGURED_ID = "noHoverConfiguredId"; //$NON-NLS-1$ - - /** - * A string value used by the named preferences for hover configuration to - * descibe that the default hover should be shown for the given key - * modifiers. The default hover is described by the - * EDITOR_DEFAULT_HOVER property. - * - * @since 2.1 - */ - public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID = "defaultHoverConfiguredId"; //$NON-NLS-1$ - - /** - * A named preference that defines the hover named the 'default hover'. - * Value is of type String: possible values are - * EDITOR_NO_HOVER_CONFIGURED_ID - * or the hover id of a hover - * contributed as phpEditorTextHovers. - *

- *@since 2.1 - */ - public static final String EDITOR_DEFAULT_HOVER = "defaultHover"; //$NON-NLS-1$ - - /** - * A named preference that controls if segmented view (show selected element - * only) is turned on or off. - *

- * Value is of type Boolean. - *

- */ - public static final String EDITOR_SHOW_SEGMENTS = "net.sourceforge.phpdt.ui.editor.showSegments"; //$NON-NLS-1$ - - /** - * A named preference that controls if browser like links are turned on or - * off. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS = "browserLikeLinks"; //$NON-NLS-1$ - - /** - * A named preference that controls the key modifier for browser like links. - *

- * Value is of type String. - *

- * - * @since 2.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER = "browserLikeLinksKeyModifier"; //$NON-NLS-1$ - - /** - * A named preference that controls whether occurrences are marked in the - * editor. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_MARK_OCCURRENCES = "markOccurrences"; //$NON-NLS-1$ - - /** - * A named preference that controls whether occurrences are sticky in the - * editor. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_STICKY_OCCURRENCES = "stickyOccurrences"; //$NON-NLS-1$ - - /** - * A named preference that controls disabling of the overwrite mode. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_DISABLE_OVERWRITE_MODE = "disable_overwrite_mode"; //$NON-NLS-1$ - - /** - * A named preference that controls saving of a file on loss of editor focus. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_SAVE_ON_BLUR = "save_on_blur"; //$NON-NLS-1$ - - /** - * A named preference that controls the "smart semicolon" smart typing - * handler - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_SMART_SEMICOLON = "smart_semicolon"; //$NON-NLS-1$ - - /** - * A named preference that controls the smart backspace behavior. - *

- * Value is of type Boolean. - * - * @since 3.0 - */ - public static final String EDITOR_SMART_BACKSPACE = "smart_backspace"; //$NON-NLS-1$ - - /** - * A named preference that controls the "smart opening brace" smart typing - * handler - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_SMART_OPENING_BRACE = "smart_opening_brace"; //$NON-NLS-1$ - - /** - * A named preference that controls the smart tab behaviour. - *

- * Value is of type Boolean. - * - * @since 3.0 - */ - public static final String EDITOR_SMART_TAB = "smart_tab"; //$NON-NLS-1$ - - public static final String EDITOR_P_RTRIM_ON_SAVE = "editor_p_trim_on_save"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Java comments should be - * spell-checked. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_CHECK_SPELLING = ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING; - - /** - * A named preference that controls whether words containing digits should - * be skipped during spell-checking. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_DIGITS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS; - - /** - * A named preference that controls whether mixed case words should be - * skipped during spell-checking. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_MIXED = ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED; - - /** - * A named preference that controls whether sentence capitalization should - * be ignored during spell-checking. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_SENTENCE = ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE; - - /** - * A named preference that controls whether upper case words should be - * skipped during spell-checking. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_UPPER = ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER; - - /** - * A named preference that controls whether urls should be ignored during - * spell-checking. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_IGNORE_URLS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS; - - /** - * A named preference that controls the locale used for spell-checking. - *

- * Value is of type String. - *

- * - * @since 3.0 - */ - public final static String SPELLING_LOCALE = ISpellCheckPreferenceKeys.SPELLING_LOCALE; - - /** - * A named preference that controls the number of proposals offered during - * spell-checking. - *

- * Value is of type Integer. - *

- * - * @since 3.0 - */ - public final static String SPELLING_PROPOSAL_THRESHOLD = ISpellCheckPreferenceKeys.SPELLING_PROPOSAL_THRESHOLD; - - /** - * A named preference that specifies the workspace user dictionary. - *

- * Value is of type Integer. - *

- * - * @since 3.0 - */ - public final static String SPELLING_USER_DICTIONARY = ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY; - - /** - * A named preference that specifies whether spelling dictionaries are - * available to content assist. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String SPELLING_ENABLE_CONTENTASSIST = ISpellCheckPreferenceKeys.SPELLING_ENABLE_CONTENTASSIST; - - /** - * A named preference that controls whether code snippets are formatted in - * Javadoc comments. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATSOURCE = "comment_format_source_code"; //$NON-NLS-1$ - - /** - * A named preference that controls whether description of Javadoc - * parameters are indented. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION = "comment_indent_parameter_description"; //$NON-NLS-1$ - - /** - * A named preference that controls whether the header comment of a Java - * source file is formatted. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATHEADER = "comment_format_header"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Javadoc root tags are indented. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_INDENTROOTTAGS = "comment_indent_root_tags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether Javadoc comments are formatted - * by the content formatter. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMAT = "comment_format_comments"; //$NON-NLS-1$ - - /** - * A named preference that controls whether a new line is inserted after - * Javadoc root tag parameters. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER = "comment_new_line_for_parameter"; //$NON-NLS-1$ - - /** - * A named preference that controls whether an empty line is inserted before - * the Javadoc root tag block. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS = "comment_separate_root_tags"; //$NON-NLS-1$ - - /** - * A named preference that controls whether blank lines are cleared during - * formatting - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_CLEARBLANKLINES = "comment_clear_blank_lines"; //$NON-NLS-1$ - - /** - * A named preference that controls the line length of comments. - *

- * Value is of type Integer. The value must be at least 4 - * for reasonable formatting. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_LINELENGTH = "comment_line_length"; //$NON-NLS-1$ - - /** - * A named preference that controls whether html tags are formatted. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public final static String FORMATTER_COMMENT_FORMATHTML = "comment_format_html"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist gets auto - * activated. - *

- * Value is of type Boolean. - *

- */ - public final static String CODEASSIST_AUTOACTIVATION = "content_assist_autoactivation"; //$NON-NLS-1$ - - /** - * A name preference that holds the auto activation delay time in milli - * seconds. - *

- * Value is of type Int. - *

- */ - public final static String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay"; //$NON-NLS-1$ - - /** - * A named preference that controls if code assist contains only visible - * proposals. - *

- * Value is of type Boolean. if - * true code assist only contains visible members. If - * false all members are included. - *

- */ - public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS = "content_assist_show_visible_proposals"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist inserts a - * proposal automatically if only one proposal is available. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String CODEASSIST_AUTOINSERT = "content_assist_autoinsert"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist adds import - * statements. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String CODEASSIST_ADDIMPORT = "content_assist_add_import"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java code assist only inserts - * completions. If set to false the proposals can also _replace_ code. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String CODEASSIST_INSERT_COMPLETION = "content_assist_insert_completion"; //$NON-NLS-1$ - - /** - * A named preference that controls whether code assist proposals filtering - * is case sensitive or not. - *

- * Value is of type Boolean. - *

- */ - public final static String CODEASSIST_CASE_SENSITIVITY = "content_assist_case_sensitivity"; //$NON-NLS-1$ - - /** - * A named preference that defines if code assist proposals are sorted in - * alphabetical order. - *

- * Value is of type Boolean. If true that are - * sorted in alphabetical order. If false that are unsorted. - *

- */ - public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ - - /** - * A named preference that controls if argument names are filled in when a - * method is selected from as list of code assist proposal. - *

- * Value is of type Boolean. - *

- */ - public final static String CODEASSIST_FILL_ARGUMENT_NAMES = "content_assist_fill_method_arguments"; //$NON-NLS-1$ - - /** - * A named preference that controls if method arguments are guessed when a - * method is selected from as list of code assist proposal. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS = "content_assist_guess_method_arguments"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code - * assist in PHP code. - *

- * Value is of type Sring. All characters that trigger auto - * code assist in PHP code. - *

- */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA = "content_assist_autoactivation_triggers_php"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code - * assist in PHPDoc. - *

- * Value is of type Sring. All characters that trigger auto - * code assist in PHPDoc. - *

- */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC = "content_assist_autoactivation_triggers_phpdoc"; //$NON-NLS-1$ - - /** - * A named preference that holds the characters that auto activate code - * assist in HTML. - *

- * Value is of type Sring. All characters that trigger auto - * code assist in HTML. - *

- */ - public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used in the code - * assist selection dialog. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code - * assist selection dialog. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used for parameter - * hints. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_BACKGROUND = "content_assist_parameters_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code - * assist selection dialog - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_FOREGROUND = "content_assist_parameters_foreground"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used in the code - * assist selection dialog to mark replaced code. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String CODEASSIST_REPLACEMENT_BACKGROUND = "content_assist_completion_replacement_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code - * assist selection dialog to mark replaced code. - *

- * Value is of type String. A RGB color value encoded as a - * string using class PreferenceConverter - *

- * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - * @since 2.1 - */ - public final static String CODEASSIST_REPLACEMENT_FOREGROUND = "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ - - /** - * A named preference that controls the behaviour of the refactoring wizard - * for showing the error page. - *

- * Value is of type String. Valid values are: - * REFACTOR_FATAL_SEVERITY, - * REFACTOR_ERROR_SEVERITY,REFACTOR_WARNING_SEVERITY - * REFACTOR_INFO_SEVERITY, - * REFACTOR_OK_SEVERITY. - *

- * - * @see #REFACTOR_FATAL_SEVERITY - * @see #REFACTOR_ERROR_SEVERITY - * @see #REFACTOR_WARNING_SEVERITY - * @see #REFACTOR_INFO_SEVERITY - * @see #REFACTOR_OK_SEVERITY - */ - public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD = "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_FATAL_SEVERITY = "4"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_ERROR_SEVERITY = "3"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_WARNING_SEVERITY = "2"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_INFO_SEVERITY = "1"; //$NON-NLS-1$ - - /** - * A string value used by the named preference - * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. - * - * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD - */ - public static final String REFACTOR_OK_SEVERITY = "0"; //$NON-NLS-1$ - - /** - * A named preference thet controls whether all dirty editors are - * automatically saved before a refactoring is executed. - *

- * Value is of type Boolean. - *

- */ - public static final String REFACTOR_SAVE_ALL_EDITORS = "Refactoring.savealleditors"; //$NON-NLS-1$ - - /** - * A named preference that controls if the Java Browsing views are linked to - * the active editor. - *

- * Value is of type Boolean. - *

- * - * @see #LINK_PACKAGES_TO_EDITOR - */ - public static final String BROWSING_LINK_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ - - /** - * A named preference that controls the layout of the Java Browsing views - * vertically. Boolean value. - *

- * Value is of type Boolean. If - * true the views are stacked vertical. - * If false they are stacked horizontal. - *

- */ - public static final String BROWSING_STACK_VERTICALLY = "net.sourceforge.phpdt.ui.browsing.stackVertically"; //$NON-NLS-1$ - - /** - * A named preference that controls if templates are formatted when applied. - *

- * Value is of type Boolean. - *

- * - * @since 2.1 - */ - public static final String TEMPLATES_USE_CODEFORMATTER = "net.sourceforge.phpdt.ui.template.format"; //$NON-NLS-1$ - - /** - * A named preference that controls whether annotation roll over is used or - * not. - *

- * Value is of type Boolean. If - * true the annotation ruler column - * uses a roll over to display multiple annotations - *

- * - * @since 3.0 - */ - public static final String EDITOR_ANNOTATION_ROLL_OVER = "editor_annotation_roll_over"; //$NON-NLS-1$ - - /** - * A named preference that controls the key modifier mask for browser like - * links. The value is only used if the value of - * EDITOR_BROWSER_LIKE_LINKS cannot be resolved to valid SWT - * modifier bits. - *

- * Value is of type String. - *

- * - * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER - * @since 2.1.1 - */ - public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ - - /** - * A named preference that defines the key for the hover modifier state - * masks. The value is only used if the value of - * EDITOR_TEXT_HOVER_MODIFIERS cannot be resolved to valid - * SWT modifier bits. - * - * @see JavaUI - * @see #EDITOR_TEXT_HOVER_MODIFIERS - * @since 2.1.1 - */ - public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$ - - /** - * A named preference that controls whether folding is enabled in the Java - * editor. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_ENABLED = "editor_folding_enabled"; //$NON-NLS-1$ - - /** - * A named preference that stores the configured folding provider. - *

- * Value is of type String. - *

- * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_PROVIDER = "editor_folding_provider"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for Javadoc folding for the - * default folding provider. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_JAVADOC = "editor_folding_default_javadoc"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for inner type folding for the - * default folding provider. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_INNERTYPES = "editor_folding_default_innertypes"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for method folding for the - * default folding provider. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - public static final String EDITOR_FOLDING_METHODS = "editor_folding_default_methods"; //$NON-NLS-1$ - - /** - * A named preference that stores the value for imports folding for the - * default folding provider. - *

- * Value is of type Boolean. - *

- * - * @since 3.0 - */ - // public static final String EDITOR_FOLDING_IMPORTS = - // "editor_folding_default_imports"; //$NON-NLS-1$ - /** - * A named preference that stores the value for header comment folding for - * the default folding provider. - *

- * Value is of type Boolean. - *

- * - * @since 3.1 - */ - public static final String EDITOR_FOLDING_HEADERS = "editor_folding_default_headers"; //$NON-NLS-1$ - - public static void initializeDefaultValues(IPreferenceStore store) { - store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); - - // JavaBasePreferencePage - store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true); - store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, - false); - store - .setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, - true); - store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, - PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); - store.setDefault(PreferenceConstants.DOUBLE_CLICK, - PreferenceConstants.DOUBLE_CLICK_EXPANDS); - store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, - PreferenceConstants.UPDATE_WHILE_EDITING); - - // AppearancePreferencePage - store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, - false); - store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, - false); - store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); - store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, - true); - store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); - store.setDefault( - PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, - ""); //$NON-NLS-1$ - store - .setDefault( - PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, - true); - - // ImportOrganizePreferencePage - // store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, - // "php;phpx;org;com"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); - store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); - - // ClasspathVariablesPreferencePage - // CodeFormatterPreferencePage - // CompilerPreferencePage - // no initialization needed - - // RefactoringPreferencePage - store.setDefault( - PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, - PreferenceConstants.REFACTOR_ERROR_SEVERITY); - store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); - store.setDefault("RefactoringUI", "dialog"); - - // TemplatePreferencePage - store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); - - // CodeGenerationPreferencePage - store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, - false); - store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, - false); - store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, - "fg, f, _$, _, m_"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ - - store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); - store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); - store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); - store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, - false); - store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); - - // MembersOrderPreferencePage - store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, - "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, - "B,V,R,D"); //$NON-NLS-1$ - store.setDefault( - PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, - false); - // must add here to guarantee that it is the first in the listener list - store.addPropertyChangeListener(WebUI.getDefault() - .getMemberOrderPreferenceCache()); - - store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB( - 192, 192, 192)); - - store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, - 235, 224)); - - store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); - store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, - 180, 185)); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176, - 180)); - - // store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, - // true); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0, - // 128)); - // store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, - // true); - // - // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, - // true); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, - // 200, 45)); - // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, - // true); - // - // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, - // 255)); - // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, - // false); - // - // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, - // false); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, - // 164, 99)); - // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, - // false); - // - // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, - // false); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new - // RGB(192, 192, 192)); - // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, - // false); - // - // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, - // false); - // PreferenceConverter.setDefault(store, - // PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, - // 0)); - // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, - // false); - - store - .setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, - true); - store.setDefault( - PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); - - store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, - true); - - store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); - - // WorkbenchChainedTextFontFieldEditor.startPropagate(store, - // JFaceResources.TEXT_FONT); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, - 200, 100)); - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); - - store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, - true); - - store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, - true); - - store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); - store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB( - 63, 127, 95)); - store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, - false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB( - 63, 127, 95)); - store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, - false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_TAG_COLOR, new RGB(255, 0, 128)); - store.setDefault(PreferenceConstants.EDITOR_PHP_TAG_BOLD, true); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, - 85)); - store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR, new RGB(127, - 127, 159)); - store.setDefault(PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD, - false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR, new RGB(127, - 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR, new RGB( - 127, 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD, - false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR, new RGB(127, 0, - 85)); - store.setDefault(PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_PHP_TYPE_COLOR, new RGB(127, 0, 85)); - store.setDefault(PreferenceConstants.EDITOR_PHP_TYPE_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_STRING_COLOR_DQ, - PHPColorProvider.STRING_DQ); - store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_DQ, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_STRING_COLOR_SQ, - PHPColorProvider.STRING_SQ); - store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_SQ, true); - - PreferenceConverter - .setDefault(store, - PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB( - 0, 0, 0)); - store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, - 159, 191)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, - 159)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, - 191)); - store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); - - PreferenceConverter.setDefault(store, - PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, - 95, 191)); - store - .setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, - false); - - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); - store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, - 500); - - store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB( - 254, 241, 233)); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, - 0, 0)); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB( - 254, 241, 233)); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB( - 0, 0, 0)); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB( - 255, 255, 0)); - PreferenceConverter.setDefault(store, - PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB( - 255, 0, 0)); - store.setDefault( - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, - "$>"); //$NON-NLS-1$ - store.setDefault( - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, - "@"); //$NON-NLS-1$ - store.setDefault( - PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, - "<&#"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, - true); - store - .setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, - false); - store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); - store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); - store - .setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, - true); - store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, - false); - store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, - true); - store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, - false); - - store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); - store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); - store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); - store.setDefault(PreferenceConstants.EDITOR_WRAP_WORDS, false); - store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, true); - store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, false); - store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, true); - store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, false); - store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); - store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); - store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, - false); - - store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, true); - store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, true); - - // store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, - // JavaPlugin.ID_BESTMATCH_HOVER); - store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - // store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, - // JavaPlugin.ID_SOURCE_HOVER); - store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, - PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); - - int modifier = SWT.CTRL; - if (Platform.getOS().equals(Platform.OS_MACOSX)) - modifier = SWT.COMMAND; - String ctrl = Action.findModifierString(modifier); - store - .setDefault( - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, - "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$ - store - .setDefault( - PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, - "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + modifier); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, - true); - - store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); - store.setDefault( - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, - ctrl); - store - .setDefault( - PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, - modifier); - - // mark occurrences - store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, true); - store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, - // true); - // store.setDefault(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, true); - - // spell checking - store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); - store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine - .getDefaultLocale().toString()); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); - store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); - store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); - store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, - false); - - // folding - store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, - "net.sourceforge.phpdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); - // store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, false); - store.setDefault(PreferenceConstants.EDITOR_FOLDING_HEADERS, true); - - store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); - store.setDefault(PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, false); - // do more complicated stuff - // NewJavaProjectPreferencePage.initDefaults(store); - } - - /** - * Returns the JDT-UI preference store. - * - * @return the JDT-UI preference store - */ - public static IPreferenceStore getPreferenceStore() { - return WebUI.getDefault().getPreferenceStore(); - } - - // /** - // * Encodes a JRE library to be used in the named preference - // NEWPROJECT_JRELIBRARY_LIST. - // * - // * @param description a string value describing the JRE library. The - // description is used - // * to indentify the JDR library in the UI - // * @param entries an array of classpath entries to be encoded - // * - // * @return the encoded string. - // */ - // public static String encodeJRELibrary(String description, - // IClasspathEntry[] entries) { - // return NewJavaProjectPreferencePage.encodeJRELibrary(description, - // entries); - // } - // - // /** - // * Decodes an encoded JRE library and returns its description string. - // * - // * @return the description of an encoded JRE library - // * - // * @see #encodeJRELibrary(String, IClasspathEntry[]) - // */ - // public static String decodeJRELibraryDescription(String encodedLibrary) { - // return - // NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); - // } - // - // /** - // * Decodes an encoded JRE library and returns its classpath entries. - // * - // * @return the array of classpath entries of an encoded JRE library. - // * - // * @see #encodeJRELibrary(String, IClasspathEntry[]) - // */ - // public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String - // encodedLibrary) { - // return - // NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); - // } - // - // /** - // * Returns the current configuration for the JRE to be used as default in - // new Java projects. - // * This is a convenience method to access the named preference - // NEWPROJECT_JRELIBRARY_LIST - // * with the index defined by - // NEWPROJECT_JRELIBRARY_INDEX. - // * - // * @return the current default set of classpath entries - // * - // * @see #NEWPROJECT_JRELIBRARY_LIST - // * @see #NEWPROJECT_JRELIBRARY_INDEX - // */ - // public static IClasspathEntry[] getDefaultJRELibrary() { - // return NewJavaProjectPreferencePage.getDefaultJRELibrary(); - // } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java deleted file mode 100644 index 4beed98..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java +++ /dev/null @@ -1,426 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui; - -import java.util.Iterator; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.viewsupport.IProblemChangedListener; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -//incastrix -//import org.eclipse.jface.util.ListenerList; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.IDecoration; -import org.eclipse.jface.viewers.ILabelDecorator; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ILightweightLabelDecorator; -import org.eclipse.jface.viewers.LabelProviderChangedEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.texteditor.MarkerAnnotation; - -/** - * LabelDecorator that decorates an element's image with error and warning - * overlays that represent the severity of markers attached to the element's - * underlying resource. To see a problem decoration for a marker, the marker - * needs to be a subtype of IMarker.PROBLEM. - *

- * Note: Only images for elements in Java projects are currently updated on - * marker changes. - *

- * - * @since 2.0 - */ -public class ProblemsLabelDecorator implements ILabelDecorator, - ILightweightLabelDecorator { - - /** - * This is a special LabelProviderChangedEvent carring - * additional information whether the event orgins from a maker change. - *

- * ProblemsLabelChangedEvents are only generated by - * ProblemsLabelDecorators. - *

- */ - public static class ProblemsLabelChangedEvent extends - LabelProviderChangedEvent { - - /** - * - */ - private static final long serialVersionUID = -7557704732816971319L; - private boolean fMarkerChange; - - /** - * Note: This constructor is for internal use only. Clients should not - * call this constructor. - */ - public ProblemsLabelChangedEvent(IBaseLabelProvider source, - IResource[] changedResource, boolean isMarkerChange) { - super(source, changedResource); - fMarkerChange = isMarkerChange; - } - - /** - * Returns whether this event origins from marker changes. If - * false an annotation model change is the origin. In - * this case viewers not displaying working copies can ignore these - * events. - * - * @return if this event origins from a marker change. - */ - public boolean isMarkerChange() { - return fMarkerChange; - } - - } - - private static final int ERRORTICK_WARNING = JavaElementImageDescriptor.WARNING; - - private static final int ERRORTICK_ERROR = JavaElementImageDescriptor.ERROR; - - private ImageDescriptorRegistry fRegistry; - - private boolean fUseNewRegistry = false; - - private IProblemChangedListener fProblemChangedListener; - - private ListenerList fListeners; - - /** - * Creates a new ProblemsLabelDecorator. - */ -// public ProblemsLabelDecorator() { -// this(null); -// fUseNewRegistry = true; -// } - - /* - * Creates decorator with a shared image registry. - * - * @param registry The registry to use or null to use the - * Java plugin's image registry. - */ - /** - * Note: This constructor is for internal use only. Clients should not call - * this constructor. - */ - public ProblemsLabelDecorator(ImageDescriptorRegistry registry) { - fRegistry = registry; - fProblemChangedListener = null; - } - - private ImageDescriptorRegistry getRegistry() { - if (fRegistry == null) { - fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() - : WebUI.getImageDescriptorRegistry(); - } - return fRegistry; - } - - /* - * (non-Javadoc) - * - * @see ILabelDecorator#decorateText(String, Object) - */ - public String decorateText(String text, Object element) { - return text; - } - - /* - * (non-Javadoc) - * - * @see ILabelDecorator#decorateImage(Image, Object) - */ - public Image decorateImage(Image image, Object obj) { - int adornmentFlags = computeAdornmentFlags(obj); - if (adornmentFlags != 0) { - ImageDescriptor baseImage = new ImageImageDescriptor(image); - Rectangle bounds = image.getBounds(); - return getRegistry().get( - new JavaElementImageDescriptor(baseImage, adornmentFlags, - new Point(bounds.width, bounds.height))); - } - return image; - } - - /** - * Note: This method is for internal use only. Clients should not call this - * method. - */ - protected int computeAdornmentFlags(Object obj) { - try { - if (obj instanceof IJavaElement) { - IJavaElement element = (IJavaElement) obj; - int type = element.getElementType(); - switch (type) { - case IJavaElement.JAVA_PROJECT: - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - return getErrorTicksFromMarkers(element.getResource(), - IResource.DEPTH_INFINITE, null); - case IJavaElement.PACKAGE_FRAGMENT: - case IJavaElement.CLASS_FILE: - return getErrorTicksFromMarkers(element.getResource(), - IResource.DEPTH_ONE, null); - case IJavaElement.COMPILATION_UNIT: - case IJavaElement.PACKAGE_DECLARATION: - case IJavaElement.IMPORT_DECLARATION: - case IJavaElement.IMPORT_CONTAINER: - case IJavaElement.TYPE: - case IJavaElement.INITIALIZER: - case IJavaElement.METHOD: - case IJavaElement.FIELD: - ICompilationUnit cu = (ICompilationUnit) element - .getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) { - ISourceReference ref = (type == IJavaElement.COMPILATION_UNIT) ? null - : (ISourceReference) element; - // The assumption is that only source elements in - // compilation unit can have markers - if (cu.isWorkingCopy()) { - // working copy: look at annotation model - return getErrorTicksFromWorkingCopy( - (ICompilationUnit) cu.getOriginalElement(), - ref); - } - return getErrorTicksFromMarkers(cu.getResource(), - IResource.DEPTH_ONE, ref); - } - break; - default: - } - } else if (obj instanceof IResource) { - return getErrorTicksFromMarkers((IResource) obj, - IResource.DEPTH_INFINITE, null); - } - } catch (CoreException e) { - if (e instanceof JavaModelException) { - if (((JavaModelException) e).isDoesNotExist()) { - return 0; - } - } - PHPeclipsePlugin.log(e); - } - return 0; - } - - private int getErrorTicksFromMarkers(IResource res, int depth, - ISourceReference sourceElement) throws CoreException { - if (res == null || !res.isAccessible()) { - return 0; - } - int info = 0; - - IMarker[] markers = res.findMarkers(IMarker.PROBLEM, true, depth); - if (markers != null) { - for (int i = 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { - IMarker curr = markers[i]; - if (sourceElement == null - || isMarkerInRange(curr, sourceElement)) { - int priority = curr.getAttribute(IMarker.SEVERITY, -1); - if (priority == IMarker.SEVERITY_WARNING) { - info = ERRORTICK_WARNING; - } else if (priority == IMarker.SEVERITY_ERROR) { - info = ERRORTICK_ERROR; - } - } - } - } - return info; - } - - private boolean isMarkerInRange(IMarker marker, - ISourceReference sourceElement) throws CoreException { - if (marker.isSubtypeOf(IMarker.TEXT)) { - int pos = marker.getAttribute(IMarker.CHAR_START, -1); - return isInside(pos, sourceElement); - } - return false; - } - - private int getErrorTicksFromWorkingCopy(ICompilationUnit original, - ISourceReference sourceElement) throws CoreException { - int info = 0; - FileEditorInput editorInput = new FileEditorInput((IFile) original - .getResource()); - IAnnotationModel model = WebUI.getDefault() - .getCompilationUnitDocumentProvider().getAnnotationModel( - editorInput); - if (model != null) { - Iterator iter = model.getAnnotationIterator(); - while ((info != ERRORTICK_ERROR) && iter.hasNext()) { - Annotation curr = (Annotation) iter.next(); - IMarker marker = isAnnotationInRange(model, curr, sourceElement); - if (marker != null) { - int priority = marker.getAttribute(IMarker.SEVERITY, -1); - if (priority == IMarker.SEVERITY_WARNING) { - info = ERRORTICK_WARNING; - } else if (priority == IMarker.SEVERITY_ERROR) { - info = ERRORTICK_ERROR; - } - } - } - } - return info; - } - - private IMarker isAnnotationInRange(IAnnotationModel model, - Annotation annot, ISourceReference sourceElement) - throws CoreException { - if (annot instanceof MarkerAnnotation) { - IMarker marker = ((MarkerAnnotation) annot).getMarker(); - if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { - Position pos = model.getPosition(annot); - if (sourceElement == null - || isInside(pos.getOffset(), sourceElement)) { - return marker; - } - } - } - return null; - } - - /** - * Tests if a position is inside the source range of an element. - * - * @param pos - * Position to be tested. - * @param sourceElement - * Source element (must be a IJavaElement) - * @return boolean Return true if position is located inside - * the source element. - * @throws CoreException - * Exception thrown if element range could not be accessed. - * - * @since 2.1 - */ - protected boolean isInside(int pos, ISourceReference sourceElement) - throws CoreException { - ISourceRange range = sourceElement.getSourceRange(); - if (range != null) { - int rangeOffset = range.getOffset(); - return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); - } - return false; - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#dispose() - */ - public void dispose() { - if (fProblemChangedListener != null) { - WebUI.getDefault().getProblemMarkerManager() - .removeListener(fProblemChangedListener); - fProblemChangedListener = null; - } - if (fRegistry != null && fUseNewRegistry) { - fRegistry.dispose(); - } - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#isLabelProperty(Object, String) - */ - public boolean isLabelProperty(Object element, String property) { - return true; - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#addListener(ILabelProviderListener) - */ - public void addListener(ILabelProviderListener listener) { - if (fListeners == null) { - fListeners = new ListenerList(); - } - fListeners.add(listener); - if (fProblemChangedListener == null) { - fProblemChangedListener = new IProblemChangedListener() { - public void problemsChanged(IResource[] changedResources, - boolean isMarkerChange) { - fireProblemsChanged(changedResources, isMarkerChange); - } - }; - WebUI.getDefault().getProblemMarkerManager() - .addListener(fProblemChangedListener); - } - } - - /* - * (non-Javadoc) - * - * @see IBaseLabelProvider#removeListener(ILabelProviderListener) - */ - public void removeListener(ILabelProviderListener listener) { - if (fListeners != null) { - fListeners.remove(listener); - if (fListeners.isEmpty() && fProblemChangedListener != null) { - WebUI.getDefault().getProblemMarkerManager() - .removeListener(fProblemChangedListener); - fProblemChangedListener = null; - } - } - } - - private void fireProblemsChanged(IResource[] changedResources, - boolean isMarkerChange) { - if (fListeners != null && !fListeners.isEmpty()) { - LabelProviderChangedEvent event = new ProblemsLabelChangedEvent( - this, changedResources, isMarkerChange); - Object[] listeners = fListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) { - ((ILabelProviderListener) listeners[i]) - .labelProviderChanged(event); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, - * org.eclipse.jface.viewers.IDecoration) - */ - public void decorate(Object element, IDecoration decoration) { - int adornmentFlags = computeAdornmentFlags(element); - if (adornmentFlags == ERRORTICK_ERROR) { - decoration.addOverlay(PHPUiImages.DESC_OVR_ERROR); - } else if (adornmentFlags == ERRORTICK_WARNING) { - decoration.addOverlay(PHPUiImages.DESC_OVR_WARNING); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java deleted file mode 100644 index 74abea1..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java +++ /dev/null @@ -1,813 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui.actions; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.Stack; -import java.util.StringTokenizer; -import java.util.TreeSet; - -//import net.sourceforge.phpdt.core.IJavaModel; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.filters.CustomFiltersDialog; -import net.sourceforge.phpdt.internal.ui.filters.FilterDescriptor; -import net.sourceforge.phpdt.internal.ui.filters.FilterMessages; -import net.sourceforge.phpdt.internal.ui.filters.NamePatternFilter; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ContributionItem; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -//import org.eclipse.jface.viewers.IContentProvider; -//import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IMemento; -//import org.eclipse.ui.IViewPart; -import org.eclipse.ui.actions.ActionGroup; - -/** - * Action group to add the filter action to a view part's tool bar menu. - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * @since 2.0 - */ -public class CustomFiltersActionGroup extends ActionGroup { - - class ShowFilterDialogAction extends Action { - ShowFilterDialogAction() { - setText(FilterMessages - .getString("OpenCustomFiltersDialogAction.text")); //$NON-NLS-1$ - setImageDescriptor(PHPUiImages.DESC_ELCL_FILTER); - setDisabledImageDescriptor(PHPUiImages.DESC_DLCL_FILTER); - } - - public void run() { - openDialog(); - } - } - - /** - * Menu contribution item which shows and lets check and uncheck filters. - * - * @since 3.0 - */ - class FilterActionMenuContributionItem extends ContributionItem { - - private int fItemNumber; - - private boolean fState; - - private String fFilterId; - - private String fFilterName; - - private CustomFiltersActionGroup fActionGroup; - - /** - * Constructor for FilterActionMenuContributionItem. - * - * @param actionGroup - * the action group - * @param filterId - * the id of the filter - * @param filterName - * the name of the filter - * @param state - * the initial state of the filter - * @param itemNumber - * the menu item index - */ - public FilterActionMenuContributionItem( - CustomFiltersActionGroup actionGroup, String filterId, - String filterName, boolean state, int itemNumber) { - super(filterId); - Assert.isNotNull(actionGroup); - Assert.isNotNull(filterId); - Assert.isNotNull(filterName); - fActionGroup = actionGroup; - fFilterId = filterId; - fFilterName = filterName; - fState = state; - fItemNumber = itemNumber; - } - - /* - * Overrides method from ContributionItem. - */ - public void fill(Menu menu, int index) { - MenuItem mi = new MenuItem(menu, SWT.CHECK, index); - mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$ - /* - * XXX: Don't set the image - would look bad because other menu - * items don't provide image XXX: Get working set specific image - * name from XML - would need to cache icons - */ - // mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET)); - mi.setSelection(fState); - mi.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - fState = !fState; - fActionGroup.setFilter(fFilterId, fState); - } - }); - } - - /* - * @see org.eclipse.jface.action.IContributionItem#isDynamic() - */ - public boolean isDynamic() { - return true; - } - } - - private static final String TAG_CUSTOM_FILTERS = "customFilters"; //$NON-NLS-1$ - - private static final String TAG_USER_DEFINED_PATTERNS_ENABLED = "userDefinedPatternsEnabled"; //$NON-NLS-1$ - - private static final String TAG_USER_DEFINED_PATTERNS = "userDefinedPatterns"; //$NON-NLS-1$ - - private static final String TAG_XML_DEFINED_FILTERS = "xmlDefinedFilters"; //$NON-NLS-1$ - - private static final String TAG_LRU_FILTERS = "lastRecentlyUsedFilters"; //$NON-NLS-1$ - - private static final String TAG_CHILD = "child"; //$NON-NLS-1$ - - private static final String TAG_PATTERN = "pattern"; //$NON-NLS-1$ - - private static final String TAG_FILTER_ID = "filterId"; //$NON-NLS-1$ - - private static final String TAG_IS_ENABLED = "isEnabled"; //$NON-NLS-1$ - - private static final String SEPARATOR = ","; //$NON-NLS-1$ - - private static final int MAX_FILTER_MENU_ENTRIES = 3; - - private static final String RECENT_FILTERS_GROUP_NAME = "recentFiltersGroup"; //$NON-NLS-1$ - - private StructuredViewer fViewer; - - private NamePatternFilter fPatternFilter; - - private Map fInstalledBuiltInFilters; - - private Map fEnabledFilterIds; - - private boolean fUserDefinedPatternsEnabled; - - private String[] fUserDefinedPatterns; - - /** - * Recently changed filter Ids stack with oldest on top (i.e. at the end). - * - * @since 3.0 - */ - private Stack fLRUFilterIdsStack; - - /** - * Handle to menu manager to dynamically update the last recently used - * filters. - * - * @since 3.0 - */ - private IMenuManager fMenuManager; - - /** - * The menu listener which dynamically updates the last recently used - * filters. - * - * @since 3.0 - */ - private IMenuListener fMenuListener; - - /** - * Filter Ids used in the last view menu invocation. - * - * @since 3.0 - */ - private String[] fFilterIdsUsedInLastViewMenu; - - private HashMap fFilterDescriptorMap; - - private String fTargetId; - - /** - * Creates a new CustomFiltersActionGroup. - * - * @param part - * the view part that owns this action group - * @param viewer - * the viewer to be filtered - */ -// public CustomFiltersActionGroup(IViewPart part, StructuredViewer viewer) { -// this(part.getViewSite().getId(), viewer); -// } - - /** - * Creates a new CustomFiltersActionGroup. - * - * @param ownerId - * the id of this action group's owner - * @param viewer - * the viewer to be filtered - */ - public CustomFiltersActionGroup(String ownerId, StructuredViewer viewer) { - Assert.isNotNull(ownerId); - Assert.isNotNull(viewer); - fTargetId = ownerId; - fViewer = viewer; - - fLRUFilterIdsStack = new Stack(); - - initializeWithPluginContributions(); - initializeWithViewDefaults(); - - installFilters(); - } - - /* - * Method declared on ActionGroup. - */ - public void fillActionBars(IActionBars actionBars) { - fillToolBar(actionBars.getToolBarManager()); - fillViewMenu(actionBars.getMenuManager()); - } - -// public String[] removeFiltersFor(Object parent, Object element, -// IContentProvider contentProvider) { -// String[] enabledFilters = getEnabledFilterIds(); -// Set newFilters = new HashSet(); -// for (int i = 0; i < enabledFilters.length; i++) { -// String filterName = enabledFilters[i]; -// ViewerFilter filter = (ViewerFilter) fInstalledBuiltInFilters -// .get(filterName); -// if (filter == null) -// newFilters.add(filterName); -// else if (isSelected(parent, element, contentProvider, filter)) -// newFilters.add(filterName); -// } -// if (newFilters.size() == enabledFilters.length) -// return new String[0]; -// return (String[]) newFilters.toArray(new String[newFilters.size()]); -// } - - public void setFilters(String[] newFilters) { - setEnabledFilterIds(newFilters); - updateViewerFilters(true); - } - -// private boolean isSelected(Object parent, Object element, -// IContentProvider contentProvider, ViewerFilter filter) { -// if (contentProvider instanceof ITreeContentProvider) { -// // the element and all its parents have to be selected -// ITreeContentProvider provider = (ITreeContentProvider) contentProvider; -// while (element != null && !(element instanceof IJavaModel)) { -// if (!filter.select(fViewer, parent, element)) -// return false; -// element = provider.getParent(element); -// } -// return true; -// } -// return filter.select(fViewer, parent, element); -// } - - /** - * Sets the enable state of the given filter. - * - * @param filterId - * the id of the filter - * @param state - * the filter state - */ - private void setFilter(String filterId, boolean state) { - // Renew filter id in LRU stack - fLRUFilterIdsStack.remove(filterId); - fLRUFilterIdsStack.add(0, filterId); - - fEnabledFilterIds.put(filterId, new Boolean(state)); - storeViewDefaults(); - - updateViewerFilters(true); - } - - private String[] getEnabledFilterIds() { - Set enabledFilterIds = new HashSet(fEnabledFilterIds.size()); - Iterator iter = fEnabledFilterIds.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String id = (String) entry.getKey(); - boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); - if (isEnabled) - enabledFilterIds.add(id); - } - return (String[]) enabledFilterIds.toArray(new String[enabledFilterIds - .size()]); - } - - private void setEnabledFilterIds(String[] enabledIds) { - Iterator iter = fEnabledFilterIds.keySet().iterator(); - while (iter.hasNext()) { - String id = (String) iter.next(); - fEnabledFilterIds.put(id, Boolean.FALSE); - } - for (int i = 0; i < enabledIds.length; i++) - fEnabledFilterIds.put(enabledIds[i], Boolean.TRUE); - } - - private void setUserDefinedPatterns(String[] patterns) { - fUserDefinedPatterns = patterns; - cleanUpPatternDuplicates(); - } - - /** - * Sets the recently changed filters. - * - * @param changeHistory - * the change history - * @since 3.0 - */ - private void setRecentlyChangedFilters(Stack changeHistory) { - Stack oldestFirstStack = new Stack(); - - int length = Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES); - for (int i = 0; i < length; i++) - oldestFirstStack.push(((FilterDescriptor) changeHistory.pop()) - .getId()); - - length = Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES - - oldestFirstStack.size()); - int NEWEST = 0; - for (int i = 0; i < length; i++) { - Object filter = fLRUFilterIdsStack.remove(NEWEST); - if (!oldestFirstStack.contains(filter)) - oldestFirstStack.push(filter); - } - fLRUFilterIdsStack = oldestFirstStack; - } - - private boolean areUserDefinedPatternsEnabled() { - return fUserDefinedPatternsEnabled; - } - - private void setUserDefinedPatternsEnabled(boolean state) { - fUserDefinedPatternsEnabled = state; - } - - private void fillToolBar(IToolBarManager tooBar) { - } - - /** - * Fills the given view menu with the entries managed by the group. - * - * @param viewMenu - * the menu to fill - */ - public void fillViewMenu(IMenuManager viewMenu) { - /* - * Don't change the separator group name. Using this name ensures that - * other filters get contributed to the same group. - */ - viewMenu.add(new Separator("filters")); //$NON-NLS-1$ - viewMenu.add(new GroupMarker(RECENT_FILTERS_GROUP_NAME)); - viewMenu.add(new ShowFilterDialogAction()); - - fMenuManager = viewMenu; - fMenuListener = new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - removePreviousLRUFilterActions(manager); - addLRUFilterActions(manager); - } - }; - fMenuManager.addMenuListener(fMenuListener); - } - - private void removePreviousLRUFilterActions(IMenuManager mm) { - if (fFilterIdsUsedInLastViewMenu == null) - return; - - for (int i = 0; i < fFilterIdsUsedInLastViewMenu.length; i++) - mm.remove(fFilterIdsUsedInLastViewMenu[i]); - } - - private void addLRUFilterActions(IMenuManager mm) { - if (fLRUFilterIdsStack.isEmpty()) { - fFilterIdsUsedInLastViewMenu = null; - return; - } - - SortedSet sortedFilters = new TreeSet(fLRUFilterIdsStack); - String[] recentlyChangedFilterIds = (String[]) sortedFilters - .toArray(new String[sortedFilters.size()]); - - fFilterIdsUsedInLastViewMenu = new String[recentlyChangedFilterIds.length]; - for (int i = 0; i < recentlyChangedFilterIds.length; i++) { - String id = recentlyChangedFilterIds[i]; - fFilterIdsUsedInLastViewMenu[i] = id; - boolean state = fEnabledFilterIds.containsKey(id) - && ((Boolean) fEnabledFilterIds.get(id)).booleanValue(); - FilterDescriptor filterDesc = (FilterDescriptor) fFilterDescriptorMap - .get(id); - if (filterDesc != null) { - IContributionItem item = new FilterActionMenuContributionItem( - this, id, filterDesc.getName(), state, i + 1); - mm.insertBefore(RECENT_FILTERS_GROUP_NAME, item); - } - } - } - - /* - * Method declared on ActionGroup. - */ - public void dispose() { - if (fMenuManager != null) - fMenuManager.removeMenuListener(fMenuListener); - super.dispose(); - } - - private void initializeWithPluginContributions() { - fUserDefinedPatterns = new String[0]; - fUserDefinedPatternsEnabled = false; - - FilterDescriptor[] filterDescs = FilterDescriptor - .getFilterDescriptors(fTargetId); - fFilterDescriptorMap = new HashMap(filterDescs.length); - fEnabledFilterIds = new HashMap(filterDescs.length); - for (int i = 0; i < filterDescs.length; i++) { - String id = filterDescs[i].getId(); - Boolean isEnabled = new Boolean(filterDescs[i].isEnabled()); - if (fEnabledFilterIds.containsKey(id)) - WebUI - .logErrorMessage("WARNING: Duplicate id for extension-point \"net.sourceforge.phpdt.ui.javaElementFilters\""); //$NON-NLS-1$ - fEnabledFilterIds.put(id, isEnabled); - fFilterDescriptorMap.put(id, filterDescs[i]); - } - } - - // ---------- viewer filter handling ---------- - - private void installFilters() { - fInstalledBuiltInFilters = new HashMap(fEnabledFilterIds.size()); - fPatternFilter = new NamePatternFilter(); - fPatternFilter.setPatterns(getUserAndBuiltInPatterns()); - fViewer.addFilter(fPatternFilter); - updateBuiltInFilters(); - } - - private void updateViewerFilters(boolean refresh) { - String[] patterns = getUserAndBuiltInPatterns(); - fPatternFilter.setPatterns(patterns); - fViewer.getControl().setRedraw(false); - updateBuiltInFilters(); - if (refresh) - fViewer.refresh(); - fViewer.getControl().setRedraw(true); - } - - private void updateBuiltInFilters() { - Set installedFilters = fInstalledBuiltInFilters.keySet(); - Set filtersToAdd = new HashSet(fEnabledFilterIds.size()); - Set filtersToRemove = new HashSet(fEnabledFilterIds.size()); - Iterator iter = fEnabledFilterIds.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String id = (String) entry.getKey(); - boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); - if (isEnabled && !installedFilters.contains(id)) - filtersToAdd.add(id); - else if (!isEnabled && installedFilters.contains(id)) - filtersToRemove.add(id); - } - - // Install the filters - FilterDescriptor[] filterDescs = FilterDescriptor - .getFilterDescriptors(fTargetId); - for (int i = 0; i < filterDescs.length; i++) { - String id = filterDescs[i].getId(); - // just to double check - id should denote a custom filter anyway - boolean isCustomFilter = filterDescs[i].isCustomFilter(); - if (isCustomFilter) { - if (filtersToAdd.contains(id)) { - ViewerFilter filter = filterDescs[i].createViewerFilter(); - if (filter != null) { - fViewer.addFilter(filter); - fInstalledBuiltInFilters.put(id, filter); - } - } - if (filtersToRemove.contains(id)) { - fViewer - .removeFilter((ViewerFilter) fInstalledBuiltInFilters - .get(id)); - fInstalledBuiltInFilters.remove(id); - } - } - } - } - - private String[] getUserAndBuiltInPatterns() { - List patterns = new ArrayList(fUserDefinedPatterns.length); - if (areUserDefinedPatternsEnabled()) - patterns.addAll(Arrays.asList(fUserDefinedPatterns)); - FilterDescriptor[] filterDescs = FilterDescriptor - .getFilterDescriptors(fTargetId); - for (int i = 0; i < filterDescs.length; i++) { - String id = filterDescs[i].getId(); - boolean isPatternFilter = filterDescs[i].isPatternFilter(); - Object isEnabled = fEnabledFilterIds.get(id); - if (isEnabled != null && isPatternFilter - && ((Boolean) isEnabled).booleanValue()) - patterns.add(filterDescs[i].getPattern()); - } - return (String[]) patterns.toArray(new String[patterns.size()]); - } - - // ---------- view kind/defaults persistency ---------- - - private void initializeWithViewDefaults() { - // get default values for view - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - - // XXX: can be removed once bug 22533 is fixed. - if (!store.contains(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE")))//$NON-NLS-1$ - return; - - // XXX: Uncomment once bug 22533 is fixed. - // if - // (!store.contains(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED))) - // return; - - fUserDefinedPatternsEnabled = store - .getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); - setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store - .getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), - SEPARATOR)); - - Iterator iter = fEnabledFilterIds.keySet().iterator(); - while (iter.hasNext()) { - String id = (String) iter.next(); - Boolean isEnabled = new Boolean(store.getBoolean(id)); - fEnabledFilterIds.put(id, isEnabled); - } - - fLRUFilterIdsStack.clear(); - String lruFilterIds = store.getString(TAG_LRU_FILTERS); - StringTokenizer tokenizer = new StringTokenizer(lruFilterIds, SEPARATOR); - while (tokenizer.hasMoreTokens()) { - String id = tokenizer.nextToken(); - if (fFilterDescriptorMap.containsKey(id) - && !fLRUFilterIdsStack.contains(id)) - fLRUFilterIdsStack.push(id); - } - } - - private void storeViewDefaults() { - // get default values for view - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - - // XXX: can be removed once bug 22533 is fixed. - store - .setValue( - getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE"), "storedViewPreferences");//$NON-NLS-1$//$NON-NLS-2$ - - store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), - fUserDefinedPatternsEnabled); - store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), - CustomFiltersDialog.convertToString(fUserDefinedPatterns, - SEPARATOR)); - - Iterator iter = fEnabledFilterIds.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String id = (String) entry.getKey(); - boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); - store.setValue(id, isEnabled); - } - - StringBuffer buf = new StringBuffer(fLRUFilterIdsStack.size() * 20); - iter = fLRUFilterIdsStack.iterator(); - while (iter.hasNext()) { - buf.append((String) iter.next()); - buf.append(SEPARATOR); - } - store.setValue(TAG_LRU_FILTERS, buf.toString()); - } - - private String getPreferenceKey(String tag) { - return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$ - } - - // ---------- view instance persistency ---------- - - /** - * Saves the state of the custom filters in a memento. - * - * @param memento - * the memento into which the state is saved - */ - public void saveState(IMemento memento) { - IMemento customFilters = memento.createChild(TAG_CUSTOM_FILTERS); - customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, new Boolean( - fUserDefinedPatternsEnabled).toString()); - saveUserDefinedPatterns(customFilters); - saveXmlDefinedFilters(customFilters); - saveLRUFilters(customFilters); - } - - private void saveXmlDefinedFilters(IMemento memento) { - if (fEnabledFilterIds != null && !fEnabledFilterIds.isEmpty()) { - IMemento xmlDefinedFilters = memento - .createChild(TAG_XML_DEFINED_FILTERS); - Iterator iter = fEnabledFilterIds.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String id = (String) entry.getKey(); - Boolean isEnabled = (Boolean) entry.getValue(); - IMemento child = xmlDefinedFilters.createChild(TAG_CHILD); - child.putString(TAG_FILTER_ID, id); - child.putString(TAG_IS_ENABLED, isEnabled.toString()); - } - } - } - - /** - * Stores the last recently used filter Ids into the given memento - * - * @param memento - * the memento into which to store the LRU filter Ids - * @since 3.0 - */ - private void saveLRUFilters(IMemento memento) { - if (fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) { - IMemento lruFilters = memento.createChild(TAG_LRU_FILTERS); - Iterator iter = fLRUFilterIdsStack.iterator(); - while (iter.hasNext()) { - String id = (String) iter.next(); - IMemento child = lruFilters.createChild(TAG_CHILD); - child.putString(TAG_FILTER_ID, id); - } - } - } - - private void saveUserDefinedPatterns(IMemento memento) { - if (fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) { - IMemento userDefinedPatterns = memento - .createChild(TAG_USER_DEFINED_PATTERNS); - for (int i = 0; i < fUserDefinedPatterns.length; i++) { - IMemento child = userDefinedPatterns.createChild(TAG_CHILD); - child.putString(TAG_PATTERN, fUserDefinedPatterns[i]); - } - } - } - - /** - * Restores the state of the filter actions from a memento. - *

- * Note: This method does not refresh the viewer. - *

- * - * @param memento - * the memento from which the state is restored - */ - public void restoreState(IMemento memento) { - if (memento == null) - return; - IMemento customFilters = memento.getChild(TAG_CUSTOM_FILTERS); - if (customFilters == null) - return; - String userDefinedPatternsEnabled = customFilters - .getString(TAG_USER_DEFINED_PATTERNS_ENABLED); - if (userDefinedPatternsEnabled == null) - return; - - fUserDefinedPatternsEnabled = Boolean.valueOf( - userDefinedPatternsEnabled).booleanValue(); - restoreUserDefinedPatterns(customFilters); - restoreXmlDefinedFilters(customFilters); - restoreLRUFilters(customFilters); - - updateViewerFilters(false); - } - - private void restoreUserDefinedPatterns(IMemento memento) { - IMemento userDefinedPatterns = memento - .getChild(TAG_USER_DEFINED_PATTERNS); - if (userDefinedPatterns != null) { - IMemento children[] = userDefinedPatterns.getChildren(TAG_CHILD); - String[] patterns = new String[children.length]; - for (int i = 0; i < children.length; i++) - patterns[i] = children[i].getString(TAG_PATTERN); - - setUserDefinedPatterns(patterns); - } else - setUserDefinedPatterns(new String[0]); - } - - private void restoreXmlDefinedFilters(IMemento memento) { - IMemento xmlDefinedFilters = memento.getChild(TAG_XML_DEFINED_FILTERS); - if (xmlDefinedFilters != null) { - IMemento[] children = xmlDefinedFilters.getChildren(TAG_CHILD); - for (int i = 0; i < children.length; i++) { - String id = children[i].getString(TAG_FILTER_ID); - Boolean isEnabled = new Boolean(children[i] - .getString(TAG_IS_ENABLED)); - fEnabledFilterIds.put(id, isEnabled); - } - } - } - - private void restoreLRUFilters(IMemento memento) { - IMemento lruFilters = memento.getChild(TAG_LRU_FILTERS); - fLRUFilterIdsStack.clear(); - if (lruFilters != null) { - IMemento[] children = lruFilters.getChildren(TAG_CHILD); - for (int i = 0; i < children.length; i++) { - String id = children[i].getString(TAG_FILTER_ID); - if (fFilterDescriptorMap.containsKey(id) - && !fLRUFilterIdsStack.contains(id)) - fLRUFilterIdsStack.push(id); - } - } - } - - private void cleanUpPatternDuplicates() { - if (!areUserDefinedPatternsEnabled()) - return; - List userDefinedPatterns = new ArrayList(Arrays - .asList(fUserDefinedPatterns)); - FilterDescriptor[] filters = FilterDescriptor - .getFilterDescriptors(fTargetId); - - for (int i = 0; i < filters.length; i++) { - if (filters[i].isPatternFilter()) { - String pattern = filters[i].getPattern(); - if (userDefinedPatterns.contains(pattern)) { - fEnabledFilterIds.put(filters[i].getId(), Boolean.TRUE); - boolean hasMore = true; - while (hasMore) - hasMore = userDefinedPatterns.remove(pattern); - } - } - } - fUserDefinedPatterns = (String[]) userDefinedPatterns - .toArray(new String[userDefinedPatterns.size()]); - setUserDefinedPatternsEnabled(fUserDefinedPatternsEnabled - && fUserDefinedPatterns.length > 0); - } - - // ---------- dialog related code ---------- - - private void openDialog() { - CustomFiltersDialog dialog = new CustomFiltersDialog(fViewer - .getControl().getShell(), fTargetId, - areUserDefinedPatternsEnabled(), fUserDefinedPatterns, - getEnabledFilterIds()); - - if (dialog.open() == Window.OK) { - setEnabledFilterIds(dialog.getEnabledFilterIds()); - setUserDefinedPatternsEnabled(dialog - .areUserDefinedPatternsEnabled()); - setUserDefinedPatterns(dialog.getUserDefinedPatterns()); - setRecentlyChangedFilters(dialog.getFilterDescriptorChangeHistory()); - - storeViewDefaults(); - - updateViewerFilters(true); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java deleted file mode 100644 index 14eae9f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java +++ /dev/null @@ -1,328 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui.actions; - -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.actions.ActionMessages; -import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilter; -import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilterAction; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -//import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.actions.ActionGroup; - -/** - * Action Group that contributes filter buttons for a view parts showing methods - * and fields. Contributed filters are: hide fields, hide static members and - * hide non-public members. - *

- * The action group installs a filter on a structured viewer. The filter is - * connected to the actions installed in the view part's toolbar menu and is - * updated when the state of the buttons changes. - * - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * @since 2.0 - */ -public class MemberFilterActionGroup extends ActionGroup { - - public static final int FILTER_NONPUBLIC = MemberFilter.FILTER_NONPUBLIC; - - public static final int FILTER_STATIC = MemberFilter.FILTER_STATIC; - - public static final int FILTER_FIELDS = MemberFilter.FILTER_FIELDS; - - private static final String TAG_HIDEFIELDS = "hidefields"; //$NON-NLS-1$ - - private static final String TAG_HIDESTATIC = "hidestatic"; //$NON-NLS-1$ - - private static final String TAG_HIDENONPUBLIC = "hidenonpublic"; //$NON-NLS-1$ - - private MemberFilterAction[] fFilterActions; - - private MemberFilter fFilter; - - private StructuredViewer fViewer; - - private String fViewerId; - - private boolean fInViewMenu; - - /** - * Creates a new MemberFilterActionGroup. - * - * @param viewer - * the viewer to be filtered - * @param viewerId - * a unique id of the viewer. Used as a key to to store the last - * used filter settings in the preference store - */ - public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) { - this(viewer, viewerId, false); - } - - /** - * Creates a new MemberFilterActionGroup. - * - * @param viewer - * the viewer to be filtered - * @param viewerId - * a unique id of the viewer. Used as a key to to store the last - * used filter settings in the preference store - * @param inViewMenu - * if true the actions are added to the view menu. - * If false they are added to the toobar. - * - * @since 2.1 - */ - public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, - boolean inViewMenu) { - fViewer = viewer; - fViewerId = viewerId; - fInViewMenu = inViewMenu; - - // get initial values - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - boolean doHideFields = store - .getBoolean(getPreferenceKey(FILTER_FIELDS)); - boolean doHideStatic = store - .getBoolean(getPreferenceKey(FILTER_STATIC)); - boolean doHidePublic = store - .getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); - - fFilter = new MemberFilter(); - if (doHideFields) - fFilter.addFilter(FILTER_FIELDS); - if (doHideStatic) - fFilter.addFilter(FILTER_STATIC); - if (doHidePublic) - fFilter.addFilter(FILTER_NONPUBLIC); - - // fields - String title = ActionMessages - .getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ - String helpContext = IJavaHelpContextIds.FILTER_FIELDS_ACTION; - MemberFilterAction hideFields = new MemberFilterAction(this, title, - FILTER_FIELDS, helpContext, doHideFields); - hideFields.setDescription(ActionMessages - .getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ - hideFields.setToolTipText(ActionMessages - .getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ - - // static - title = ActionMessages - .getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ - helpContext = IJavaHelpContextIds.FILTER_STATIC_ACTION; - MemberFilterAction hideStatic = new MemberFilterAction(this, title, - FILTER_STATIC, helpContext, doHideStatic); - hideStatic.setDescription(ActionMessages - .getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ - hideStatic.setToolTipText(ActionMessages - .getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ - - // non-public - title = ActionMessages - .getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ - helpContext = IJavaHelpContextIds.FILTER_PUBLIC_ACTION; - MemberFilterAction hideNonPublic = new MemberFilterAction(this, title, - FILTER_NONPUBLIC, helpContext, doHidePublic); - hideNonPublic - .setDescription(ActionMessages - .getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ - hideNonPublic.setToolTipText(ActionMessages - .getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ - - // order corresponds to order in toolbar - fFilterActions = new MemberFilterAction[] { hideFields, hideStatic, - hideNonPublic }; - - fViewer.addFilter(fFilter); - } - - private String getPreferenceKey(int filterProperty) { - return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$ - } - - /** - * Sets the member filters. - * - * @param filterProperty - * the filter to be manipulated. Valid values are - * FILTER_FIELDS, FILTER_PUBLIC, - * and FILTER_PRIVATE as defined by this action - * group - * @param set - * if true the given filter is installed. If - * false the given filter is removed . - */ - public void setMemberFilter(int filterProperty, boolean set) { - setMemberFilters(new int[] { filterProperty }, new boolean[] { set }, - true); - } - - private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, - boolean refresh) { - if (propertyKeys.length == 0) - return; - Assert.isTrue(propertyKeys.length == propertyValues.length); - - for (int i = 0; i < propertyKeys.length; i++) { - int filterProperty = propertyKeys[i]; - boolean set = propertyValues[i]; - if (set) { - fFilter.addFilter(filterProperty); - } else { - fFilter.removeFilter(filterProperty); - } - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - - for (int j = 0; j < fFilterActions.length; j++) { - int currProperty = fFilterActions[j].getFilterProperty(); - if (currProperty == filterProperty) { - fFilterActions[j].setChecked(set); - } - store.setValue(getPreferenceKey(currProperty), - hasMemberFilter(currProperty)); - } - } - if (refresh) { - fViewer.getControl().setRedraw(false); - BusyIndicator.showWhile(fViewer.getControl().getDisplay(), - new Runnable() { - public void run() { - fViewer.refresh(); - } - }); - fViewer.getControl().setRedraw(true); - } - } - - /** - * Returns true if the given filter is installed. - * - * @param filterProperty - * the filter to be tested. Valid values are - * FILTER_FIELDS, FILTER_PUBLIC, - * and FILTER_PRIVATE as defined by this action - * group - */ - public boolean hasMemberFilter(int filterProperty) { - return fFilter.hasFilter(filterProperty); - } - - /** - * Saves the state of the filter actions in a memento. - * - * @param memento - * the memento to which the state is saved - */ - public void saveState(IMemento memento) { - memento.putString(TAG_HIDEFIELDS, String - .valueOf(hasMemberFilter(FILTER_FIELDS))); - memento.putString(TAG_HIDESTATIC, String - .valueOf(hasMemberFilter(FILTER_STATIC))); - memento.putString(TAG_HIDENONPUBLIC, String - .valueOf(hasMemberFilter(FILTER_NONPUBLIC))); - } - - /** - * Restores the state of the filter actions from a memento. - *

- * Note: This method does not refresh the viewer. - *

- * - * @param memento - * the memento from which the state is restored - */ - public void restoreState(IMemento memento) { - setMemberFilters(new int[] { FILTER_FIELDS, FILTER_STATIC, - FILTER_NONPUBLIC }, new boolean[] { - Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)) - .booleanValue(), - Boolean.valueOf(memento.getString(TAG_HIDESTATIC)) - .booleanValue(), - Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)) - .booleanValue() }, false); - } - - /* - * (non-Javadoc) - * - * @see ActionGroup#fillActionBars(IActionBars) - */ - public void fillActionBars(IActionBars actionBars) { - contributeToToolBar(actionBars.getToolBarManager()); - }; - - /** - * Adds the filter actions to the given tool bar - * - * @param tbm - * the tool bar to which the actions are added - */ - public void contributeToToolBar(IToolBarManager tbm) { - if (fInViewMenu) - return; - tbm.add(fFilterActions[0]); // fields - tbm.add(fFilterActions[1]); // static - tbm.add(fFilterActions[2]); // public - } - - /** - * Adds the filter actions to the given menu manager. - * - * @param menu - * the menu manager to which the actions are added - * @since 2.1 - */ -// public void contributeToViewMenu(IMenuManager menu) { -// if (!fInViewMenu) -// return; -// final String filters = "filters"; //$NON-NLS-1$ -// if (menu.find(filters) != null) { -// menu.prependToGroup(filters, fFilterActions[0]); // fields -// menu.prependToGroup(filters, fFilterActions[1]); // static -// menu.prependToGroup(filters, fFilterActions[2]); // public -// } else { -// menu.add(fFilterActions[0]); // fields -// menu.add(fFilterActions[1]); // static -// menu.add(fFilterActions[2]); // public -// } -// } - - /* - * (non-Javadoc) - * - * @see ActionGroup#dispose() - */ - public void dispose() { - super.dispose(); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java deleted file mode 100644 index 577af0e..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui.actions; - -import net.sourceforge.phpdt.internal.ui.actions.ActionMessages; -import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; -import net.sourceforge.phpdt.ui.JavaUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jface.action.Action; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.WorkbenchException; - -/** - * Action to programmatically open a Java perspective. - * - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * @since 2.0 - */ -public class OpenPHPPerspectiveAction extends Action { - - /** - * Create a new OpenPHPPerspectiveAction. - */ - public OpenPHPPerspectiveAction() { - // WorkbenchHelp.setHelp(this, - // IJavaHelpContextIds.OPEN_JAVA_PERSPECTIVE_ACTION); - } - - public void run() { - IWorkbench workbench = WebUI.getDefault().getWorkbench(); - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - IAdaptable input; - if (page != null) - input = page.getInput(); - else - input = ResourcesPlugin.getWorkspace().getRoot(); - try { - workbench.showPerspective(JavaUI.ID_PERSPECTIVE, window, - input); - } catch (WorkbenchException e) { - ExceptionHandler - .handle( - e, - window.getShell(), - ActionMessages - .getString("OpenPHPPerspectiveAction.dialog.title"), //$NON-NLS-1$ - ActionMessages - .getString("OpenPHPPerspectiveAction.error.open_failed")); //$NON-NLS-1$ - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java deleted file mode 100644 index 4431f9d..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java +++ /dev/null @@ -1,737 +0,0 @@ -package net.sourceforge.phpdt.ui.text; - -/* - * (c) Copyright IBM Corp. 2000, 2001. - * All Rights Reserved. - */ - -import net.sourceforge.phpdt.internal.ui.text.FastJavaPartitionScanner; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaColorManager; -import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCodeScanner; -import net.sourceforge.phpeclipse.IPreferenceConstants; -import net.sourceforge.phpeclipse.phpeditor.php.HTMLPartitionScanner; -import net.sourceforge.phpeclipse.phpeditor.php.PHPCodeScanner; -import net.sourceforge.phpeclipse.phpeditor.php.PHPDocumentPartitioner; -import net.sourceforge.phpeclipse.phpeditor.php.PHPPartitionScanner; -import net.sourceforge.phpeclipse.phpeditor.php.SmartyCodeScanner; -import net.sourceforge.phpeclipse.phpeditor.php.SmartyDocCodeScanner; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IDocumentPartitioner; -//import org.eclipse.jface.text.rules.DefaultPartitioner; -import org.eclipse.jface.text.rules.FastPartitioner; -//import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; - -// -// import org.phpeclipse.phpdt.internal.ui.text.FastJavaPartitionScanner; -// import org.phpeclipse.phpdt.internal.ui.text.JavaColorManager; -// import org.phpeclipse.phpdt.internal.ui.text.JavaPartitionScanner; -// import org.phpeclipse.phpdt.internal.ui.text.SingleTokenJavaScanner; -// import org.phpeclipse.phpdt.internal.ui.text.php.JavaCodeScanner; -// import org.phpeclipse.phpdt.internal.ui.text.phpdoc.JavaDocScanner; - -/** - * Tools required to configure a Java text viewer. The color manager and all - * scanner exist only one time, i.e. the same instances are returned to all - * clients. Thus, clients share those tools. - *

- * This class may be instantiated; it is not intended to be subclassed. - *

- */ -public class JavaTextTools implements IPHPPartitions { - // private static final String[] TOKENS = { - // JSPScriptScanner.JSP_DEFAULT, - // JSPScriptScanner.JSP_BRACKET }; - private final static String[] LEGAL_CONTENT_TYPES = new String[] { - PHP_PHPDOC_COMMENT, PHP_MULTILINE_COMMENT, PHP_SINGLELINE_COMMENT, - PHP_STRING_DQ, PHP_STRING_SQ, PHP_STRING_HEREDOC }; - - // private static XMLPartitionScanner HTML_PARTITION_SCANNER = null; - - // private static FastJavaPartitionScanner PHP_PARTITION_SCANNER = null; - - private static HTMLPartitionScanner SMARTY_PARTITION_SCANNER = null; - - // private static XMLPartitionScanner XML_PARTITION_SCANNER = null; - - // private final static String[] TYPES= new String[] { - // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, - // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; - // private final static String[] TYPES = new String[] { - // IPHPPartitions.PHP_PARTITIONING, - // IPHPPartitions.PHP_PHPDOC_COMMENT, - // // IPHPPartitions.HTML, - // // IPHPPartitions.HTML_MULTILINE_COMMENT, - // IPHPPartitions.JAVASCRIPT, - // IPHPPartitions.CSS, - // IPHPPartitions.SMARTY, - // IPHPPartitions.SMARTY_MULTILINE_COMMENT }; - - /** - * This tools' preference listener. - */ - private class PreferenceListener implements IPropertyChangeListener, - Preferences.IPropertyChangeListener { - public void propertyChange(PropertyChangeEvent event) { - adaptToPreferenceChange(event); - } - - public void propertyChange(Preferences.PropertyChangeEvent event) { - adaptToPreferenceChange(new PropertyChangeEvent(event.getSource(), - event.getProperty(), event.getOldValue(), event - .getNewValue())); - } - }; - - // /** The color manager */ - private JavaColorManager colorManager; - - /** The PHP source code scanner */ - private PHPCodeScanner fCodeScanner; - - /** The PHP multiline comment scanner */ - private SingleTokenPHPScanner fMultilineCommentScanner; - - /** The Java singleline comment scanner */ - private SingleTokenPHPScanner fSinglelineCommentScanner; - - /** The PHP double quoted string scanner */ - // private SingleTokenPHPScanner fStringDQScanner; - /** The PHP single quoted string scanner */ - // private SingleTokenPHPScanner fStringSQScanner; - /** The PHPDoc scanner */ - private PHPDocCodeScanner fPHPDocScanner; - - /** The HTML scanner */ - // private HTMLCodeScanner fHTMLScanner; - /** The Smarty scanner */ - private SmartyCodeScanner fSmartyScanner; - - /** The SmartyDoc scanner */ - private SmartyDocCodeScanner fSmartyDocScanner; - - /** The Java partitions scanner. */ - private FastJavaPartitionScanner fPartitionScanner; - - /** The preference store */ - private IPreferenceStore fPreferenceStore; - - /** The XML Language text tools */ - private XMLTextTools xmlTextTools; - - /** - * The core preference store. - * - * @since 2.1 - */ - private Preferences fCorePreferenceStore; - - /** The preference change listener */ - private PreferenceListener fPreferenceListener = new PreferenceListener(); - - /** The JSP partitions scanner */ - private PHPPartitionScanner jspPartitionScanner = null; - - /** The JSP script subpartitions scanner */ - // private JSPScriptScanner jspScriptScanner; - /** The PHP plain text scanner */ - // private RuleBasedScanner jspTextScanner; - /** The PHP brackets scanner */ - // private RuleBasedScanner jspBracketScanner; - /** - * Creates a new Java text tools collection. - * - * @param store - * the preference store to initialize the text tools. The text - * tool instance installs a listener on the passed preference - * store to adapt itself to changes in the preference store. In - * general PreferenceConstants. - * getPreferenceStore() - * should be used to initialize the text tools. - * @param coreStore - * optional preference store to initialize the text tools. The - * text tool instance installs a listener on the passed - * preference store to adapt itself to changes in the preference - * store. - * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() - * @since 2.1 - */ - public JavaTextTools(IPreferenceStore store, Preferences coreStore) { - this(store, coreStore, true); - } - - /** - * Creates a new Java text tools collection. - * - * @param store - * the preference store to initialize the text tools. The text - * tool instance installs a listener on the passed preference - * store to adapt itself to changes in the preference store. In - * general PreferenceConstants. - * getPreferenceStore() - * shoould be used to initialize the text tools. - * @param coreStore - * optional preference store to initialize the text tools. The - * text tool instance installs a listener on the passed - * preference store to adapt itself to changes in the preference - * store. - * @param autoDisposeOnDisplayDispose - * if true the color manager automatically - * disposes all managed colors when the current display gets - * disposed and all calls to - * {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()}are - * ignored. - * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() - * @since 2.1 - */ - public JavaTextTools(IPreferenceStore store, Preferences coreStore, - boolean autoDisposeOnDisplayDispose) { - // super(store, TOKENS, ); - // REVISIT: preference store - xmlTextTools = new XMLTextTools(/*XMLPlugin*/WebUI.getDefault() - .getPreferenceStore()); - - colorManager = new JavaColorManager(autoDisposeOnDisplayDispose); - fPreferenceStore = store; - fPreferenceStore.addPropertyChangeListener(fPreferenceListener); - - fCorePreferenceStore = coreStore; - if (fCorePreferenceStore != null) - fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener); - - fCodeScanner = new PHPCodeScanner((JavaColorManager) colorManager, - store); - fMultilineCommentScanner = new SingleTokenPHPScanner( - (JavaColorManager) colorManager, store, - IPreferenceConstants.PHP_MULTILINE_COMMENT); - fSinglelineCommentScanner = new SingleTokenPHPScanner( - (JavaColorManager) colorManager, store, - IPreferenceConstants.PHP_SINGLELINE_COMMENT); - // fStringDQScanner = new SingleTokenPHPScanner((JavaColorManager) - // colorManager, store, IPreferenceConstants.PHP_STRING); - // fStringSQScanner = new SingleTokenPHPScanner((JavaColorManager) - // colorManager, store, IPreferenceConstants.PHP_STRING); - - fPHPDocScanner = new PHPDocCodeScanner((JavaColorManager) colorManager, - store); - // fHTMLScanner = new HTMLCodeScanner((JavaColorManager)fColorManager, - // store); - fSmartyScanner = new SmartyCodeScanner((JavaColorManager) colorManager, - store); - fSmartyDocScanner = new SmartyDocCodeScanner( - (JavaColorManager) colorManager, store); - - fPartitionScanner = new FastJavaPartitionScanner(); - - // jspScriptScanner = new JSPScriptScanner(); - // fPartitionScanner = new FastJavaPartitionScanner(); - // fPartitionScanner = new PHPPartitionScanner(); - - // jspBracketScanner = new RuleBasedScanner(); - // jspBracketScanner.setDefaultReturnToken(new - // Token(JSPScriptScanner.JSP_BRACKET)); - // jspTextScanner = new RuleBasedScanner(); - // jspTextScanner.setDefaultReturnToken(new - // Token(JSPScriptScanner.JSP_DEFAULT)); - } - - /** - * - */ - public XMLTextTools getXMLTextTools() { - return xmlTextTools; - } - - /** - * Disposes all the individual tools of this tools collection. - */ - public void dispose() { - - fCodeScanner = null; - fMultilineCommentScanner = null; - fSinglelineCommentScanner = null; - // fStringDQScanner = null; - // fStringSQScanner = null; - fPHPDocScanner = null; - // fPartitionScanner = null; - - if (colorManager != null) { - colorManager.dispose(); - colorManager = null; - } - - if (fPreferenceStore != null) { - fPreferenceStore.removePropertyChangeListener(fPreferenceListener); - fPreferenceStore = null; - - if (fCorePreferenceStore != null) { - fCorePreferenceStore - .removePropertyChangeListener(fPreferenceListener); - fCorePreferenceStore = null; - } - - fPreferenceListener = null; - } - } - - /** - * Returns the color manager which is used to manage any Java-specific - * colors needed for such things like syntax highlighting. - * - * @return the color manager to be used for Java text viewers - */ - public JavaColorManager getColorManager() { - return (JavaColorManager) colorManager; - } - - /** - * Returns a scanner which is configured to scan Java source code. - * - * @return a Java source code scanner - */ -// public RuleBasedScanner getCodeScanner() { -// return fCodeScanner; -// } - - /** - * Returns a scanner which is configured to scan Java multiline comments. - * - * @return a Java multiline comment scanner - * - * @since 2.0 - */ -// public RuleBasedScanner getMultilineCommentScanner() { -// return fMultilineCommentScanner; -// } - - /** - * Returns a scanner which is configured to scan HTML code. - * - * @return a HTML scanner - * - * @since 2.0 - */ - // public RuleBasedScanner getHTMLScanner() { - // return fHTMLScanner; - // } - /** - * Returns a scanner which is configured to scan Smarty code. - * - * @return a Smarty scanner - * - * @since 2.0 - */ -// public RuleBasedScanner getSmartyScanner() { -// return fSmartyScanner; -// } - - /** - * Returns a scanner which is configured to scan Smarty code. - * - * @return a Smarty scanner - * - * @since 2.0 - */ -// public RuleBasedScanner getSmartyDocScanner() { -// return fSmartyDocScanner; -// } - - /** - * Returns a scanner which is configured to scan Java singleline comments. - * - * @return a Java singleline comment scanner - * - * @since 2.0 - */ -// public RuleBasedScanner getSinglelineCommentScanner() { -// return fSinglelineCommentScanner; -// } - - /** - * Returns a scanner which is configured to scan Java strings. - * - * @return a Java string scanner - * - * @since 2.0 - */ - // public RuleBasedScanner getStringScanner() { - // return fStringDQScanner; - // } - /** - * Returns a scanner which is configured to scan JavaDoc compliant comments. - * Notes that the start sequence "/**" and the corresponding end sequence - * are part of the JavaDoc comment. - * - * @return a JavaDoc scanner - */ -// public RuleBasedScanner getJavaDocScanner() { -// return fPHPDocScanner; -// } - - /** - * Returns a scanner which is configured to scan Java-specific partitions, - * which are multi-line comments, JavaDoc comments, and regular Java source - * code. - * - * @return a Java partition scanner - */ - // public IPartitionTokenScanner getPartitionScanner() { - // return fPartitionScanner; - // } - /** - * Factory method for creating a PHP-specific document partitioner using - * this object's partitions scanner. This method is a convenience method. - * - * @return a newly created Java document partitioner - */ - public IDocumentPartitioner createDocumentPartitioner() { - return createDocumentPartitioner(".php"); - } - - /** - * Factory method for creating a PHP-specific document partitioner using - * this object's partitions scanner. This method is a convenience method. - * - * @return a newly created Java document partitioner - */ - public IDocumentPartitioner createDocumentPartitioner(String extension) { - - // String[] types = - // new String[] { - // FastJavaPartitionScanner.JAVA_DOC, - // FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, - // FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT, - // FastJavaPartitionScanner.JAVA_STRING }; - // - // return new DefaultPartitioner(getPartitionScanner(), types); - IDocumentPartitioner partitioner = null; - // System.out.println(extension); - if (extension.equalsIgnoreCase(".html") - || extension.equalsIgnoreCase(".htm")) { - // html - partitioner = createHTMLPartitioner(); - partitioner = createJSPPartitioner(); - } else if (extension.equalsIgnoreCase(".xml")) { - // xml - partitioner = createXMLPartitioner(); - // } else if (extension.equalsIgnoreCase(".js")) { - // // javascript - // partitioner = createJavaScriptPartitioner(); - // } else if (extension.equalsIgnoreCase(".css")) { - // // cascading style sheets - // partitioner = createCSSPartitioner(); - } else if (extension.equalsIgnoreCase(".tpl")) { - // smarty ? - partitioner = createSmartyPartitioner(); - // } else if (extension.equalsIgnoreCase(".inc")) { - // // php include files ? - // partitioner = createIncludePartitioner(); - } - - if (partitioner == null) { - partitioner = createJSPPartitioner(); - } - - return partitioner; - } - - /** - * Sets up the Java document partitioner for the given document for the - * given partitioning. - * - * @param document - * the document to be set up - * @param partitioning - * the document partitioning - * @param element - * TODO - * - * @since 3.0 - */ - // public void setupJavaDocumentPartitioner(IDocument document, String - // partitioning, Object element) { - // IDocumentPartitioner partitioner = createDocumentPartitioner(".php"); - // - // // if (document instanceof IDocumentExtension3) { - // // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // // extension3.setDocumentPartitioner(partitioning, partitioner); - // // } else { - // document.setDocumentPartitioner(partitioner); - // // } - // partitioner.connect(document); - // } - public void setupHTMLDocumentPartitioner(IDocument document, - String partitioning, Object element) { - IDocumentPartitioner partitioner = createDocumentPartitioner(".html"); - - // if (document instanceof IDocumentExtension3) { - // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // extension3.setDocumentPartitioner(partitioning, partitioner); - // } else { - document.setDocumentPartitioner(partitioner); - // } - partitioner.connect(document); - } - - public void setupSmartyDocumentPartitioner(IDocument document, - String partitioning, Object element) { - IDocumentPartitioner partitioner = createDocumentPartitioner(".tpl"); - - // if (document instanceof IDocumentExtension3) { - // IDocumentExtension3 extension3= (IDocumentExtension3) document; - // extension3.setDocumentPartitioner(partitioning, partitioner); - // } else { - document.setDocumentPartitioner(partitioner); - // } - partitioner.connect(document); - } - - /** - * Returns the names of the document position categories used by the - * document partitioners created by this object to manage their partition - * information. If the partitioners don't use document position categories, - * the returned result is null. - * - * @return the partition managing position categories or null - * if there is none - */ -// public String[] getPartitionManagingPositionCategories() { -// return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; -// } - - /** - * Determines whether the preference change encoded by the given event - * changes the behavior of one its contained components. - * - * @param event - * the event to be investigated - * @return true if event causes a behavioral change - * @since 2.0 - * @deprecated As of 3.0, replaced by - * {@link net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration#affectsTextPresentation(PropertyChangeEvent)} - */ - // public boolean affectsBehavior(PropertyChangeEvent event) { - // return fCodeScanner.affectsBehavior(event) - // || fMultilineCommentScanner.affectsBehavior(event) - // || fSinglelineCommentScanner.affectsBehavior(event) - // || fStringDQScanner.affectsBehavior(event) - // || fPHPDocScanner.affectsBehavior(event); - // } - /** - * Adapts the behavior of the contained components to the change encoded in - * the given event. - * - * @param event - * the event to which to adapt - * @since 2.0 - */ - protected void adaptToPreferenceChange(PropertyChangeEvent event) { - if (fCodeScanner.affectsBehavior(event)) - fCodeScanner.adaptToPreferenceChange(event); - if (fMultilineCommentScanner.affectsBehavior(event)) - fMultilineCommentScanner.adaptToPreferenceChange(event); - if (fSinglelineCommentScanner.affectsBehavior(event)) - fSinglelineCommentScanner.adaptToPreferenceChange(event); - // if (fStringDQScanner.affectsBehavior(event)) - // fStringDQScanner.adaptToPreferenceChange(event); - if (fPHPDocScanner.affectsBehavior(event)) - fPHPDocScanner.adaptToPreferenceChange(event); - // if (fHTMLScanner.affectsBehavior(event)) - // fHTMLScanner.adaptToPreferenceChange(event); - if (fSmartyScanner.affectsBehavior(event)) - fSmartyScanner.adaptToPreferenceChange(event); - if (fSmartyDocScanner.affectsBehavior(event)) - fSmartyDocScanner.adaptToPreferenceChange(event); - // if (XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event)) - // { - // XMLPlugin.getDefault().getXMLTextTools().adaptToPreferenceChange(event); - // } - } - - /** - * Return a partitioner for .html files. - */ - public IDocumentPartitioner createHTMLPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - return xmlTextTools.createXMLPartitioner(); - } - - // private static IDocumentPartitioner createIncludePartitioner() { - // // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // return new DefaultPartitioner(getPHPPartitionScanner(), - // FastJavaPartitionScanner.PHP_PARTITION_TYPES); - // - // } - - // private static IDocumentPartitioner createJavaScriptPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - - /** - * Return a partitioner for .php files. - */ - public IDocumentPartitioner createPHPPartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - return new /*DefaultPartitioner*/FastPartitioner(getPHPPartitionScanner(), - LEGAL_CONTENT_TYPES); - } - - private IDocumentPartitioner createJSPPartitioner() { - return new PHPDocumentPartitioner(getJSPPartitionScanner()); - // return new JSPDocumentPartitioner(getJSPPartitionScanner(), - // jspScriptScanner); - } - - /** - * - */ - // public IPartitionTokenScanner getJSPScriptScanner() { - // return jspScriptScanner; - // } - private IDocumentPartitioner createSmartyPartitioner() { - return new /*DefaultPartitioner*/FastPartitioner(getSmartyPartitionScanner(), - XMLTextTools.TYPES); - } - - private IDocumentPartitioner createXMLPartitioner() { - // return new DefaultPartitioner(getXMLPartitionScanner(), - // XMLTextTools.TYPES); - return xmlTextTools.createXMLPartitioner(); - } - - // private IDocumentPartitioner createCSSPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), - // XMLTextTools.TYPES); - // } - - /** - * Return a scanner for creating html partitions. - */ - // private static XMLPartitionScanner getHTMLPartitionScanner() { - // // if (HTML_PARTITION_SCANNER == null) - // // HTML_PARTITION_SCANNER = new - // HTMLPartitionScanner(IPHPPartitions.HTML_FILE); - // // return HTML_PARTITION_SCANNER;^ - // if (HTML_PARTITION_SCANNER == null) - // HTML_PARTITION_SCANNER = new XMLPartitionScanner(false); - // return HTML_PARTITION_SCANNER; - // } - /** - * Return a scanner for creating php partitions. - */ - private FastJavaPartitionScanner getPHPPartitionScanner() { - // if (PHP_PARTITION_SCANNER == null) - // PHP_PARTITION_SCANNER = new FastJavaPartitionScanner(); //new - // PHPPartitionScanner(IPHPPartitions.PHP_FILE); - // return PHP_PARTITION_SCANNER; - return fPartitionScanner; - } - - /** - * Returns a scanner which is configured to scan plain text in JSP. - * - * @return a JSP text scanner - */ - // public RuleBasedScanner getJSPTextScanner() { - // return jspTextScanner; - // } - /** - * Returns a scanner which is configured to scan plain text in JSP. - * - * @return a JSP text scanner - */ - // public RuleBasedScanner getJSPBracketScanner() { - // return jspBracketScanner; - // } - /** - * Return a scanner for creating smarty partitions. - */ - private static HTMLPartitionScanner getSmartyPartitionScanner() { - if (SMARTY_PARTITION_SCANNER == null) - SMARTY_PARTITION_SCANNER = new HTMLPartitionScanner( - IPHPPartitions.SMARTY_FILE); - return SMARTY_PARTITION_SCANNER; - } - - /** - * Return a scanner for creating xml partitions. - */ - // private static XMLPartitionScanner getXMLPartitionScanner() { - // // if (XML_PARTITION_SCANNER == null) - // // XML_PARTITION_SCANNER = new - // HTMLPartitionScanner(IPHPPartitions.XML_FILE); - // // return XML_PARTITION_SCANNER; - // if (XML_PARTITION_SCANNER == null) - // XML_PARTITION_SCANNER = new XMLPartitionScanner(false); - // return XML_PARTITION_SCANNER; - // } - private PHPPartitionScanner getJSPPartitionScanner() { - if (jspPartitionScanner == null) - jspPartitionScanner = new PHPPartitionScanner(); - return jspPartitionScanner; - } - - /** - * Sets up the Java document partitioner for the given document for the - * default partitioning. - * - * @param document - * the document to be set up - * @since 3.0 - */ - public void setupJavaDocumentPartitioner(IDocument document) { - setupJavaDocumentPartitioner(document, - IDocumentExtension3.DEFAULT_PARTITIONING); - } - - /** - * Sets up the Java document partitioner for the given document for the - * given partitioning. - * - * @param document - * the document to be set up - * @param partitioning - * the document partitioning - * @since 3.0 - */ - public void setupJavaDocumentPartitioner(IDocument document, - String partitioning) { - IDocumentPartitioner partitioner = createDocumentPartitioner(); - if (document instanceof IDocumentExtension3) { - IDocumentExtension3 extension3 = (IDocumentExtension3) document; - extension3.setDocumentPartitioner(partitioning, partitioner); - } else { - document.setDocumentPartitioner(partitioner); - } - partitioner.connect(document); - } - - /** - * Returns this text tool's preference store. - * - * @return the preference store - * @since 3.0 - */ - protected IPreferenceStore getPreferenceStore() { - return fPreferenceStore; - } - - /** - * Returns this text tool's core preference store. - * - * @return the core preference store - * @since 3.0 - */ -// protected Preferences getCorePreferenceStore() { -// return fCorePreferenceStore; -// } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java deleted file mode 100644 index 62ccb11..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java +++ /dev/null @@ -1,1150 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -package net.sourceforge.phpdt.ui.text; - -import java.util.Vector; - -import net.sourceforge.phpdt.core.JavaCore; -//import net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiMessages; -import net.sourceforge.phpdt.internal.ui.text.AbstractJavaScanner; -import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference; -import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaAnnotationHover; -import net.sourceforge.phpdt.internal.ui.text.JavaCompositeReconcilingStrategy; -import net.sourceforge.phpdt.internal.ui.text.JavaElementProvider; -import net.sourceforge.phpdt.internal.ui.text.JavaOutlineInformationControl; -import net.sourceforge.phpdt.internal.ui.text.JavaPresentationReconciler; -import net.sourceforge.phpdt.internal.ui.text.JavaReconciler; -import net.sourceforge.phpdt.internal.ui.text.java.JavaFormattingStrategy; -import net.sourceforge.phpdt.internal.ui.text.java.JavaStringAutoIndentStrategyDQ; -import net.sourceforge.phpdt.internal.ui.text.java.JavaStringAutoIndentStrategySQ; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaInformationProvider; -import net.sourceforge.phpdt.internal.ui.text.phpdoc.JavaDocAutoIndentStrategy; -import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCodeScanner; -import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCompletionProcessor; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpeclipse.IPreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.HTMLCompletionProcessor; -import net.sourceforge.phpeclipse.phpeditor.php.PHPAutoIndentStrategy; -import net.sourceforge.phpeclipse.phpeditor.php.PHPCodeScanner; -import net.sourceforge.phpeclipse.phpeditor.php.PHPCompletionProcessor; -import net.sourceforge.phpeclipse.phpeditor.php.PHPDocumentPartitioner; -import net.sourceforge.phpeclipse.phpeditor.php.PHPDoubleClickSelector; -import net.sourceforge.phpeclipse.phpeditor.php.PHPPartitionScanner; -import net.sourceforge.phpeclipse.ui.WebUI; -//import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLConfiguration; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLPartitionScanner; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.ITextDoubleClickStrategy; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.formatter.ContentFormatter; -import org.eclipse.jface.text.formatter.IContentFormatter; -import org.eclipse.jface.text.formatter.IFormattingStrategy; -import org.eclipse.jface.text.information.IInformationPresenter; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.InformationPresenter; -import org.eclipse.jface.text.presentation.IPresentationDamager; -import org.eclipse.jface.text.presentation.IPresentationReconciler; -import org.eclipse.jface.text.presentation.IPresentationRepairer; -import org.eclipse.jface.text.presentation.PresentationReconciler; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; -import org.eclipse.jface.text.rules.DefaultDamagerRepairer; -import org.eclipse.jface.text.rules.DefaultPartitioner; -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.text.rules.Token; -import org.eclipse.jface.text.source.IAnnotationHover; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Configuration for an SourceViewer which shows PHP code. - */ -public class PHPSourceViewerConfiguration extends SourceViewerConfiguration { - /** - * Preference key used to look up display tab width. - * - * @since 2.0 - */ - public final static String PREFERENCE_TAB_WIDTH = PreferenceConstants.EDITOR_TAB_WIDTH; - - /** - * Preference key for inserting spaces rather than tabs. - * - * @since 2.0 - */ - public final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; - - // public static final String HTML_DEFAULT = - // IPHPPartitionScannerConstants.HTML; - // IDocument.DEFAULT_CONTENT_TYPE; - // private JavaTextTools fJavaTextTools; - - private ITextEditor fTextEditor; - - /** - * The document partitioning. - * - * @since 3.0 - */ - private String fDocumentPartitioning; - - private ContentFormatter fFormatter; - - /** - * Single token scanner. - */ - static class SingleTokenScanner extends BufferedRuleBasedScanner { - public SingleTokenScanner(TextAttribute attribute) { - setDefaultReturnToken(new Token(attribute)); - } - }; - - /** - * The document partitioning. - * - * @since 3.0 - */ - // private String fDocumentPartitioning; - /** - * The Java source code scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fCodeScanner; - - /** - * The Java multi-line comment scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fMultilineCommentScanner; - - /** - * The Java single-line comment scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fSinglelineCommentScanner; - - /** - * The PHP double quoted string scanner - */ - private AbstractJavaScanner fStringDQScanner; - - /** - * The PHP single quoted string scanner - */ - private AbstractJavaScanner fStringSQScanner; - - /** - * The Javadoc scanner - * - * @since 3.0 - */ - private AbstractJavaScanner fJavaDocScanner; - - /** - * The preference store, can be read-only - * - * @since 3.0 - */ - private IPreferenceStore fPreferenceStore; - - /** - * The color manager - * - * @since 3.0 - */ - private IColorManager fColorManager; - - private XMLTextTools fXMLTextTools; - - private XMLConfiguration xmlConfiguration; - - /** - * Creates a new Java source viewer configuration for viewers in the given - * editor using the given preference store, the color manager and the - * specified document partitioning. - *

- * Creates a Java source viewer configuration in the new setup without text - * tools. Clients are allowed to call - * {@link JavaSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}and - * disallowed to call - * {@link JavaSourceViewerConfiguration#getPreferenceStore()}on the - * resulting Java source viewer configuration. - *

- * - * @param colorManager - * the color manager - * @param preferenceStore - * the preference store, can be read-only - * @param editor - * the editor in which the configured viewer(s) will reside - * @param partitioning - * the document partitioning for this configuration - * @since 3.0 - */ - public PHPSourceViewerConfiguration(IColorManager colorManager, - IPreferenceStore preferenceStore, ITextEditor editor, - String partitioning) { - fColorManager = colorManager; - fPreferenceStore = preferenceStore; - fTextEditor = editor; - fDocumentPartitioning = partitioning; - // fJavaTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - fXMLTextTools = new XMLTextTools(getPreferenceStore()); - //XMLPlugin.getDefault().getXMLTextTools(); - xmlConfiguration = new XMLConfiguration(fXMLTextTools); - fColorManager = colorManager; - fPreferenceStore = preferenceStore; - fTextEditor = editor; - fDocumentPartitioning = partitioning; - - initializeScanners(); - } - - /** - * Creates a new Java source viewer configuration for viewers in the given - * editor using the given Java tools. - * - * @param tools - * the Java text tools to be used - * @param editor - * the editor in which the configured viewer(s) will reside - * @see JavaTextTools - * @deprecated As of 3.0, replaced by - * {@link JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)} - */ - // public PHPSourceViewerConfiguration(JavaTextTools tools, PHPEditor - // editor, String partitioning) { - // fJavaTextTools = tools; - // fColorManager = tools.getColorManager(); - // fPreferenceStore = createPreferenceStore(); - // fDocumentPartitioning = partitioning; - // fCodeScanner = (AbstractJavaScanner) fJavaTextTools.getCodeScanner(); - // fMultilineCommentScanner = (AbstractJavaScanner) - // fJavaTextTools.getMultilineCommentScanner(); - // fSinglelineCommentScanner = (AbstractJavaScanner) - // fJavaTextTools.getSinglelineCommentScanner(); - // fStringDQScanner = (AbstractJavaScanner) - // fJavaTextTools.getStringScanner(); - // fJavaDocScanner = (AbstractJavaScanner) - // fJavaTextTools.getJavaDocScanner(); - // fTextEditor = editor; - // fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); - // xmlConfiguration = new XMLConfiguration(fXMLTextTools); - // } - /** - * Returns the color manager for this configuration. - * - * @return the color manager - */ - protected IColorManager getColorManager() { - return fColorManager; - } - - /** - * Initializes the scanners. - * - * @since 3.0 - */ - private void initializeScanners() { - // Assert.isTrue(isNewSetup()); - fCodeScanner = new PHPCodeScanner(getColorManager(), fPreferenceStore); - fMultilineCommentScanner = new SingleTokenPHPScanner(getColorManager(), - fPreferenceStore, IPreferenceConstants.PHP_MULTILINE_COMMENT); - fSinglelineCommentScanner = new SingleTokenPHPScanner( - getColorManager(), fPreferenceStore, - IPreferenceConstants.PHP_SINGLELINE_COMMENT); - // fStringDQScanner = new SingleTokenPHPScanner(getColorManager(), - // fPreferenceStore, IPreferenceConstants.PHP_STRING_DQ); - fStringDQScanner = new PHPStringDQCodeScanner(getColorManager(), - fPreferenceStore); - fStringSQScanner = new SingleTokenPHPScanner(getColorManager(), - fPreferenceStore, IPreferenceConstants.PHP_STRING_SQ); - fJavaDocScanner = new PHPDocCodeScanner(getColorManager(), - fPreferenceStore); - } - - /** - * Determines whether the preference change encoded by the given event - * changes the behavior of one of its contained components. - * - * @param event - * the event to be investigated - * @return true if event causes a behavioral change - * @since 3.0 - */ - public boolean affectsTextPresentation(PropertyChangeEvent event) { - return fCodeScanner.affectsBehavior(event) - || fMultilineCommentScanner.affectsBehavior(event) - || fSinglelineCommentScanner.affectsBehavior(event) - || fStringDQScanner.affectsBehavior(event) - || fStringSQScanner.affectsBehavior(event) - || fJavaDocScanner.affectsBehavior(event); - } - - /** - * Adapts the behavior of the contained components to the change encoded in - * the given event. - *

- * Clients are not allowed to call this method if the old setup with text - * tools is in use. - *

- * - * @param event - * the event to which to adapt - * @see JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, - * IPreferenceStore, ITextEditor, String) - * @since 3.0 - */ - public void handlePropertyChangeEvent(PropertyChangeEvent event) { - // Assert.isTrue(isNewSetup()); - if (fCodeScanner.affectsBehavior(event)) - fCodeScanner.adaptToPreferenceChange(event); - if (fMultilineCommentScanner.affectsBehavior(event)) - fMultilineCommentScanner.adaptToPreferenceChange(event); - if (fSinglelineCommentScanner.affectsBehavior(event)) - fSinglelineCommentScanner.adaptToPreferenceChange(event); - if (fStringDQScanner.affectsBehavior(event)) - fStringDQScanner.adaptToPreferenceChange(event); - if (fStringSQScanner.affectsBehavior(event)) - fStringSQScanner.adaptToPreferenceChange(event); - if (fJavaDocScanner.affectsBehavior(event)) - fJavaDocScanner.adaptToPreferenceChange(event); - } - - /* - * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) - */ - public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { - // if (fFormatter == null) { - // fFormatter = new ContentFormatter(); - // fFormattingStrategy = new HTMLFormattingStrategy(this, - // sourceViewer); - // fFormatter.setFormattingStrategy(fFormattingStrategy, HTML_DEFAULT); - // fFormatter.enablePartitionAwareFormatting(false); - // fFormatter.setPartitionManagingPositionCategories(getConfiguredContentTypes(null)); - // } - // return fFormatter; - if (fFormatter == null) { - // ContentFormatter - fFormatter = new ContentFormatter(); - IFormattingStrategy strategy = new JavaFormattingStrategy( - sourceViewer); - fFormatter.setFormattingStrategy(strategy, - IDocument.DEFAULT_CONTENT_TYPE); - fFormatter.enablePartitionAwareFormatting(false); - fFormatter - .setPartitionManagingPositionCategories(getPartitionManagingPositionCategories()); - } - return fFormatter; - } - - /** - * Returns the names of the document position categories used by the - * document partitioners created by this object to manage their partition - * information. If the partitioners don't use document position categories, - * the returned result is null. - * - * @return the partition managing position categories or null - * if there is none - */ - public String[] getPartitionManagingPositionCategories() { - return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; - } - - // /** - // * Returns the names of the document position categories used by the - // document - // * partitioners created by this object to manage their partition - // information. - // * If the partitioners don't use document position categories, the - // returned - // * result is null. - // * - // * @return the partition managing position categories or - // null - // * if there is none - // */ - // private String[] getPartitionManagingPositionCategories() { - // return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; - // } - public ITextEditor getEditor() { - return fTextEditor; - } - - /** - * Returns the preference store used by this configuration to initialize the - * individual bits and pieces. - * - * @return the preference store used to initialize this configuration - * - * @since 2.0 - */ - protected IPreferenceStore getPreferenceStore() { - return WebUI.getDefault().getPreferenceStore(); - } - - // /* (non-Javadoc) - // * Method declared on SourceViewerConfiguration - // */ - // public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - // return new PHPAnnotationHover(); - // } - /* - * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) - */ - public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER); - } - - /* - * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer) - * @since 3.0 - */ - public IAnnotationHover getOverviewRulerAnnotationHover( - ISourceViewer sourceViewer) { - return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER); - } - - public IAutoEditStrategy[] getAutoEditStrategies( - ISourceViewer sourceViewer, String contentType) { - IAutoEditStrategy strategy = new DefaultIndentLineAutoEditStrategy(); - if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(contentType) - || IPHPPartitions.PHP_MULTILINE_COMMENT.equals(contentType)) - strategy = new JavaDocAutoIndentStrategy( - getConfiguredDocumentPartitioning(sourceViewer)); - else if (IPHPPartitions.PHP_STRING_DQ.equals(contentType)) - strategy = new JavaStringAutoIndentStrategyDQ( - getConfiguredDocumentPartitioning(sourceViewer)); - else if (IPHPPartitions.PHP_STRING_SQ.equals(contentType)) - strategy = new JavaStringAutoIndentStrategySQ( - getConfiguredDocumentPartitioning(sourceViewer)); - else - strategy = (PHPDocumentPartitioner.PHP_TEMPLATE_DATA - .equals(contentType) - || PHPDocumentPartitioner.PHP_SCRIPT_CODE - .equals(contentType) - || IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) - || IPHPPartitions.PHP_PARTITIONING.equals(contentType) - || PHPPartitionScanner.PHP_SCRIPTING_AREA - .equals(contentType) ? new PHPAutoIndentStrategy() - : new DefaultIndentLineAutoEditStrategy()); - IAutoEditStrategy[] result = new IAutoEditStrategy[1]; - result[0] = strategy; - return result; - } - - /** - * Returns the PHP source code scanner for this configuration. - * - * @return the PHP source code scanner - */ - protected RuleBasedScanner getCodeScanner() { - return fCodeScanner; // fJavaTextTools.getCodeScanner(); - } - - /** - * Returns the Java multi-line comment scanner for this configuration. - * - * @return the Java multi-line comment scanner - * @since 2.0 - */ - protected RuleBasedScanner getMultilineCommentScanner() { - return fMultilineCommentScanner; - } - - /** - * Returns the Java single-line comment scanner for this configuration. - * - * @return the Java single-line comment scanner - * @since 2.0 - */ - protected RuleBasedScanner getSinglelineCommentScanner() { - return fSinglelineCommentScanner; - } - - /** - * Returns the PHP double quoted string scanner for this configuration. - * - * @return the PHP double quoted string scanner - */ - protected RuleBasedScanner getStringDQScanner() { - return fStringDQScanner; - } - - /** - * Returns the PHP single quoted string scanner for this configuration. - * - * @return the PHP single quoted string scanner - */ - protected RuleBasedScanner getStringSQScanner() { - return fStringSQScanner; - } - - /** - * Returns the HTML source code scanner for this configuration. - * - * @return the HTML source code scanner - */ - // protected RuleBasedScanner getHTMLScanner() { - // return fJavaTextTools.getHTMLScanner(); - // } - /** - * Returns the Smarty source code scanner for this configuration. - * - * @return the Smarty source code scanner - */ - // protected RuleBasedScanner getSmartyScanner() { - // return fJavaTextTools.getSmartyScanner(); - // } - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - public IReconciler getReconciler(ISourceViewer sourceViewer) { - - final ITextEditor editor = getEditor(); - if (editor != null && editor.isEditable()) { - - JavaCompositeReconcilingStrategy strategy = new JavaCompositeReconcilingStrategy( - editor, getConfiguredDocumentPartitioning(sourceViewer)); - JavaReconciler reconciler = new JavaReconciler(editor, strategy, - false); - reconciler.setIsIncrementalReconciler(false); - reconciler.setProgressMonitor(new NullProgressMonitor()); - reconciler.setDelay(500); - - return reconciler; - } - return null; - } - - /* - * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, - * String) - * @since 2.1 - */ - public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, - String contentType) { - JavaEditorTextHoverDescriptor[] hoverDescs = WebUI - .getDefault().getJavaEditorTextHoverDescriptors(); - int stateMasks[] = new int[hoverDescs.length]; - int stateMasksLength = 0; - for (int i = 0; i < hoverDescs.length; i++) { - if (hoverDescs[i].isEnabled()) { - int j = 0; - int stateMask = hoverDescs[i].getStateMask(); - while (j < stateMasksLength) { - if (stateMasks[j] == stateMask) - break; - j++; - } - if (j == stateMasksLength) - stateMasks[stateMasksLength++] = stateMask; - } - } - if (stateMasksLength == hoverDescs.length) - return stateMasks; - int[] shortenedStateMasks = new int[stateMasksLength]; - System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, - stateMasksLength); - return shortenedStateMasks; - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) - * @since 2.1 - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, - String contentType, int stateMask) { - JavaEditorTextHoverDescriptor[] hoverDescs = WebUI - .getDefault().getJavaEditorTextHoverDescriptors(); - int i = 0; - while (i < hoverDescs.length) { - if (hoverDescs[i].isEnabled() - && hoverDescs[i].getStateMask() == stateMask) - return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor()); - i++; - } - return null; - // if (fEditor != null) { - // IEditorInput editorInput = fEditor.getEditorInput(); - // if (editorInput instanceof IFileEditorInput) { - // try { - // IFile f = ((IFileEditorInput) editorInput).getFile(); - // return new PHPTextHover(f.getProject()); - // } catch (NullPointerException e) { - // // this exception occurs, if getTextHover is called by - // // preference pages ! - // } - // } - // } - // return new PHPTextHover(null); - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, - String contentType) { - return getTextHover(sourceViewer, contentType, - ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); - } - - /** - * Returns the SmartyDoc source code scanner for this configuration. - * - * @return the SmartyDoc source code scanner - */ - // protected RuleBasedScanner getSmartyDocScanner() { - // return fJavaTextTools.getSmartyDocScanner(); - // } - /** - * Returns the PHPDoc source code scanner for this configuration. - * - * @return the PHPDoc source code scanner - */ - protected RuleBasedScanner getPHPDocScanner() { - return fJavaDocScanner; // fJavaTextTools.getJavaDocScanner(); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, - PHPPartitionScanner.PHP_SCRIPTING_AREA, - - IPHPPartitions.HTML, IPHPPartitions.HTML_MULTILINE_COMMENT, - IPHPPartitions.PHP_PARTITIONING, - IPHPPartitions.PHP_SINGLELINE_COMMENT, - IPHPPartitions.PHP_MULTILINE_COMMENT, - IPHPPartitions.PHP_PHPDOC_COMMENT, - IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, - IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, - IPHPPartitions.CSS_MULTILINE_COMMENT, - IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, - IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, - - XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, - XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, - XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, - - XMLPartitionScanner.DTD_INTERNAL, - XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, - - PHPDocumentPartitioner.PHP_TEMPLATE_DATA, - PHPDocumentPartitioner.PHP_SCRIPT_CODE }; - } - - public String[] getConfiguredHTMLContentTypes() { - return new String[] { XMLPartitionScanner.XML_PI, - XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, - - XMLPartitionScanner.DTD_INTERNAL, - XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, }; - } - - public String[] getConfiguredPHPContentTypes() { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, - IPHPPartitions.PHP_PARTITIONING, - IPHPPartitions.PHP_SINGLELINE_COMMENT, - IPHPPartitions.PHP_MULTILINE_COMMENT, - IPHPPartitions.PHP_PHPDOC_COMMENT, - IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, - IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, - IPHPPartitions.CSS_MULTILINE_COMMENT, - IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, - IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, }; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer) - * @since 3.0 - */ - public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { - if (fDocumentPartitioning != null) - return fDocumentPartitioning; - return super.getConfiguredDocumentPartitioning(sourceViewer); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - ContentAssistant assistant = new ContentAssistant(); - IContentAssistProcessor processor = new HTMLCompletionProcessor( - getEditor()); - assistant - .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - assistant.setContentAssistProcessor(processor, IPHPPartitions.HTML); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.HTML_MULTILINE_COMMENT); - - assistant.setContentAssistProcessor(processor, IPHPPartitions.CSS); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.CSS_MULTILINE_COMMENT); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.JAVASCRIPT); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.JS_MULTILINE_COMMENT); - // TODO define special smarty partition content assist - assistant.setContentAssistProcessor(processor, IPHPPartitions.SMARTY); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.SMARTY_MULTILINE_COMMENT); - - assistant.setContentAssistProcessor(processor, - PHPDocumentPartitioner.PHP_TEMPLATE_DATA); - String[] htmlTypes = getConfiguredHTMLContentTypes(); - for (int i = 0; i < htmlTypes.length; i++) { - assistant.setContentAssistProcessor(processor, htmlTypes[i]); - } - processor = new PHPCompletionProcessor(getEditor()); - - assistant.setContentAssistProcessor(processor, - PHPDocumentPartitioner.PHP_SCRIPT_CODE); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.PHP_PARTITIONING); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.PHP_STRING_DQ); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.PHP_STRING_SQ); - assistant.setContentAssistProcessor(processor, - IPHPPartitions.PHP_STRING_HEREDOC); - - assistant.setContentAssistProcessor(new PHPDocCompletionProcessor( - getEditor()), IPHPPartitions.PHP_PHPDOC_COMMENT); - // assistant.enableAutoActivation(true); - // assistant.setAutoActivationDelay(500); - // assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); - // ContentAssistPreference.configure(assistant, getPreferenceStore()); - // assistant.setContextInformationPopupOrientation( - // ContentAssistant.CONTEXT_INFO_ABOVE); - // assistant.setContextInformationPopupBackground( - // PHPEditorEnvironment.getPHPColorProvider().getColor( - // new RGB(150, 150, 0))); - ContentAssistPreference.configure(assistant, getPreferenceStore()); - assistant - .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); - assistant - .setInformationControlCreator(getInformationControlCreator(sourceViewer)); - return assistant; - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - // public String getDefaultPrefix(ISourceViewer sourceViewer, String - // contentType) { - // return (PHPPartitionScanner.PHP.equals(contentType) ? "//" : null); - // //$NON-NLS-1$ - // // return (IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) ? "//" : - // null); //$NON-NLS-1$ - // } - /* - * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) - * @since 2.0 - */ - public String[] getDefaultPrefixes(ISourceViewer sourceViewer, - String contentType) { - return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public ITextDoubleClickStrategy getDoubleClickStrategy( - ISourceViewer sourceViewer, String contentType) { - return new PHPDoubleClickSelector(); - } - - /* - * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) - */ - public String[] getIndentPrefixes(ISourceViewer sourceViewer, - String contentType) { - Vector vector = new Vector(); - // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces - final IPreferenceStore preferences = WebUI.getDefault() - .getPreferenceStore(); - int tabWidth = preferences.getInt(JavaCore.FORMATTER_TAB_SIZE); - boolean useSpaces = getPreferenceStore().getBoolean(SPACES_FOR_TABS); - for (int i = 0; i <= tabWidth; i++) { - StringBuffer prefix = new StringBuffer(); - if (useSpaces) { - for (int j = 0; j + i < tabWidth; j++) - prefix.append(' '); - if (i != 0) - prefix.append('\t'); - } else { - for (int j = 0; j < i; j++) - prefix.append(' '); - if (i != tabWidth) - prefix.append('\t'); - } - vector.add(prefix.toString()); - } - vector.add(""); //$NON-NLS-1$ - return (String[]) vector.toArray(new String[vector.size()]); - } - - /** - * @return true iff the new setup without text tools is in - * use. - * - * @since 3.0 - */ - // private boolean isNewSetup() { - // return fJavaTextTools == null; - // } - /** - * Creates and returns a preference store which combines the preference - * stores from the text tools and which is read-only. - * - * @return the read-only preference store - * @since 3.0 - */ - // private IPreferenceStore createPreferenceStore() { - // Assert.isTrue(!isNewSetup()); - // IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); - // if (fJavaTextTools.getCorePreferenceStore() == null) - // return new ChainedPreferenceStore(new IPreferenceStore[] { - // fJavaTextTools.getPreferenceStore(), generalTextStore }); - // - // return new ChainedPreferenceStore(new IPreferenceStore[] { - // fJavaTextTools.getPreferenceStore(), - // new PreferencesAdapter(fJavaTextTools.getCorePreferenceStore()), - // generalTextStore }); - // } - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public IPresentationReconciler getPresentationReconciler( - ISourceViewer sourceViewer) { - // PHPColorProvider provider = - // PHPEditorEnvironment.getPHPColorProvider(); - // JavaColorManager provider = - // PHPEditorEnvironment.getPHPColorProvider(); - PresentationReconciler phpReconciler = new JavaPresentationReconciler(); - phpReconciler - .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - // DefaultDamagerRepairer dr = new - // DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - // reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.HTML); - // reconciler.setRepairer(dr, IPHPPartitions.HTML); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.CSS); - // reconciler.setRepairer(dr, IPHPPartitions.CSS); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.JAVASCRIPT); - // reconciler.setRepairer(dr, IPHPPartitions.JAVASCRIPT); - // dr = new DefaultDamagerRepairer(getHTMLScanner()); - // reconciler.setDamager(dr, IPHPPartitions.JS_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.JS_MULTILINE_COMMENT); - // DefaultDamagerRepairer phpDR = new - // DefaultDamagerRepairer(getSmartyScanner()); - // phpReconciler.setDamager(phpDR, IPHPPartitions.SMARTY); - // phpReconciler.setRepairer(phpDR, IPHPPartitions.SMARTY); - // phpDR = new DefaultDamagerRepairer(getSmartyDocScanner()); - // phpReconciler.setDamager(phpDR, - // IPHPPartitions.SMARTY_MULTILINE_COMMENT); - // phpReconciler.setRepairer(phpDR, - // IPHPPartitions.SMARTY_MULTILINE_COMMENT); - // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new - // TextAttribute(fJavaTextTools.getColorManager().getColor( - // PHPColorProvider.MULTI_LINE_COMMENT)))); - // reconciler.setDamager(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); - // reconciler.setRepairer(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); - - DefaultDamagerRepairer phpDR = new DefaultDamagerRepairer( - getCodeScanner()); - phpReconciler.setDamager(phpDR, IDocument.DEFAULT_CONTENT_TYPE); - phpReconciler.setRepairer(phpDR, IDocument.DEFAULT_CONTENT_TYPE); - - phpDR = new DefaultDamagerRepairer(getCodeScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PARTITIONING); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PARTITIONING); - - phpDR = new DefaultDamagerRepairer(getPHPDocScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); - - phpDR = new DefaultDamagerRepairer(getStringDQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_DQ); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_DQ); - phpDR = new DefaultDamagerRepairer(getStringSQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_SQ); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_SQ); - phpDR = new DefaultDamagerRepairer(getStringDQScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); - phpDR = new DefaultDamagerRepairer(getSinglelineCommentScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); - phpDR = new DefaultDamagerRepairer(getMultilineCommentScanner()); - phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); - phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); - - PresentationReconciler reconciler = new PresentationReconciler(); - reconciler - .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - // - // JavaTextTools jspTextTools = - // PHPeclipsePlugin.getDefault().getJavaTextTools(); - DefaultDamagerRepairer dr = new DefaultDamagerRepairer( - getPHPDocScanner());// jspTextTools.getJSPTextScanner()); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - - // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new - // TextAttribute(fJavaTextTools.getColorManager().getColor( - // PHPColorProvider.PHPDOC_TAG))));//jspTextTools.getJSPBracketScanner()); - // reconciler.setDamager(dr, JSPScriptScanner.JSP_BRACKET); - // reconciler.setRepairer(dr, JSPScriptScanner.JSP_BRACKET); - - // xml partitions - configureEmbeddedPresentationReconciler(reconciler, xmlConfiguration - .getPresentationReconciler(sourceViewer), xmlConfiguration - .getConfiguredContentTypes(sourceViewer), - PHPDocumentPartitioner.PHP_TEMPLATE_DATA); - - // java partitions - configureEmbeddedPresentationReconciler(reconciler, phpReconciler, - getConfiguredPHPContentTypes(), - PHPDocumentPartitioner.PHP_SCRIPT_CODE); - - return reconciler; - } - - private void configureEmbeddedPresentationReconciler( - PresentationReconciler reconciler, - IPresentationReconciler embedded, String[] types, String defaultType) { - for (int i = 0; i < types.length; i++) { - String type = types[i]; - - IPresentationDamager damager = embedded.getDamager(type); - IPresentationRepairer repairer = embedded.getRepairer(type); - - if (type == IDocument.DEFAULT_CONTENT_TYPE) { - type = defaultType; - } - - reconciler.setDamager(damager, type); - reconciler.setRepairer(repairer, type); - } - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - public int getTabWidth(ISourceViewer sourceViewer) { - return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH); - } - - /* - * (non-Javadoc) Method declared on SourceViewerConfiguration - */ - // public ITextHover getTextHover(ISourceViewer sourceViewer, String - // contentType) { - // if (fEditor != null) { - // IEditorInput editorInput = fEditor.getEditorInput(); - // if (editorInput instanceof IFileEditorInput) { - // try { - // IFile f = ((IFileEditorInput) editorInput).getFile(); - // return new PHPTextHover(f.getProject()); - // } catch (NullPointerException e) { - // // this exception occurs, if getTextHover is called by preference pages - // ! - // } - // } - // } - // return new PHPTextHover(null); - // } - /* - * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer) - * @since 2.0 - */ - public IInformationControlCreator getInformationControlCreator( - ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { -//incastrix - // return new DefaultInformationControl(parent, SWT.NONE, -// new HTMLTextPresenter(true)); - return new DefaultInformationControl(parent, - new HTMLTextPresenter(true)); - // return new HoverBrowserControl(parent); - } - }; - } - - /* - * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) - * @since 2.0 - */ - public IInformationPresenter getInformationPresenter( - ISourceViewer sourceViewer) { - InformationPresenter presenter = new InformationPresenter( - getInformationPresenterControlCreator(sourceViewer)); - presenter - .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - IInformationProvider provider = new JavaInformationProvider(getEditor()); - presenter.setInformationProvider(provider, - IDocument.DEFAULT_CONTENT_TYPE); - presenter.setInformationProvider(provider, - IPHPPartitions.PHP_PHPDOC_COMMENT); - // presenter.setInformationProvider(provider, - // IPHPPartitions.JAVA_CHARACTER); - presenter.setSizeConstraints(60, 10, true, true); - return presenter; - } - - /* - * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) - * @since 2.0 - */ - // public IInformationPresenter getInformationPresenter(ISourceViewer - // sourceViewer) { - // InformationPresenter presenter= new - // InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); - // IInformationProvider provider= new JavaInformationProvider(getEditor()); - // presenter.setInformationProvider(provider, - // IDocument.DEFAULT_CONTENT_TYPE); - // presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); - // presenter.setSizeConstraints(60, 10, true, true); - // return presenter; - // } - /** - * Returns the information presenter control creator. The creator is a - * factory creating the presenter controls for the given source viewer. This - * implementation always returns a creator for - * DefaultInformationControl instances. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an information control creator - * @since 2.1 - */ - private IInformationControlCreator getInformationPresenterControlCreator( - ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE; - int style = SWT.V_SCROLL | SWT.H_SCROLL; - return new DefaultInformationControl(parent, shellStyle, style, - new HTMLTextPresenter(false)); - // return new HoverBrowserControl(parent); - } - }; - } - - /** - * Returns the outline presenter control creator. The creator is a factory - * creating outline presenter controls for the given source viewer. This - * implementation always returns a creator for - * JavaOutlineInformationControl instances. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an information control creator - * @since 2.1 - */ - private IInformationControlCreator getOutlinePresenterControlCreator( - ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE; - int treeStyle = SWT.V_SCROLL | SWT.H_SCROLL; - return new JavaOutlineInformationControl(parent, shellStyle, - treeStyle); - } - }; - } - - /** - * Returns the outline presenter which will determine and shown information - * requested for the current cursor position. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param doCodeResolve - * a boolean which specifies whether code resolve should be used - * to compute the Java element - * @return an information presenter - * @since 2.1 - */ - public IInformationPresenter getOutlinePresenter( - ISourceViewer sourceViewer, boolean doCodeResolve) { - InformationPresenter presenter = new InformationPresenter( - getOutlinePresenterControlCreator(sourceViewer)); - presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); - IInformationProvider provider = new JavaElementProvider(getEditor(), - doCodeResolve); - presenter.setInformationProvider(provider, - IDocument.DEFAULT_CONTENT_TYPE); - presenter.setInformationProvider(provider, - PHPDocumentPartitioner.PHP_SCRIPT_CODE); - presenter.setInformationProvider(provider, - IPHPPartitions.PHP_PARTITIONING); - presenter.setInformationProvider(provider, - IPHPPartitions.PHP_PHPDOC_COMMENT); - presenter.setInformationProvider(provider, - IPHPPartitions.SMARTY_MULTILINE_COMMENT); - presenter.setInformationProvider(provider, IPHPPartitions.HTML); - presenter.setInformationProvider(provider, - IPHPPartitions.HTML_MULTILINE_COMMENT); - presenter.setSizeConstraints(40, 20, true, false); - return presenter; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java deleted file mode 100644 index 58fd483..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java +++ /dev/null @@ -1,476 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui.wizards; - -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.IPackageFragmentRoot; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -// incastrix -//import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo; -import net.sourceforge.phpeclipse.ui.StatusInfo; -import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider; -import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.views.contentoutline.ContentOutline; - -/** - * Wizard page that acts as a base class for wizard pages that create new Java - * elements. The class provides a input field for source folders (called - * container in this class) and API to validate the enter source folder name. - * - * @since 2.0 - */ -public abstract class NewContainerWizardPage extends NewElementWizardPage { - - /** Id of the container field */ - protected static final String CONTAINER = "NewContainerWizardPage.container"; //$NON-NLS-1$ - - /** The status of the last validation. */ - protected IStatus fContainerStatus; - - private StringButtonDialogField fContainerDialogField; - - /* - * package fragment root corresponding to the input type (can be null) - */ - private IPackageFragmentRoot fCurrRoot; - - private IWorkspaceRoot fWorkspaceRoot; - - /** - * Create a new NewContainerWizardPage - * - * @param name - * the wizard page's name - */ - public NewContainerWizardPage(String name) { - super(name); - fWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - ContainerFieldAdapter adapter = new ContainerFieldAdapter(); - - fContainerDialogField = new StringButtonDialogField(adapter); - fContainerDialogField.setDialogFieldListener(adapter); - fContainerDialogField.setLabelText(NewWizardMessages - .getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ - fContainerDialogField.setButtonLabel(NewWizardMessages - .getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ - - fContainerStatus = new StatusInfo(); - fCurrRoot = null; - } - - /** - * Initializes the source folder field with a valid package fragement root. - * The package fragement root is computed from the given Java element. - * - * @param elem - * the Java element used to compute the initial package fragment - * root used as the source folder - */ -// protected void initContainerPage(IJavaElement elem) { -// //IPackageFragmentRoot initRoot = null; -// // if (elem != null) { -// // initRoot= JavaModelUtil.getPackageFragmentRoot(elem); -// // if (initRoot == null || initRoot.isArchive()) { -// // IJavaProject jproject= elem.getJavaProject(); -// // if (jproject != null) { -// // try { -// // initRoot= null; -// // if (jproject.exists()) { -// // IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); -// // for (int i= 0; i < roots.length; i++) { -// // if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { -// // initRoot= roots[i]; -// // break; -// // } -// // } -// // } -// // } catch (JavaModelException e) { -// // PHPeclipsePlugin.log(e); -// // } -// // if (initRoot == null) { -// // initRoot= jproject.getPackageFragmentRoot(jproject.getResource()); -// // } -// // } -// // } -// // } -// // setPackageFragmentRoot(initRoot, true); -// } - - /** - * Utility method to inspect a selection to find a Java element. - * - * @param selection - * the selection to be inspected - * @return a Java element to be used as the initial selection, or - * null, if no Java element exists in the given - * selection - */ - protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { - IJavaElement jelem = null; - if (selection != null && !selection.isEmpty()) { - Object selectedElement = selection.getFirstElement(); - if (selectedElement instanceof IAdaptable) { - IAdaptable adaptable = (IAdaptable) selectedElement; - - jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class); - if (jelem == null) { - IResource resource = (IResource) adaptable - .getAdapter(IResource.class); - if (resource != null - && resource.getType() != IResource.ROOT) { - while (jelem == null - && resource.getType() != IResource.PROJECT) { - resource = resource.getParent(); - jelem = (IJavaElement) resource - .getAdapter(IJavaElement.class); - } - if (jelem == null) { - jelem = JavaCore.create(resource); // java project - } - } - } - } - } - if (jelem == null) { - IWorkbenchPart part = WebUI.getActivePage() - .getActivePart(); - if (part instanceof ContentOutline) { - part = WebUI.getActivePage().getActiveEditor(); - } - - if (part instanceof IViewPartInputProvider) { - Object elem = ((IViewPartInputProvider) part) - .getViewPartInput(); - if (elem instanceof IJavaElement) { - jelem = (IJavaElement) elem; - } - } - } - - if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) { - try { - IJavaProject[] projects = JavaCore.create(getWorkspaceRoot()) - .getJavaProjects(); - if (projects.length == 1) { - jelem = projects[0]; - } - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); - } - } - return jelem; - } - - /** - * Returns the recommended maximum width for text fields (in pixels). This - * method requires that createContent has been called before this method is - * call. Subclasses may override to change the maximum width for text - * fields. - * - * @return the recommended maximum width for text fields. - */ - protected int getMaxFieldWidth() { - return convertWidthInCharsToPixels(40); - } - - /** - * Creates the necessary controls (label, text field and browse button) to - * edit the source folder location. The method expects that the parent - * composite uses a GridLayout as its layout manager and that - * the grid layout has at least 3 columns. - * - * @param parent - * the parent composite - * @param nColumns - * the number of columns to span. This number must be greater or - * equal three - */ - protected void createContainerControls(Composite parent, int nColumns) { - fContainerDialogField.doFillIntoGrid(parent, nColumns); - LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), - getMaxFieldWidth()); - } - - /** - * Sets the focus to the source folder's text field. - */ -// protected void setFocusOnContainer() { -// fContainerDialogField.setFocus(); -// } - - // -------- ContainerFieldAdapter -------- - - private class ContainerFieldAdapter implements IStringButtonAdapter, - IDialogFieldListener { - - // -------- IStringButtonAdapter - public void changeControlPressed(DialogField field) { - //containerChangeControlPressed(field); - } - - // -------- IDialogFieldListener - public void dialogFieldChanged(DialogField field) { - containerDialogFieldChanged(field); - } - } - -// private void containerChangeControlPressed(DialogField field) { -// // take the current jproject as init element of the dialog -// // IPackageFragmentRoot root= getPackageFragmentRoot(); -// // root= chooseSourceContainer(root); -// // if (root != null) { -// // setPackageFragmentRoot(root, true); -// // } -// } - - private void containerDialogFieldChanged(DialogField field) { - if (field == fContainerDialogField) { - fContainerStatus = containerChanged(); - } - // tell all others - //handleFieldChanged(CONTAINER); - } - - // ----------- validation ---------- - - /** - * This method is a hook which gets called after the source folder's text - * input field has changed. This default implementation updates the model - * and returns an error status. The underlying model is only valid if the - * returned status is OK. - * - * @return the model's error status - */ - protected IStatus containerChanged() { - StatusInfo status = new StatusInfo(); - - fCurrRoot = null; - String str = getPackageFragmentRootText(); - if (str.length() == 0) { - status - .setError(NewWizardMessages - .getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ - return status; - } - IPath path = new Path(str); - IResource res = fWorkspaceRoot.findMember(path); - if (res != null) { - int resType = res.getType(); - if (resType == IResource.PROJECT || resType == IResource.FOLDER) { - IProject proj = res.getProject(); - if (!proj.isOpen()) { - status - .setError(NewWizardMessages - .getFormattedString( - "NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ - return status; - } - //IJavaProject jproject = JavaCore.create(proj); - // fCurrRoot= jproject.getPackageFragmentRoot(res); - // if (res.exists()) { - // try { - // if (!proj.hasNature(JavaCore.NATURE_ID)) { - // if (resType == IResource.PROJECT) { - // status.setError(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); - // //$NON-NLS-1$ - // } else { - // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); - // //$NON-NLS-1$ - // } - // return status; - // } - // } catch (CoreException e) { - // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); - // //$NON-NLS-1$ - // } - // if (!jproject.isOnClasspath(fCurrRoot)) { - // status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", - // str)); //$NON-NLS-1$ - // } - // if (fCurrRoot.isArchive()) { - // status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", - // str)); //$NON-NLS-1$ - // return status; - // } - // } - return status; - } else { - status.setError(NewWizardMessages.getFormattedString( - "NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ - return status; - } - } else { - status.setError(NewWizardMessages.getFormattedString( - "NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ - return status; - } - } - - // -------- update message ---------------- - - /** - * Hook method that gets called when a field on this page has changed. For - * this page the method gets called when the source folder field changes. - *

- * Every sub type is responsible to call this method when a field on its - * page has changed. Subtypes override (extend) the method to add - * verification when a own field has a dependency to an other field. For - * example the class name input must be verified again when the package - * field changes (check for duplicated class names). - * - * @param fieldName - * The name of the field that has changed (field id). For the - * source folder the field id is CONTAINER - */ -// protected void handleFieldChanged(String fieldName) { -// } - - // ---- get ---------------- - - /** - * Returns the workspace root. - * - * @return the workspace root - */ - protected IWorkspaceRoot getWorkspaceRoot() { - return fWorkspaceRoot; - } - - /** - * Returns the IPackageFragmentRoot that corresponds to the - * current value of the source folder field. - * - * @return the IPackageFragmentRoot or null if the current - * source folder value is not a valid package fragment root - * - */ - public IPackageFragmentRoot getPackageFragmentRoot() { - return fCurrRoot; - } - - /** - * Returns the current text of source folder text field. - * - * @return the text of the source folder text field - */ - public String getPackageFragmentRootText() { - return fContainerDialogField.getText(); - } - - /** - * Sets the current source folder (model and text field) to the given - * package fragment root. - * - * @param canBeModified - * if false the source folder field can not be - * changed by the user. If true the field is - * editable - */ - // public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean - // canBeModified) { - // fCurrRoot= root; - // String str= (root == null) ? "" : - // root.getPath().makeRelative().toString(); //$NON-NLS-1$ - // fContainerDialogField.setText(str); - // fContainerDialogField.setEnabled(canBeModified); - // } - // ------------- choose source container dialog - // private IPackageFragmentRoot chooseSourceContainer(IJavaElement - // initElement) { - // Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, - // IJavaProject.class }; - // TypedElementSelectionValidator validator= new - // TypedElementSelectionValidator(acceptedClasses, false) { - // public boolean isSelectedValid(Object element) { - // try { - // if (element instanceof IJavaProject) { - // IJavaProject jproject= (IJavaProject)element; - // IPath path= jproject.getProject().getFullPath(); - // return (jproject.findPackageFragmentRoot(path) != null); - // } else if (element instanceof IPackageFragmentRoot) { - // return (((IPackageFragmentRoot)element).getKind() == - // IPackageFragmentRoot.K_SOURCE); - // } - // return true; - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation - // } - // return false; - // } - // }; - // - // acceptedClasses= new Class[] { IJavaModel.class, - // IPackageFragmentRoot.class, IJavaProject.class }; - // ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { - // public boolean select(Viewer viewer, Object parent, Object element) { - // if (element instanceof IPackageFragmentRoot) { - // try { - // return (((IPackageFragmentRoot)element).getKind() == - // IPackageFragmentRoot.K_SOURCE); - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation - // return false; - // } - // } - // return super.select(viewer, parent, element); - // } - // }; - // - // StandardJavaElementContentProvider provider= new - // StandardJavaElementContentProvider(); - // ILabelProvider labelProvider= new - // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); - // ElementTreeSelectionDialog dialog= new - // ElementTreeSelectionDialog(getShell(), labelProvider, provider); - // dialog.setValidator(validator); - // dialog.setSorter(new JavaElementSorter()); - // dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); - // //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); - // //$NON-NLS-1$ - // dialog.addFilter(filter); - // dialog.setInput(JavaCore.create(fWorkspaceRoot)); - // dialog.setInitialSelection(initElement); - // - // if (dialog.open() == ElementTreeSelectionDialog.OK) { - // Object element= dialog.getFirstResult(); - // if (element instanceof IJavaProject) { - // IJavaProject jproject= (IJavaProject)element; - // return jproject.getPackageFragmentRoot(jproject.getProject()); - // } else if (element instanceof IPackageFragmentRoot) { - // return (IPackageFragmentRoot)element; - // } - // return null; - // } - // return null; - // } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java deleted file mode 100644 index 50de3fe..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java +++ /dev/null @@ -1,1957 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpdt.ui.wizards; - -import java.util.ArrayList; -import java.util.List; - -import net.sourceforge.phpdt.core.Flags; -import net.sourceforge.phpdt.core.IBuffer; -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IPackageFragment; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.ToolFactory; -import net.sourceforge.phpdt.core.compiler.IScanner; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -//incastrix -//import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo; -import net.sourceforge.phpeclipse.ui.StatusInfo; -import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; -//import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -//import net.sourceforge.phpdt.internal.corext.template.php.Templates; -//import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.util.SWTUtil; -import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IListAdapter; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.Separator; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; -import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringDialogField; -//import net.sourceforge.phpdt.ui.CodeGeneration; -//import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; -//import org.eclipse.jface.preference.IPreferenceStore; -//import org.eclipse.jface.text.BadLocationException; -//import org.eclipse.jface.text.templates.Template; -//import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.viewers.LabelProvider; -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; - -/** - * The class NewTypeWizardPage contains controls and validation - * routines for a 'New Type WizardPage'. Implementors decide which components to - * add and to enable. Implementors can also customize the validation code. - * NewTypeWizardPage is intended to serve as base class of all - * wizards that create types like applets, servlets, classes, interfaces, etc. - *

- * See NewClassWizardPage or NewInterfaceWizardPage - * for an example usage of NewTypeWizardPage. - *

- * - * @see net.sourceforge.phpdt.ui.wizards.NewClassWizardPage - * @see net.sourceforge.phpdt.ui.wizards.NewInterfaceWizardPage - * - * @since 2.0 - */ -public abstract class NewTypeWizardPage extends NewContainerWizardPage { - - /** - * Class used in stub creation routines to add needed imports to a - * compilation unit. - */ - // public static class ImportsManager { - // - // private IImportsStructure fImportsStructure; - // - // /* package */ ImportsManager(IImportsStructure structure) { - // fImportsStructure= structure; - // } - // - // /* package */ IImportsStructure getImportsStructure() { - // return fImportsStructure; - // } - // - // /** - // * Adds a new import declaration that is sorted in the existing imports. - // * If an import already exists or the import would conflict with another - // import - // * of an other type with the same simple name the import is not added. - // * - // * @param qualifiedTypeName The fully qualified name of the type to import - // * (dot separated) - // * @return Returns the simple type name that can be used in the code or - // the - // * fully qualified type name if an import conflict prevented the import - // */ - // public String addImport(String qualifiedTypeName) { - // return fImportsStructure.addImport(qualifiedTypeName); - // } - // } - /** - * Public access flag. See The Java Virtual Machine Specification for more - * details. - */ - public int F_PUBLIC = Flags.AccPublic; - - /** - * Private access flag. See The Java Virtual Machine Specification for more - * details. - */ - public int F_PRIVATE = Flags.AccPrivate; - - /** - * Protected access flag. See The Java Virtual Machine Specification for - * more details. - */ - public int F_PROTECTED = Flags.AccProtected; - - /** - * Static access flag. See The Java Virtual Machine Specification for more - * details. - */ - public int F_STATIC = Flags.AccStatic; - - /** - * Final access flag. See The Java Virtual Machine Specification for more - * details. - */ - public int F_FINAL = Flags.AccFinal; - - /** - * Abstract property flag. See The Java Virtual Machine Specification for - * more details. - */ - // public int F_ABSTRACT = Flags.AccAbstract; - private final static String PAGE_NAME = "NewTypeWizardPage"; //$NON-NLS-1$ - - /** Field ID of the package input field */ - protected final static String PACKAGE = PAGE_NAME + ".package"; //$NON-NLS-1$ - - /** Field ID of the eclosing type input field */ - protected final static String ENCLOSING = PAGE_NAME + ".enclosing"; //$NON-NLS-1$ - - /** Field ID of the enclosing type checkbox */ - protected final static String ENCLOSINGSELECTION = ENCLOSING + ".selection"; //$NON-NLS-1$ - - /** Field ID of the type name input field */ - protected final static String TYPENAME = PAGE_NAME + ".typename"; //$NON-NLS-1$ - - /** Field ID of the super type input field */ - protected final static String SUPER = PAGE_NAME + ".superclass"; //$NON-NLS-1$ - - /** Field ID of the super interfaces input field */ - protected final static String INTERFACES = PAGE_NAME + ".interfaces"; //$NON-NLS-1$ - - /** Field ID of the modifier checkboxes */ - protected final static String MODIFIERS = PAGE_NAME + ".modifiers"; //$NON-NLS-1$ - - /** Field ID of the method stubs checkboxes */ - protected final static String METHODS = PAGE_NAME + ".methods"; //$NON-NLS-1$ - - private class InterfacesListLabelProvider extends LabelProvider { - - private Image fInterfaceImage; - - public InterfacesListLabelProvider() { - super(); - fInterfaceImage = PHPUiImages.get(PHPUiImages.IMG_OBJS_INTERFACE); - } - - public Image getImage(Object element) { - return fInterfaceImage; - } - } - - private StringButtonStatusDialogField fPackageDialogField; - - private SelectionButtonDialogField fEnclosingTypeSelection; - - private StringButtonDialogField fEnclosingTypeDialogField; - - private boolean fCanModifyPackage; - - private boolean fCanModifyEnclosingType; - - private IPackageFragment fCurrPackage; - - // private IType fCurrEnclosingType; - private StringDialogField fTypeNameDialogField; - - private StringButtonDialogField fSuperClassDialogField; - - private ListDialogField fSuperInterfacesDialogField; - - // private IType fSuperClass; - - private SelectionButtonDialogFieldGroup fAccMdfButtons; - - private SelectionButtonDialogFieldGroup fOtherMdfButtons; - - private IType fCreatedType; - - protected IStatus fEnclosingTypeStatus; - - protected IStatus fPackageStatus; - - protected IStatus fTypeNameStatus; - - // protected IStatus fSuperClassStatus; - protected IStatus fModifierStatus; - - // protected IStatus fSuperInterfacesStatus; - - private boolean fIsClass; - - private int fStaticMdfIndex; - - private final int PUBLIC_INDEX = 0, DEFAULT_INDEX = 1, PRIVATE_INDEX = 2, - PROTECTED_INDEX = 3; - - private final int ABSTRACT_INDEX = 0, FINAL_INDEX = 1; - - /** - * Creates a new NewTypeWizardPage - * - * @param isClass - * true if a new class is to be created; otherwise - * an interface is to be created - * @param pageName - * the wizard page's name - */ - public NewTypeWizardPage(boolean isClass, String pageName) { - super(pageName); - fCreatedType = null; - - fIsClass = isClass; - - TypeFieldsAdapter adapter = new TypeFieldsAdapter(); - - fPackageDialogField = new StringButtonStatusDialogField(adapter); - fPackageDialogField.setDialogFieldListener(adapter); - fPackageDialogField.setLabelText(NewWizardMessages - .getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ - fPackageDialogField.setButtonLabel(NewWizardMessages - .getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ - fPackageDialogField.setStatusWidthHint(NewWizardMessages - .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ - - fEnclosingTypeSelection = new SelectionButtonDialogField(SWT.CHECK); - fEnclosingTypeSelection.setDialogFieldListener(adapter); - fEnclosingTypeSelection.setLabelText(NewWizardMessages - .getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ - - fEnclosingTypeDialogField = new StringButtonDialogField(adapter); - fEnclosingTypeDialogField.setDialogFieldListener(adapter); - fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages - .getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ - - fTypeNameDialogField = new StringDialogField(); - fTypeNameDialogField.setDialogFieldListener(adapter); - fTypeNameDialogField.setLabelText(NewWizardMessages - .getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ - - fSuperClassDialogField = new StringButtonDialogField(adapter); - fSuperClassDialogField.setDialogFieldListener(adapter); - fSuperClassDialogField.setLabelText(NewWizardMessages - .getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ - fSuperClassDialogField.setButtonLabel(NewWizardMessages - .getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ - - String[] addButtons = new String[] { - /* 0 */ - NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ - /* 1 */ - null, - /* 2 */ - NewWizardMessages - .getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ - }; - fSuperInterfacesDialogField = new ListDialogField(adapter, addButtons, - new InterfacesListLabelProvider()); - fSuperInterfacesDialogField.setDialogFieldListener(adapter); - String interfaceLabel = fIsClass ? NewWizardMessages - .getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ - fSuperInterfacesDialogField.setLabelText(interfaceLabel); - fSuperInterfacesDialogField.setRemoveButtonIndex(2); - - String[] buttonNames1 = new String[] { - /* 0 == PUBLIC_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ - /* 1 == DEFAULT_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ - /* 2 == PRIVATE_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ - /* 3 == PROTECTED_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ - }; - fAccMdfButtons = new SelectionButtonDialogFieldGroup(SWT.RADIO, - buttonNames1, 4); - fAccMdfButtons.setDialogFieldListener(adapter); - fAccMdfButtons.setLabelText(NewWizardMessages - .getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ - fAccMdfButtons.setSelection(0, true); - - String[] buttonNames2; - if (fIsClass) { - buttonNames2 = new String[] { - /* 0 == ABSTRACT_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ - /* 1 == FINAL_INDEX */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ - /* 2 */ - NewWizardMessages - .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ - }; - fStaticMdfIndex = 2; // index of the static checkbox is 2 - } else { - buttonNames2 = new String[] { NewWizardMessages - .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ - }; - fStaticMdfIndex = 0; // index of the static checkbox is 0 - } - - fOtherMdfButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, - buttonNames2, 4); - fOtherMdfButtons.setDialogFieldListener(adapter); - - fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); - fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); - fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); - - fPackageStatus = new StatusInfo(); - fEnclosingTypeStatus = new StatusInfo(); - - fCanModifyPackage = true; - fCanModifyEnclosingType = true; - updateEnableState(); - - fTypeNameStatus = new StatusInfo(); - // fSuperClassStatus= new StatusInfo(); - // fSuperInterfacesStatus= new StatusInfo(); - fModifierStatus = new StatusInfo(); - } - - /** - * Initializes all fields provided by the page with a given selection. - * - * @param elem - * the selection used to intialize this page or - * null - * if no selection was available - */ - protected void initTypePage(IJavaElement elem) { - String initSuperclass = "java.lang.Object"; //$NON-NLS-1$ - ArrayList initSuperinterfaces = new ArrayList(5); - - IPackageFragment pack = null; - IType enclosingType = null; - - if (elem != null) { - // evaluate the enclosing type - pack = (IPackageFragment) elem - .getAncestor(IJavaElement.PACKAGE_FRAGMENT); - IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE); - if (typeInCU != null) { - if (typeInCU.getCompilationUnit() != null) { - enclosingType = typeInCU; - } - } else { - ICompilationUnit cu = (ICompilationUnit) elem - .getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) { - // enclosingType= cu.findPrimaryType(); - } - } - - // try { - // IType type= null; - // if (elem.getElementType() == IJavaElement.TYPE) { - // type= (IType)elem; - // if (type.exists()) { - // String superName= JavaModelUtil.getFullyQualifiedName(type); - // if (type.isInterface()) { - // initSuperinterfaces.add(superName); - // } else { - // initSuperclass= superName; - // } - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // ignore this exception now - // } - } - - setPackageFragment(pack, true); - // setEnclosingType(enclosingType, true); - setEnclosingTypeSelection(false, true); - - setTypeName("", true); //$NON-NLS-1$ - setSuperClass(initSuperclass, true); - setSuperInterfaces(initSuperinterfaces, true); - } - - // -------- UI Creation --------- - - /** - * Creates a separator line. Expects a GridLayout with at - * least 1 column. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createSeparator(Composite composite, int nColumns) { - (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid( - composite, nColumns, convertHeightInCharsToPixels(1)); - } - - /** - * Creates the controls for the package name field. Expects a - * GridLayout with at least 4 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createPackageControls(Composite composite, int nColumns) { - fPackageDialogField.doFillIntoGrid(composite, nColumns); - LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), - getMaxFieldWidth()); - LayoutUtil.setHorizontalGrabbing(fPackageDialogField - .getTextControl(null)); - } - - /** - * Creates the controls for the enclosing type name field. Expects a - * GridLayout with at least 4 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createEnclosingTypeControls(Composite composite, int nColumns) { - // #6891 - Composite tabGroup = new Composite(composite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.marginWidth = 0; - layout.marginHeight = 0; - tabGroup.setLayout(layout); - - fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); - - Control c = fEnclosingTypeDialogField.getTextControl(composite); - GridData gd = new GridData(GridData.FILL_HORIZONTAL); - gd.widthHint = getMaxFieldWidth(); - gd.horizontalSpan = 2; - c.setLayoutData(gd); - - Button button = fEnclosingTypeDialogField.getChangeControl(composite); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.heightHint = SWTUtil.getButtonHeightHint(button); - gd.widthHint = SWTUtil.getButtonWidthHint(button); - button.setLayoutData(gd); - } - - /** - * Creates the controls for the type name field. Expects a - * GridLayout with at least 2 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createTypeNameControls(Composite composite, int nColumns) { - fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); - DialogField.createEmptySpace(composite); - - LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), - getMaxFieldWidth()); - } - - /** - * Creates the controls for the modifiers radio/ceckbox buttons. Expects a - * GridLayout with at least 3 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createModifierControls(Composite composite, int nColumns) { - LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), - 1); - - Control control = fAccMdfButtons.getSelectionButtonsGroup(composite); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = nColumns - 2; - control.setLayoutData(gd); - - DialogField.createEmptySpace(composite); - - DialogField.createEmptySpace(composite); - - control = fOtherMdfButtons.getSelectionButtonsGroup(composite); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = nColumns - 2; - control.setLayoutData(gd); - - DialogField.createEmptySpace(composite); - } - - /** - * Creates the controls for the superclass name field. Expects a - * GridLayout with at least 3 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createSuperClassControls(Composite composite, int nColumns) { - fSuperClassDialogField.doFillIntoGrid(composite, nColumns); - LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), - getMaxFieldWidth()); - } - - /** - * Creates the controls for the superclass name field. Expects a - * GridLayout with at least 3 columns. - * - * @param composite - * the parent composite - * @param nColumns - * number of columns to span - */ - protected void createSuperInterfacesControls(Composite composite, - int nColumns) { - fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); - GridData gd = (GridData) fSuperInterfacesDialogField.getListControl( - null).getLayoutData(); - if (fIsClass) { - gd.heightHint = convertHeightInCharsToPixels(3); - } else { - gd.heightHint = convertHeightInCharsToPixels(6); - } - gd.grabExcessVerticalSpace = false; - gd.widthHint = getMaxFieldWidth(); - } - - /** - * Sets the focus on the type name input field. - */ - protected void setFocus() { - fTypeNameDialogField.setFocus(); - } - - // -------- TypeFieldsAdapter -------- - - private class TypeFieldsAdapter implements IStringButtonAdapter, - IDialogFieldListener, IListAdapter { - - // -------- IStringButtonAdapter - public void changeControlPressed(DialogField field) { - // typePageChangeControlPressed(field); - } - - // -------- IListAdapter - public void customButtonPressed(ListDialogField field, int index) { - // typePageCustomButtonPressed(field, index); - } - - public void selectionChanged(ListDialogField field) { - } - - // -------- IDialogFieldListener - public void dialogFieldChanged(DialogField field) { - typePageDialogFieldChanged(field); - } - - public void doubleClicked(ListDialogField field) { - } - } - - // private void typePageChangeControlPressed(DialogField field) { - // if (field == fPackageDialogField) { - // IPackageFragment pack= choosePackage(); - // if (pack != null) { - // fPackageDialogField.setText(pack.getElementName()); - // } - // } else if (field == fEnclosingTypeDialogField) { - // IType type= chooseEnclosingType(); - // if (type != null) { - // fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); - // } - // } else if (field == fSuperClassDialogField) { - // IType type= chooseSuperType(); - // if (type != null) { - // fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); - // } - // } - // } - - // private void typePageCustomButtonPressed(DialogField field, int index) { - // if (field == fSuperInterfacesDialogField) { - // chooseSuperInterfaces(); - // } - // } - - /* - * A field on the type has changed. The fields' status and all dependend - * status are updated. - */ - private void typePageDialogFieldChanged(DialogField field) { - String fieldName = null; - if (field == fPackageDialogField) { - fPackageStatus = packageChanged(); - updatePackageStatusLabel(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = PACKAGE; - } else if (field == fEnclosingTypeDialogField) { - // fEnclosingTypeStatus= enclosingTypeChanged(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = ENCLOSING; - } else if (field == fEnclosingTypeSelection) { - updateEnableState(); - boolean isEnclosedType = isEnclosingTypeSelected(); - if (!isEnclosedType) { - if (fAccMdfButtons.isSelected(PRIVATE_INDEX) - || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { - fAccMdfButtons.setSelection(PRIVATE_INDEX, false); - fAccMdfButtons.setSelection(PROTECTED_INDEX, false); - fAccMdfButtons.setSelection(PUBLIC_INDEX, true); - } - if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { - fOtherMdfButtons.setSelection(fStaticMdfIndex, false); - } - } - fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType - && fIsClass); - fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, - isEnclosedType && fIsClass); - fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, - isEnclosedType); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - fieldName = ENCLOSINGSELECTION; - } else if (field == fTypeNameDialogField) { - fTypeNameStatus = typeNameChanged(); - fieldName = TYPENAME; - } else if (field == fSuperClassDialogField) { - // fSuperClassStatus= superClassChanged(); - fieldName = SUPER; - } else if (field == fSuperInterfacesDialogField) { - // fSuperInterfacesStatus= superInterfacesChanged(); - fieldName = INTERFACES; - } else if (field == fOtherMdfButtons) { - fModifierStatus = modifiersChanged(); - fieldName = MODIFIERS; - } else { - fieldName = METHODS; - } - // tell all others - handleFieldChanged(fieldName); - } - - // -------- update message ---------------- - - /* - * @see net.sourceforge.phpdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) - */ - protected void handleFieldChanged(String fieldName) { - //super.handleFieldChanged(fieldName); - if (fieldName == CONTAINER) { - fPackageStatus = packageChanged(); - // fEnclosingTypeStatus= enclosingTypeChanged(); - fTypeNameStatus = typeNameChanged(); - // fSuperClassStatus= superClassChanged(); - // fSuperInterfacesStatus= superInterfacesChanged(); - } - } - - // ---- set / get ---------------- - - /** - * Returns the text of the package input field. - * - * @return the text of the package input field - */ - public String getPackageText() { - return fPackageDialogField.getText(); - } - - /** - * Returns the text of the enclosing type input field. - * - * @return the text of the enclosing type input field - */ -// public String getEnclosingTypeText() { -// return fEnclosingTypeDialogField.getText(); -// } - - /** - * Returns the package fragment corresponding to the current input. - * - * @return a package fragement or null if the input could not - * be resolved. - */ - public IPackageFragment getPackageFragment() { - if (!isEnclosingTypeSelected()) { - return fCurrPackage; - } else { - // if (fCurrEnclosingType != null) { - // return fCurrEnclosingType.getPackageFragment(); - // } - } - return null; - } - - /** - * Sets the package fragment to the given value. The method updates the - * model and the text of the control. - * - * @param pack - * the package fragement to be set - * @param canBeModified - * if true the package fragment is editable; - * otherwise it is read-only. - */ - public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { - fCurrPackage = pack; - fCanModifyPackage = canBeModified; - String str = (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ - fPackageDialogField.setText(str); - updateEnableState(); - } - - /** - * Returns the enclosing type corresponding to the current input. - * - * @return the enclosing type or null if the enclosing type - * is not selected or the input could not be resolved - */ - public IType getEnclosingType() { - // if (isEnclosingTypeSelected()) { - // return fCurrEnclosingType; - // } - return null; - } - - /** - * Sets the enclosing type. The method updates the underlying model and the - * text of the control. - * - * @param type - * the enclosing type - * @param canBeModified - * if true the enclosing type field is editable; - * otherwise it is read-only. - */ - // public void setEnclosingType(IType type, boolean canBeModified) { - // fCurrEnclosingType= type; - // fCanModifyEnclosingType= canBeModified; - // String str= (type == null) ? "" : - // JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ - // fEnclosingTypeDialogField.setText(str); - // updateEnableState(); - // } - /** - * Returns the selection state of the enclosing type checkbox. - * - * @return the seleciton state of the enclosing type checkbox - */ - public boolean isEnclosingTypeSelected() { - return fEnclosingTypeSelection.isSelected(); - } - - /** - * Sets the enclosing type checkbox's selection state. - * - * @param isSelected - * the checkbox's selection state - * @param canBeModified - * if true the enclosing type checkbox is - * modifiable; otherwise it is read-only. - */ - public void setEnclosingTypeSelection(boolean isSelected, - boolean canBeModified) { - fEnclosingTypeSelection.setSelection(isSelected); - fEnclosingTypeSelection.setEnabled(canBeModified); - updateEnableState(); - } - - /** - * Returns the type name entered into the type input field. - * - * @return the type name - */ - public String getTypeName() { - return fTypeNameDialogField.getText(); - } - - /** - * Sets the type name input field's text to the given value. Method doesn't - * update the model. - * - * @param name - * the new type name - * @param canBeModified - * if true the enclosing type name field is - * editable; otherwise it is read-only. - */ - public void setTypeName(String name, boolean canBeModified) { - fTypeNameDialogField.setText(name); - fTypeNameDialogField.setEnabled(canBeModified); - } - - /** - * Returns the selected modifiers. - * - * @return the selected modifiers - * @see Flags - */ -// public int getModifiers() { -// int mdf = 0; -// if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { -// mdf += F_PUBLIC; -// } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { -// mdf += F_PRIVATE; -// } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { -// mdf += F_PROTECTED; -// } -// // if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex -// // != 0)) { -// // mdf+= F_ABSTRACT; -// // } -// if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { -// mdf += F_FINAL; -// } -// if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { -// mdf += F_STATIC; -// } -// return mdf; -// } - - /** - * Sets the modifiers. - * - * @param modifiers - * F_PUBLIC, F_PRIVATE, - * F_PROTECTED, F_ABSTRACT, F_FINAL - * or F_STATIC or, a valid combination. - * @param canBeModified - * if true the modifier fields are editable; - * otherwise they are read-only - * @see Flags - */ -// public void setModifiers(int modifiers, boolean canBeModified) { -// if (Flags.isPublic(modifiers)) { -// fAccMdfButtons.setSelection(PUBLIC_INDEX, true); -// } else if (Flags.isPrivate(modifiers)) { -// fAccMdfButtons.setSelection(PRIVATE_INDEX, true); -// } else if (Flags.isProtected(modifiers)) { -// fAccMdfButtons.setSelection(PROTECTED_INDEX, true); -// } else { -// fAccMdfButtons.setSelection(DEFAULT_INDEX, true); -// } -// // if (Flags.isAbstract(modifiers)) { -// // fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); -// // } -// if (Flags.isFinal(modifiers)) { -// fOtherMdfButtons.setSelection(FINAL_INDEX, true); -// } -// if (Flags.isStatic(modifiers)) { -// fOtherMdfButtons.setSelection(fStaticMdfIndex, true); -// } -// -// fAccMdfButtons.setEnabled(canBeModified); -// fOtherMdfButtons.setEnabled(canBeModified); -// } - - /** - * Returns the content of the superclass input field. - * - * @return the superclass name - */ -// public String getSuperClass() { -// return fSuperClassDialogField.getText(); -// } - - /** - * Sets the super class name. - * - * @param name - * the new superclass name - * @param canBeModified - * if true the superclass name field is editable; - * otherwise it is read-only. - */ - public void setSuperClass(String name, boolean canBeModified) { - fSuperClassDialogField.setText(name); - fSuperClassDialogField.setEnabled(canBeModified); - } - - /** - * Returns the chosen super interfaces. - * - * @return a list of chosen super interfaces. The list's elements are of - * type String - */ -// public List getSuperInterfaces() { -// return fSuperInterfacesDialogField.getElements(); -// } - - /** - * Sets the super interfaces. - * - * @param interfacesNames - * a list of super interface. The method requires that the list's - * elements are of type String - * @param canBeModified - * if true the super interface field is editable; - * otherwise it is read-only. - */ - public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { - fSuperInterfacesDialogField.setElements(interfacesNames); - fSuperInterfacesDialogField.setEnabled(canBeModified); - } - - // ----------- validation ---------- - - /** - * A hook method that gets called when the package field has changed. The - * method validates the package name and returns the status of the - * validation. The validation also updates the package fragment model. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - protected IStatus packageChanged() { - StatusInfo status = new StatusInfo(); - fPackageDialogField.enableButton(getPackageFragmentRoot() != null); - - // String packName= getPackageText(); - // if (packName.length() > 0) { - // IStatus val= JavaConventions.validatePackageName(packName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", - // val.getMessage())); //$NON-NLS-1$ - // return status; - // } else if (val.getSeverity() == IStatus.WARNING) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", - // val.getMessage())); //$NON-NLS-1$ - // // continue - // } - // } - - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root != null) { - // if (root.getJavaProject().exists() && packName.length() > 0) { - // try { - // IPath rootPath= root.getPath(); - // IPath outputPath= root.getJavaProject().getOutputLocation(); - // if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) - // { - // // if the bin folder is inside of our root, dont allow to name a - // package - // // like the bin folder - // IPath packagePath= rootPath.append(packName.replace('.', '/')); - // if (outputPath.isPrefixOf(packagePath)) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); - // //$NON-NLS-1$ - // return status; - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // let pass - // } - // } - // - // fCurrPackage= root.getPackageFragment(packName); - // } else { - // status.setError(""); //$NON-NLS-1$ - // } - return status; - } - - /* - * Updates the 'default' label next to the package field. - */ - private void updatePackageStatusLabel() { - String packName = getPackageText(); - - if (packName.length() == 0) { - fPackageDialogField.setStatus(NewWizardMessages - .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ - } else { - fPackageDialogField.setStatus(""); //$NON-NLS-1$ - } - } - - /* - * Updates the enable state of buttons related to the enclosing type - * selection checkbox. - */ - private void updateEnableState() { - boolean enclosing = isEnclosingTypeSelected(); - fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); - fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType - && enclosing); - } - - /** - * Hook method that gets called when the enclosing type name has changed. - * The method validates the enclosing type and returns the status of the - * validation. It also updates the enclosing type model. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - // protected IStatus enclosingTypeChanged() { - // StatusInfo status= new StatusInfo(); - // fCurrEnclosingType= null; - // - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // - // fEnclosingTypeDialogField.enableButton(root != null); - // if (root == null) { - // status.setError(""); //$NON-NLS-1$ - // return status; - // } - // - // String enclName= getEnclosingTypeText(); - // if (enclName.length() == 0) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); - // //$NON-NLS-1$ - // return status; - // } - // try { - // IType type= findType(root.getJavaProject(), enclName); - // if (type == null) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); - // //$NON-NLS-1$ - // return status; - // } - // - // if (type.getCompilationUnit() == null) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); - // //$NON-NLS-1$ - // return status; - // } - // if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); - // //$NON-NLS-1$ - // return status; - // } - // - // fCurrEnclosingType= type; - // IPackageFragmentRoot enclosingRoot= - // JavaModelUtil.getPackageFragmentRoot(type); - // if (!enclosingRoot.equals(root)) { - // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); - // //$NON-NLS-1$ - // } - // return status; - // } catch (JavaModelException e) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); - // //$NON-NLS-1$ - // PHPeclipsePlugin.log(e); - // return status; - // } - // } - /** - * Hook method that gets called when the type name has changed. The method - * validates the type name and returns the status of the validation. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - protected IStatus typeNameChanged() { - StatusInfo status = new StatusInfo(); - String typeName = getTypeName(); - // must not be empty - if (typeName.length() == 0) { - status.setError(NewWizardMessages - .getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ - return status; - } - if (typeName.indexOf('.') != -1) { - status.setError(NewWizardMessages - .getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ - return status; - } - // IStatus val= JavaConventions.validateJavaTypeName(typeName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", - // val.getMessage())); //$NON-NLS-1$ - // return status; - // } else if (val.getSeverity() == IStatus.WARNING) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", - // val.getMessage())); //$NON-NLS-1$ - // // continue checking - // } - - // must not exist - if (!isEnclosingTypeSelected()) { - IPackageFragment pack = getPackageFragment(); - if (pack != null) { - ICompilationUnit cu = pack.getCompilationUnit(typeName - + ".java"); //$NON-NLS-1$ - if (cu.getResource().exists()) { - status - .setError(NewWizardMessages - .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ - return status; - } - } - } else { - IType type = getEnclosingType(); - if (type != null) { - IType member = type.getType(typeName); - if (member.exists()) { - status - .setError(NewWizardMessages - .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ - return status; - } - } - } - return status; - } - - /** - * Hook method that gets called when the superclass name has changed. The - * method validates the superclass name and returns the status of the - * validation. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - // protected IStatus superClassChanged() { - // StatusInfo status= new StatusInfo(); - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // fSuperClassDialogField.enableButton(root != null); - // - // fSuperClass= null; - // - // String sclassName= getSuperClass(); - // if (sclassName.length() == 0) { - // // accept the empty field (stands for java.lang.Object) - // return status; - // } - // IStatus val= JavaConventions.validateJavaTypeName(sclassName); - // if (val.getSeverity() == IStatus.ERROR) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); - // //$NON-NLS-1$ - // return status; - // } - // if (root != null) { - // try { - // IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); - // if (type == null) { - // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); - // //$NON-NLS-1$ - // return status; - // } else { - // if (type.isInterface()) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", - // sclassName)); //$NON-NLS-1$ - // return status; - // } - // int flags= type.getFlags(); - // if (Flags.isFinal(flags)) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", - // sclassName)); //$NON-NLS-1$ - // return status; - // } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", - // sclassName)); //$NON-NLS-1$ - // return status; - // } - // } - // fSuperClass= type; - // } catch (JavaModelException e) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); - // //$NON-NLS-1$ - // PHPeclipsePlugin.log(e); - // } - // } else { - // status.setError(""); //$NON-NLS-1$ - // } - // return status; - // - // } - // private IType resolveSuperTypeName(IJavaProject jproject, String - // sclassName) throws JavaModelException { - // if (!jproject.exists()) { - // return null; - // } - // IType type= null; - // if (isEnclosingTypeSelected()) { - // // search in the context of the enclosing type - // IType enclosingType= getEnclosingType(); - // if (enclosingType != null) { - // String[][] res= enclosingType.resolveType(sclassName); - // if (res != null && res.length > 0) { - // type= jproject.findType(res[0][0], res[0][1]); - // } - // } - // } else { - // IPackageFragment currPack= getPackageFragment(); - // if (type == null && currPack != null) { - // String packName= currPack.getElementName(); - // // search in own package - // if (!currPack.isDefaultPackage()) { - // type= jproject.findType(packName, sclassName); - // } - // // search in java.lang - // if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ - // type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ - // } - // } - // // search fully qualified - // if (type == null) { - // type= jproject.findType(sclassName); - // } - // } - // return type; - // } - // private IType findType(IJavaProject project, String typeName) throws - // JavaModelException { - // if (project.exists()) { - // return project.findType(typeName); - // } - // return null; - // } - /** - * Hook method that gets called when the list of super interface has - * changed. The method validates the superinterfaces and returns the status - * of the validation. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - // protected IStatus superInterfacesChanged() { - // StatusInfo status= new StatusInfo(); - // - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // fSuperInterfacesDialogField.enableButton(0, root != null); - // - // if (root != null) { - // List elements= fSuperInterfacesDialogField.getElements(); - // int nElements= elements.size(); - // for (int i= 0; i < nElements; i++) { - // String intfname= (String)elements.get(i); - // try { - // IType type= findType(root.getJavaProject(), intfname); - // if (type == null) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", - // intfname)); //$NON-NLS-1$ - // return status; - // } else { - // if (type.isClass()) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", - // intfname)); //$NON-NLS-1$ - // return status; - // } - // if (!JavaModelUtil.isVisible(type, getPackageFragment())) { - // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", - // intfname)); //$NON-NLS-1$ - // return status; - // } - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // // let pass, checking is an extra - // } - // } - // } - // return status; - // } - /** - * Hook method that gets called when the modifiers have changed. The method - * validates the modifiers and returns the status of the validation. - *

- * Subclasses may extend this method to perform their own validation. - *

- * - * @return the status of the validation - */ - protected IStatus modifiersChanged() { - StatusInfo status = new StatusInfo(); - //int modifiers = getModifiers(); - - // if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { - // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); - // //$NON-NLS-1$ - // } - return status; - } - - // selection dialogs - - // private IPackageFragment choosePackage() { - // IPackageFragmentRoot froot= getPackageFragmentRoot(); - // IJavaElement[] packages= null; - // try { - // if (froot != null && froot.exists()) { - // packages= froot.getChildren(); - // } - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // } - // if (packages == null) { - // packages= new IJavaElement[0]; - // } - // - // ElementListSelectionDialog dialog= new - // ElementListSelectionDialog(getShell(), new - // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); - // dialog.setIgnoreCase(false); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); - // //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); - // //$NON-NLS-1$ - // dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); - // //$NON-NLS-1$ - // dialog.setElements(packages); - // IPackageFragment pack= getPackageFragment(); - // if (pack != null) { - // dialog.setInitialSelections(new Object[] { pack }); - // } - // - // if (dialog.open() == ElementListSelectionDialog.OK) { - // return (IPackageFragment) dialog.getFirstResult(); - // } - // return null; - // } - - // private IType chooseEnclosingType() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return null; - // } - // - // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new - // IJavaElement[] { root }); - // - // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), - // getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); - // //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); - // //$NON-NLS-1$ - // dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); - // - // if (dialog.open() == TypeSelectionDialog.OK) { - // return (IType) dialog.getFirstResult(); - // } - // return null; - // } - - // private IType chooseSuperType() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return null; - // } - // - // IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; - // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); - // - // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), - // getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); - // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); - // //$NON-NLS-1$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); - // //$NON-NLS-1$ - // dialog.setFilter(getSuperClass()); - // - // if (dialog.open() == TypeSelectionDialog.OK) { - // return (IType) dialog.getFirstResult(); - // } - // return null; - // } - - // private void chooseSuperInterfaces() { - // IPackageFragmentRoot root= getPackageFragmentRoot(); - // if (root == null) { - // return; - // } - // - // IJavaProject project= root.getJavaProject(); - // SuperInterfaceSelectionDialog dialog= new - // SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), - // fSuperInterfacesDialogField, project); - // dialog.setTitle(fIsClass ? - // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") - // : - // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); - // //$NON-NLS-1$ //$NON-NLS-2$ - // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); - // //$NON-NLS-1$ - // dialog.open(); - // return; - // } - - // ---- creation ---------------- - - /** - * Creates the new type using the entered field values. - * - * @param monitor - * a progress monitor to report progress. - */ - public void createType(IProgressMonitor monitor) throws CoreException, - InterruptedException { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - - monitor.beginTask(NewWizardMessages - .getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ - ICompilationUnit createdWorkingCopy = null; - try { - // IPackageFragmentRoot root = getPackageFragmentRoot(); - // IPackageFragment pack = getPackageFragment(); - // if (pack == null) { - // pack = root.getPackageFragment(""); //$NON-NLS-1$ - // } - // - // if (!pack.exists()) { - // String packName = pack.getElementName(); - // pack = root.createPackageFragment(packName, true, null); - // } - - monitor.worked(1); - - String clName = getTypeName(); - - boolean isInnerClass = isEnclosingTypeSelected(); - - IType createdType; - // ImportsStructure imports; - int indent = 0; - - //IPreferenceStore store = PreferenceConstants.getPreferenceStore(); - // String[] prefOrder = - // JavaPreferencesSettings.getImportOrderPreference(store); - // int threshold = - // JavaPreferencesSettings.getImportNumberThreshold(store); - // - String lineDelimiter = null; - // if (!isInnerClass) { - lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - // - // ICompilationUnit parentCU = pack.createCompilationUnit(clName + - // ".php", "", false, new SubProgressMonitor(monitor, 2)); - // //$NON-NLS-1$ //$NON-NLS-2$ - // createdWorkingCopy = (ICompilationUnit) - // parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), - // null); - // - // imports = new ImportsStructure(createdWorkingCopy, prefOrder, - // threshold, false); - // // add an import that will be removed again. Having this import - // solves 14661 - // imports.addImport(pack.getElementName(), getTypeName()); - // - //String typeContent = constructTypeStub(lineDelimiter);// new - // ImportsManager(imports), - // lineDelimiter); - - // String cuContent = constructCUContent(parentCU, typeContent, - // lineDelimiter); - - // createdWorkingCopy.getBuffer().setContents(cuContent); - // - createdType = createdWorkingCopy.getType(clName); - // } else { - // IType enclosingType = getEnclosingType(); - // - // // if we are working on a enclosed type that is open in an - // editor, - // // then replace the enclosing type with its working copy - // IType workingCopy = (IType) - // EditorUtility.getWorkingCopy(enclosingType); - // if (workingCopy != null) { - // enclosingType = workingCopy; - // } - // - // ICompilationUnit parentCU = enclosingType.getCompilationUnit(); - // imports = new ImportsStructure(parentCU, prefOrder, threshold, - // true); - // - // // add imports that will be removed again. Having the imports - // solves 14661 - // IType[] topLevelTypes = parentCU.getTypes(); - // for (int i = 0; i < topLevelTypes.length; i++) { - // imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); - // } - // - // lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); - // StringBuffer content = new StringBuffer(); - // String comment = getTypeComment(parentCU); - // if (comment != null) { - // content.append(comment); - // content.append(lineDelimiter); - // } - // content.append(constructTypeStub(new ImportsManager(imports), - // lineDelimiter)); - // IJavaElement[] elems = enclosingType.getChildren(); - // IJavaElement sibling = elems.length > 0 ? elems[0] : null; - // - // createdType = enclosingType.createType(content.toString(), - // sibling, false, new SubProgressMonitor(monitor, 1)); - // - // indent = StubUtility.getIndentUsed(enclosingType) + 1; - // } - // - // // add imports for superclass/interfaces, so types can be - // resolved correctly - // imports.create(false, new SubProgressMonitor(monitor, 1)); - // - ICompilationUnit cu = createdType.getCompilationUnit(); - synchronized (cu) { - cu.reconcile(); - } - // createTypeMembers(createdType, new ImportsManager(imports), new - // SubProgressMonitor(monitor, 1)); - // - // // add imports - // imports.create(false, new SubProgressMonitor(monitor, 1)); - - synchronized (cu) { - cu.reconcile(); - } - ISourceRange range = createdType.getSourceRange(); - - IBuffer buf = cu.getBuffer(); - String originalContent = buf.getText(range.getOffset(), range - .getLength()); - String formattedContent = StubUtility.codeFormat(originalContent, - indent, lineDelimiter); - buf.replace(range.getOffset(), range.getLength(), formattedContent); - if (!isInnerClass) { - String fileComment = getFileComment(cu); - if (fileComment != null && fileComment.length() > 0) { - buf.replace(0, 0, fileComment + lineDelimiter); - } - cu.commit(false, new SubProgressMonitor(monitor, 1)); - } else { - monitor.worked(1); - } - fCreatedType = createdType; - } finally { - if (createdWorkingCopy != null) { - createdWorkingCopy.destroy(); - } - monitor.done(); - } - } - - /** - * Uses the New Java file template from the code template page to generate a - * compilation unit with the given type content. - * - * @param cu - * The new created compilation unit - * @param typeContent - * The content of the type, including signature and type body. - * @param lineDelimiter - * The line delimiter to be used. - * @return String Returns the result of evaluating the new file template - * with the given type content. - * @throws CoreException - * @since 2.1 - */ - // protected String constructCUContent(ICompilationUnit cu, String - // typeContent, String lineDelimiter) throws CoreException { - // StringBuffer typeQualifiedName= new StringBuffer(); - // if (isEnclosingTypeSelected()) { - // typeQualifiedName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); - // } - // typeQualifiedName.append(getTypeName()); - // String typeComment= CodeGeneration.getTypeComment(cu, - // typeQualifiedName.toString(), lineDelimiter); - // IPackageFragment pack= (IPackageFragment) cu.getParent(); - // String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, - // typeContent, lineDelimiter); - // if (content != null) { - // CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray()); - // if ((pack.isDefaultPackage() || unit.getPackage() != null) && - // !unit.types().isEmpty()) { - // return content; - // } - // } - // StringBuffer buf= new StringBuffer(); - // if (!pack.isDefaultPackage()) { - // buf.append("package ").append(pack.getElementName()).append(';'); - // //$NON-NLS-1$ - // } - // buf.append(lineDelimiter).append(lineDelimiter); - // if (typeComment != null) { - // buf.append(typeComment).append(lineDelimiter); - // } - // buf.append(typeContent); - // return buf.toString(); - // } - /** - * Returns the created type. The method only returns a valid type after - * createType has been called. - * - * @return the created type - * @see #createType(IProgressMonitor) - */ - public IType getCreatedType() { - return fCreatedType; - } - - // ---- construct cu body---------------- - - // private void writeSuperClass(StringBuffer buf, ImportsManager imports) { - // String typename= getSuperClass(); - // if (fIsClass && typename.length() > 0 && - // !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ - // buf.append(" extends "); //$NON-NLS-1$ - // - // String qualifiedName= fSuperClass != null ? - // JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; - // buf.append(imports.addImport(qualifiedName)); - // } - // } - - // private void writeSuperInterfaces(StringBuffer buf, ImportsManager - // imports) { - // List interfaces= getSuperInterfaces(); - // int last= interfaces.size() - 1; - // if (last >= 0) { - // if (fIsClass) { - // buf.append(" implements "); //$NON-NLS-1$ - // } else { - // buf.append(" extends "); //$NON-NLS-1$ - // } - // for (int i= 0; i <= last; i++) { - // String typename= (String) interfaces.get(i); - // buf.append(imports.addImport(typename)); - // if (i < last) { - // buf.append(','); - // } - // } - // } - // } - - /* - * Called from createType to construct the source for this type - */ -// private String constructTypeStub(String lineDelimiter) { // ImportsManager -// // imports, -// // String -// // lineDelimiter) -// // { -// StringBuffer buf = new StringBuffer(); -// -// int modifiers = getModifiers(); -// buf.append(Flags.toString(modifiers)); -// if (modifiers != 0) { -// buf.append(' '); -// } -// buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ -// buf.append(getTypeName()); -// // writeSuperClass(buf, imports); -// // writeSuperInterfaces(buf, imports); -// buf.append('{'); -// buf.append(lineDelimiter); -// buf.append(lineDelimiter); -// buf.append('}'); -// buf.append(lineDelimiter); -// return buf.toString(); -// } - - /** - * @deprecated Overwrite createTypeMembers(IType, IImportsManager, - * IProgressMonitor) instead - */ - // protected void createTypeMembers(IType newType, IImportsStructure - // imports, IProgressMonitor monitor) throws CoreException { - // //deprecated - // } - /** - * Hook method that gets called from createType to support - * adding of unanticipated methods, fields, and inner types to the created - * type. - *

- * Implementers can use any methods defined on IType to - * manipulate the new type. - *

- *

- * The source code of the new type will be formtted using the platform's - * formatter. Needed imports are added by the wizard at the end of the type - * creation process using the given import manager. - *

- * - * @param newType - * the new type created via createType - * @param imports - * an import manager which can be used to add new imports - * @param monitor - * a progress monitor to report progress. Must not be - * null - * - * @see #createType(IProgressMonitor) - */ - // protected void createTypeMembers(IType newType, ImportsManager imports, - // IProgressMonitor monitor) throws CoreException { - // // call for compatibility - // createTypeMembers(newType, - // ((ImportsManager)imports).getImportsStructure(), monitor); - // - // // default implementation does nothing - // // example would be - // // String mainMathod= "public void foo(Vector vec) {}" - // // createdType.createMethod(main, null, false, null); - // // imports.addImport("java.lang.Vector"); - // } - /** - * @deprecated Instead of file templates, the new type code template - * specifies the stub for a compilation unit. - */ - protected String getFileComment(ICompilationUnit parentCU) { - return null; - } - - private boolean isValidComment(String template) { - IScanner scanner = ToolFactory.createScanner(true, false, false); // , - // false); - scanner.setSource(template.toCharArray()); - try { - int next = scanner.getNextToken(); - while (next == ITerminalSymbols.TokenNameCOMMENT_LINE - || next == ITerminalSymbols.TokenNameCOMMENT_PHPDOC - || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { - next = scanner.getNextToken(); - } - return next == ITerminalSymbols.TokenNameEOF; - } catch (InvalidInputException e) { - } - return false; - } - - /** - * Hook method that gets called from createType to retrieve a - * type comment. This default implementation returns the content of the - * 'typecomment' template. - * - * @return the type comment or null if a type comment is not - * desired - */ -// protected String getTypeComment(ICompilationUnit parentCU) { -// if (PreferenceConstants.getPreferenceStore().getBoolean( -// PreferenceConstants.CODEGEN_ADD_COMMENTS)) { -// try { -// StringBuffer typeName = new StringBuffer(); -// if (isEnclosingTypeSelected()) { -// typeName.append( -// JavaModelUtil -// .getTypeQualifiedName(getEnclosingType())) -// .append('.'); -// } -// typeName.append(getTypeName()); -// String comment = CodeGeneration.getTypeComment(parentCU, -// typeName.toString(), String.valueOf('\n')); -// if (comment != null && isValidComment(comment)) { -// return comment; -// } -// } catch (CoreException e) { -// PHPeclipsePlugin.log(e); -// } -// } -// return null; -// } - - /** - * @deprecated Use getTemplate(String,ICompilationUnit,int) - */ -// protected String getTemplate(String name, ICompilationUnit parentCU) { -// return getTemplate(name, parentCU, 0); -// } - - /** - * Returns the string resulting from evaluation the given template in the - * context of the given compilation unit. This accesses the normal template - * page, not the code templates. To use code templates use - * constructCUContent to construct a compilation unit stub or - * getTypeComment for the comment of the type. - * - * @param name - * the template to be evaluated - * @param parentCU - * the templates evaluation context - * @param pos - * a source offset into the parent compilation unit. The template - * is evalutated at the given source offset - */ -// protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { -// try { -// Template[] templates = Templates.getInstance().getTemplates(name); -// if (templates.length > 0) { -// return JavaContext -// .evaluateTemplate(templates[0], parentCU, pos); -// } -// } catch (CoreException e) { -// PHPeclipsePlugin.log(e); -// } catch (BadLocationException e1) { -// // TODO Auto-generated catch block -// e1.printStackTrace(); -// } catch (TemplateException e1) { -// // TODO Auto-generated catch block -// e1.printStackTrace(); -// } -// return null; -// } - - /** - * @deprecated Use - * createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) - */ - // protected IMethod[] createInheritedMethods(IType type, boolean - // doConstructors, boolean doUnimplementedMethods, IImportsStructure - // imports, IProgressMonitor monitor) throws CoreException { - // return createInheritedMethods(type, doConstructors, - // doUnimplementedMethods, new ImportsManager(imports), monitor); - // } - /** - * Creates the bodies of all unimplemented methods and constructors and adds - * them to the type. Method is typically called by implementers of - * NewTypeWizardPage to add needed method and constructors. - * - * @param type - * the type for which the new methods and constructor are to be - * created - * @param doConstructors - * if true unimplemented constructors are created - * @param doUnimplementedMethods - * if true unimplemented methods are created - * @param imports - * an import manager to add all neded import statements - * @param monitor - * a progress monitor to report progress - */ - // protected IMethod[] createInheritedMethods(IType type, boolean - // doConstructors, boolean doUnimplementedMethods, ImportsManager imports, - // IProgressMonitor monitor) throws CoreException { - // ArrayList newMethods= new ArrayList(); - // ITypeHierarchy hierarchy= null; - // CodeGenerationSettings settings= - // JavaPreferencesSettings.getCodeGenerationSettings(); - // - // if (doConstructors) { - // hierarchy= type.newSupertypeHierarchy(monitor); - // IType superclass= hierarchy.getSuperclass(type); - // if (superclass != null) { - // String[] constructors= StubUtility.evalConstructors(type, superclass, - // settings, imports.getImportsStructure()); - // if (constructors != null) { - // for (int i= 0; i < constructors.length; i++) { - // newMethods.add(constructors[i]); - // } - // } - // - // } - // } - // if (doUnimplementedMethods) { - // if (hierarchy == null) { - // hierarchy= type.newSupertypeHierarchy(monitor); - // } - // String[] unimplemented= StubUtility.evalUnimplementedMethods(type, - // hierarchy, false, settings, null, imports.getImportsStructure()); - // if (unimplemented != null) { - // for (int i= 0; i < unimplemented.length; i++) { - // newMethods.add(unimplemented[i]); - // } - // } - // } - // IMethod[] createdMethods= new IMethod[newMethods.size()]; - // for (int i= 0; i < newMethods.size(); i++) { - // String content= (String) newMethods.get(i) + '\n'; // content will be - // formatted, ok to use \n - // createdMethods[i]= type.createMethod(content, null, false, null); - // } - // return createdMethods; - // } - // ---- creation ---------------- - /** - * Returns the runnable that creates the type using the current settings. - * The returned runnable must be executed in the UI thread. - * - * @return the runnable to create the new type - */ - // public IRunnableWithProgress getRunnable() { - // return new IRunnableWithProgress() { - // public void run(IProgressMonitor monitor) throws - // InvocationTargetException, InterruptedException { - // try { - // if (monitor == null) { - // monitor= new NullProgressMonitor(); - // } - // createType(monitor); - // } catch (CoreException e) { - // throw new InvocationTargetException(e); - // } - // } - // }; - // } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java deleted file mode 100644 index 3858ed8..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java +++ /dev/null @@ -1,183 +0,0 @@ -package net.sourceforge.phpeclipse.actions; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.compiler.util.Util; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Path; -import org.eclipse.ui.IFileEditorInput; - -public class IncludesScanner implements ITerminalSymbols { - // private final PHPOpenAllIncludesEditorAction fOpenAllIncludesAction; - private IProject fProject; - - private IFileEditorInput fEditorInput; - - private HashSet fSet; - - public IncludesScanner(IProject project, IFileEditorInput editorInput) { - fProject = project; - // fOpenAllIncludesAction = action; - fEditorInput = editorInput; - fSet = new HashSet(); - } - - /** - * Add the information for a given IFile resource - * - */ - public void addFile(IFile fileToParse) { - - try { - if (fileToParse.exists()) { - addInputStream(new BufferedInputStream(fileToParse - .getContents()), fileToParse.getProjectRelativePath() - .toString()); - } - } catch (CoreException e1) { - e1.printStackTrace(); - } - } - - private void addInputStream(InputStream stream, String filePath) - throws CoreException { - try { - if (fSet.add(filePath)) { // new entry in set - parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, - null)); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - } - - /** - * Get the next token from input - */ - private int getNextToken(Scanner scanner) { - int token; - try { - token = scanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = scanner.getCurrentTokenEndPosition(); - int currentStartPosition = scanner - .getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," - + currentEndPosition + ": "); - System.out.println(scanner.toStringAction(token)); - } - return token; - } catch (InvalidInputException e) { - } - return TokenNameERROR; - } - - private void parseIdentifiers(char[] charArray) { - IFile file; - Scanner scanner = new Scanner(false, false, false, false, true, null, - null, true /* taskCaseSensitive */); - scanner.setSource(charArray); - scanner.setPHPMode(false); - int token = getNextToken(scanner); - try { - while (token != TokenNameEOF) { // && fToken != TokenNameERROR) { - if (token == TokenNameinclude || token == TokenNameinclude_once - || token == TokenNamerequire - || token == TokenNamerequire_once) { - while (token != TokenNameEOF && token != TokenNameERROR - && token != TokenNameSEMICOLON - && token != TokenNameRPAREN - && token != TokenNameLBRACE - && token != TokenNameRBRACE) { - token = getNextToken(scanner); - if (token == TokenNameStringDoubleQuote - || token == TokenNameStringSingleQuote) { - char[] includeName = scanner - .getCurrentStringLiteralSource(); - try { - System.out.println(includeName); - file = getIncludeFile(new String(includeName)); - addFile(file); - } catch (Exception e) { - // ignore - } - break; - } - } - } - token = getNextToken(scanner); - } - } catch (SyntaxError e) { - // e.printStackTrace(); - } - } - - private IContainer getWorkingLocation(IFileEditorInput editorInput) { - if (editorInput == null || editorInput.getFile() == null) { - return null; - } - return editorInput.getFile().getParent(); - } - - public IFile getIncludeFile(String relativeFilename) { - IContainer container = getWorkingLocation(fEditorInput); - IFile file = null; - if (relativeFilename.startsWith("../")) { - Path path = new Path(relativeFilename); - file = container.getFile(path); - return file; - } - int index = relativeFilename.lastIndexOf('/'); - - if (index >= 0) { - Path path = new Path(relativeFilename); - file = fProject.getFile(path); - if (file.exists()) { - return file; - } - } - Path path = new Path(relativeFilename); - file = container.getFile(path); - - return file; - } - - /** - * Returns a list of includes - * - * @return the determined list of includes - */ - public List getList() { - ArrayList list = new ArrayList(); - list.addAll(fSet); - return list; - } - - /** - * @return Returns the set. - */ - public Set getSet() { - return fSet; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java deleted file mode 100644 index 0b5690c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java +++ /dev/null @@ -1,308 +0,0 @@ -/*********************************************************************************************************************************** - * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made - * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: www.phpeclipse.de - **********************************************************************************************************************************/ -package net.sourceforge.phpeclipse.actions; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; -import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; -import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.dialogs.ListSelectionDialog; - -public class OpenDeclarationEditorAction { - - private PHPEditor fEditor; - - private IProject fProject; - - private boolean isIncludeString; - - public OpenDeclarationEditorAction(PHPEditor editor) { - fEditor = editor; - fProject = null; - isIncludeString = false; - } - - /** - * @param selection - */ - protected void openSelectedElement(ITextSelection selection) { - IDocument doc = fEditor.getDocumentProvider().getDocument( - fEditor.getEditorInput()); - int pos = selection.getOffset(); - openSelectedPosition(doc, pos); - } - - protected void openSelectedPosition(IDocument doc, int position) { - IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); - fProject = f.getProject(); - // System.out.println(selection.getText()); - String identifierOrInclude = getIdentifierOrInclude(doc, position); - // System.out.println(word); - if (identifierOrInclude != null && !identifierOrInclude.equals("")) { - if (isIncludeString) { - openIncludeFile(identifierOrInclude); - } else { - openIdentifierDeclaration(f, identifierOrInclude); - } - } - } - - /** - * @param filename - */ - private void openIncludeFile(String filename) { - if (filename != null && !filename.equals("")) { - try { - IFile currentFile = ((IFileEditorInput) fEditor - .getEditorInput()).getFile(); - IPath path = PHPFileUtil.determineFilePath(filename, - currentFile, fProject); - if (path != null) { - //IFile file = PHPFileUtil.createFile(path, fProject); - //if (file != null && file.exists()) { - // PHPeclipsePlugin.getDefault().openFileInTextEditor( - // file.getLocation().toString()); - // return; - //} - WebUI.getDefault().openFileInTextEditor( - path.toString()); - return; - } - } catch (Exception e) { - // ignore - } - - try { - - IdentifierIndexManager indexManager = WebUI - .getDefault().getIndexManager(fProject); - // filename = StringUtil.replaceRegExChars(filename); - List list = indexManager.getFileList(filename); - if (list != null && list.size() > 0) { - // String workspaceLocation = - // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); - String workspaceLocation = fProject.getFullPath() - .toString() - + java.io.File.separatorChar; - - ListSelectionDialog listSelectionDialog = new ListSelectionDialog( - WebUI.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), - list, new ListContentProvider(), - new LabelProvider(), "Select the includes to open."); - listSelectionDialog.setTitle("Multiple includes found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog.getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - // PHPIdentifierLocation location = - // (PHPIdentifierLocation) - // locations[i]; - String openFilename = workspaceLocation - + ((String) locations[i]); - WebUI.getDefault() - .openFileInTextEditor(openFilename); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } - } catch (Exception e) { - } - - } - return; - } - - /** - * @param f - * @param identiifer - */ - private void openIdentifierDeclaration(IFile f, String identiifer) { - if (identiifer != null && !identiifer.equals("")) { - IdentifierIndexManager indexManager = WebUI.getDefault() - .getIndexManager(fProject); - List locationsList = indexManager.getLocations(identiifer); - if (locationsList != null && locationsList.size() > 0) { - - // String workspaceLocation = - // PHPeclipsePlugin.getWorkspace().getRoot() - // .getLocation().toString(); - - String workspaceLocation = fProject.getFullPath().toString() - + java.io.File.separatorChar; - // TODO show all entries of the list in a dialog box - // at the moment always the first entry will be opened - if (locationsList.size() > 1) { - // determine all includes: - IncludesScanner includesScanner = new IncludesScanner( - fProject, (IFileEditorInput) fEditor - .getEditorInput()); - includesScanner.addFile(f); - Set exactIncludeSet = includesScanner.getSet(); - - PHPIdentifierLocation includeName; - for (int i = 0; i < locationsList.size(); i++) { - includeName = (PHPIdentifierLocation) locationsList - .get(i); - if (exactIncludeSet.contains(includeName.getFilename())) { - includeName - .setMatch(PHPIdentifierLocation.EXACT_MATCH); - } else { - includeName - .setMatch(PHPIdentifierLocation.UNDEFINED_MATCH); - } - } - Collections.sort(locationsList); - - ListSelectionDialog listSelectionDialog = new ListSelectionDialog( - WebUI.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), - locationsList, new ListContentProvider(), - new LabelProvider(), - "Select the resources to open."); - listSelectionDialog.setTitle("Multiple declarations found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog.getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - PHPIdentifierLocation location = (PHPIdentifierLocation) locations[i]; - String filename = workspaceLocation - + location.getFilename(); - // System.out.println(filename); - if (location.getOffset() >= 0) { - WebUI.getDefault() - .openFileAndGotoOffset( - filename, - location.getOffset(), - identiifer.length()); - } else { - WebUI.getDefault() - .openFileAndFindString( - filename, identiifer); - } - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } else { - try { - PHPIdentifierLocation location = (PHPIdentifierLocation) locationsList - .get(0); - String filename = workspaceLocation - + location.getFilename(); - // System.out.println(filename); - if (location.getOffset() >= 0) { - WebUI.getDefault() - .openFileAndGotoOffset(filename, - location.getOffset(), - identiifer.length()); - } else { - WebUI - .getDefault() - .openFileAndFindString(filename, identiifer); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - } - - private String getIdentifierOrInclude(IDocument doc, int pos) { - // private String getPHPIncludeText(IDocument doc, int pos) { - Point word = null; - int start = -1; - int end = -1; - isIncludeString = false; - try { - // try to find an include string - int position = pos; - char character = ' '; - - while (position >= 0) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') - || (character == '\r') || (character == '\n')) - break; - --position; - } - if ((character == '\"') || (character == '\'')) { - start = position; - - position = pos; - int length = doc.getLength(); - character = ' '; - while (position < length) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') - || (character == '\r') || (character == '\n')) - break; - ++position; - } - if ((character == '\"') || (character == '\'')) { - start++; - end = position; - - if (end > start) { - word = new Point(start, end - start); // include name - // found - isIncludeString = true; - } - } - } - - // try to find an identifier - if (word == null) { - word = PHPWordExtractor.findWord(doc, pos); // identifier found - isIncludeString = false; - } - } catch (BadLocationException x) { - } - - if (word != null) { - try { - return doc.get(word.x, word.y); - } catch (BadLocationException e) { - } - } - return ""; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java deleted file mode 100644 index f0ea56a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java +++ /dev/null @@ -1,160 +0,0 @@ -/*********************************************************************************************************************************** - * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made - * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: IBM Corporation - Initial implementation - * www.phpeclipse.de - **********************************************************************************************************************************/ -package net.sourceforge.phpeclipse.actions; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.ui.IPreferenceConstants; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; -//import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil; -import net.sourceforge.phpeclipse.webbrowser.IWebBrowser; -import net.sourceforge.phpeclipse.webbrowser.internal.BrowserManager; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IActionDelegate; -import org.eclipse.ui.IObjectActionDelegate; -import org.eclipse.ui.IWorkbenchPart; - -public class PHPEclipseShowAction implements IObjectActionDelegate { - private IWorkbenchPart workbenchPart; - - /** - * Constructor for Action1. - */ - public PHPEclipseShowAction() { - super(); - } - - /** - * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) - */ - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - workbenchPart = targetPart; - } - - public void run(IAction action) { - ISelectionProvider selectionProvider = null; - selectionProvider = workbenchPart.getSite().getSelectionProvider(); - StructuredSelection selection = null; - selection = (StructuredSelection) selectionProvider.getSelection(); - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - Shell shell = null; - Iterator iterator = null; - iterator = selection.iterator(); - while (iterator.hasNext()) { - // obj => selected object in the view - Object obj = iterator.next(); - // is it a resource - if (obj instanceof IResource) { - IResource resource = (IResource) obj; - // check if it's a file resource - switch (resource.getType()) { - case IResource.FILE: - // single file: - IFile previewFile = (IFile) resource; -// String extension = previewFile.getFileExtension() -// .toLowerCase(); -// boolean bringToTopPreview = ProjectPrefUtil -// .getPreviewBooleanValue( -// previewFile, -// IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); - // boolean showHTMLFilesLocal = - // ProjectPrefUtil.getPreviewBooleanValue(previewFile, - // IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL); - // boolean showXMLFilesLocal = - // ProjectPrefUtil.getPreviewBooleanValue(previewFile, - // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); -// boolean isHTMLFileName = "html".equals(extension) -// || "htm".equals(extension) -// || "xhtml".equals(extension); -// boolean isXMLFileName = "xml".equals(extension) -// || "xsd".equals(extension) -// || "dtd".equals(extension); - - String localhostURL; - // if (showHTMLFilesLocal && isHTMLFileName) { - // localhostURL = - // "file://"+previewFile.getLocation().toString(); - // } else if (showXMLFilesLocal && isXMLFileName) { - // localhostURL = - // "file://"+previewFile.getLocation().toString(); - // } else - if ((localhostURL = ShowExternalPreviewAction - .getLocalhostURL(store, previewFile)) == null) { - MessageDialog - .openInformation(shell, - "Couldn't create localhost URL", - "Please configure your localhost and documentRoot"); - return; - } - - try { - // if - // (store.getBoolean(PHPeclipsePlugin.USE_EXTERNAL_BROWSER_PREF)) - // { - // String[] arguments = { localhostURL }; - // MessageFormat form = new - // MessageFormat(store.getString(PHPeclipsePlugin.EXTERNAL_BROWSER_PREF)); - // Runtime runtime = Runtime.getRuntime(); - // String command = form.format(arguments); - // // console.write("External Browser command: " + - // command + "\n"); - // runtime.exec(command); - // } else { - open(new URL(localhostURL), shell, localhostURL); - // } - } catch (MalformedURLException e) { - MessageDialog.openInformation(shell, - "MalformedURLException: ", e.toString()); - } - } - } - } - } - - /** - * @see IActionDelegate#selectionChanged(IAction, ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - } - - public static void open(final URL url, final Shell shell, - final String dialogTitle) { - // if (WebBrowserUtil.canUseInternalWebBrowser()) { - // IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); - // try { - // IViewPart part = page.findView(BrowserView.ID_BROWSER); - // if (part == null) { - // part = page.showView(BrowserView.ID_BROWSER); - // } else { - // page.bringToTop(part); - // } - // ((BrowserView) part).setUrl(url.toExternalForm()); - // } catch (Exception e) { - // } - // } else { - BrowserManager manager = BrowserManager.getInstance(); - IWebBrowser browser = manager.getCurrentWebBrowser(); - browser.openURL(url); - // } - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java deleted file mode 100644 index 1d1e9b1..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Common Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: www.phpeclipse.de - ******************************************************************************/ -package net.sourceforge.phpeclipse.actions; - -import java.io.File; -import java.util.List; - -import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -//import org.eclipse.core.runtime.Path; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -//import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.actions.ActionDelegate; -import org.eclipse.ui.dialogs.ListSelectionDialog; - -public class PHPOpenAllIncludesEditorAction extends ActionDelegate implements - IEditorActionDelegate { - - private IWorkbenchWindow fWindow; - - private PHPEditor fEditor; - - private IProject fProject; - - private IncludesScanner fIncludesScanner; - - public void dispose() { - } - - public void init(IWorkbenchWindow window) { - this.fWindow = window; - } - - public void selectionChanged(IAction action, ISelection selection) { - if (!selection.isEmpty()) { - if (selection instanceof TextSelection) { - action.setEnabled(true); - } else if (fWindow.getActivePage() != null - && fWindow.getActivePage().getActivePart() != null) { - // - } - } - } - -// private IWorkbenchPage getActivePage() { -// IWorkbenchWindow workbenchWindow = fEditor.getEditorSite() -// .getWorkbenchWindow(); -// IWorkbenchPage page = workbenchWindow.getActivePage(); -// return page; -// } - - public IContainer getWorkingLocation(IFileEditorInput editorInput) { - if (editorInput == null || editorInput.getFile() == null) { - return null; - } - return editorInput.getFile().getParent(); - } - -// private IFile getIncludeFile(IProject project, -// IFileEditorInput editorInput, String relativeFilename) { -// IContainer container = getWorkingLocation(editorInput); -// String fullPath = project.getFullPath().toString(); -// IFile file = null; -// if (relativeFilename.startsWith("../")) { -// Path path = new Path(relativeFilename); -// file = container.getFile(path); -// return file; -// } -// int index = relativeFilename.lastIndexOf('/'); -// -// if (index >= 0) { -// Path path = new Path(relativeFilename); -// file = project.getFile(path); -// if (file.exists()) { -// return file; -// } -// } -// -// Path path = new Path(relativeFilename); -// file = container.getFile(path); -// -// return file; -// } - - public void run(IAction action) { - if (fEditor == null) { - IEditorPart targetEditor = fWindow.getActivePage() - .getActiveEditor(); - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } - if (fEditor != null) { - // determine the current Project from a (file-based) Editor - IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); - fProject = f.getProject(); - // System.out.println(fProject.toString()); - - ITextSelection selection = (ITextSelection) fEditor - .getSelectionProvider().getSelection(); - IDocument doc = fEditor.getDocumentProvider().getDocument( - fEditor.getEditorInput()); - fIncludesScanner = new IncludesScanner(fProject, - (IFileEditorInput) fEditor.getEditorInput()); - int pos = selection.getOffset(); - // System.out.println(selection.getText()); - String filename = getPHPIncludeText(doc, pos); - - if (filename != null && !filename.equals("")) { - try { - IFile file = fIncludesScanner.getIncludeFile(filename); - fIncludesScanner.addFile(file); - } catch (Exception e) { - // ignore - } - - try { - - List list = fIncludesScanner.getList(); - if (list != null && list.size() > 0) { - // String workspaceLocation = - // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); - String workspaceLocation = fProject.getFullPath() - .toString() - + File.separatorChar; - - ListSelectionDialog listSelectionDialog = new ListSelectionDialog( - WebUI.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getShell(), - list, new ListContentProvider(), - new LabelProvider(), - "Select the includes to open."); - listSelectionDialog.setTitle("Multiple includes found"); - if (listSelectionDialog.open() == Window.OK) { - Object[] locations = listSelectionDialog - .getResult(); - if (locations != null) { - try { - for (int i = 0; i < locations.length; i++) { - // PHPIdentifierLocation location = - // (PHPIdentifierLocation) - // locations[i]; - String openFilename = workspaceLocation - + ((String) locations[i]); - WebUI.getDefault() - .openFileInTextEditor( - openFilename); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - } - } catch (Exception e) { - } - - } - } - } - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - if (targetEditor != null && (targetEditor instanceof PHPEditor)) { - fEditor = (PHPEditor) targetEditor; - } - } - - private String getPHPIncludeText(IDocument doc, int pos) { - Point word = null; - int start = -1; - int end = -1; - - try { - - int position = pos; - char character; - - while (position >= 0) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') - || (character == '\r') || (character == '\n')) - break; - --position; - } - - start = position; - - position = pos; - int length = doc.getLength(); - - while (position < length) { - character = doc.getChar(position); - if ((character == '\"') || (character == '\'') - || (character == '\r') || (character == '\n')) - break; - ++position; - } - - start++; - end = position; - - if (end > start) - word = new Point(start, end - start); - - } catch (BadLocationException x) { - } - - if (word != null) { - try { - return doc.get(word.x, word.y); - } catch (BadLocationException e) { - } - } - return ""; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java deleted file mode 100644 index 4e3dcea..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java +++ /dev/null @@ -1,1029 +0,0 @@ -package net.sourceforge.phpeclipse.builder; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedMap; -import java.util.StringTokenizer; -import java.util.TreeMap; - -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.compiler.util.Util; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.obfuscator.PHPIdentifier; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; - -/** - * Manages the identifer index information for a specific project - * - */ -public class IdentifierIndexManager { - public class LineCreator implements ITerminalSymbols { - private Scanner fScanner; - - private int fToken; - - public LineCreator() { - fScanner = new Scanner(true, false, false, false, true, null, null, - true /* taskCaseSensitive */); - } - - /** - * Add the information of the current identifier to the line - * - * @param typeOfIdentifier - * the type of the identifier ('c'lass, 'd'efine, 'f'unction, - * 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) - * @param identifier - * current identifier - * @param line - * Buffer for the current index line - */ - private void addIdentifierInformation(char typeOfIdentifier, - char[] identifier, StringBuffer line) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - } - - /** - * Add the information of the current identifier to the line - * - * @param typeOfIdentifier - * the type of the identifier ('c'lass, 'd'efine, 'f'unction, - * 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) - * @param identifier - * current identifier - * @param line - * Buffer for the current index line - * @param phpdocOffset - * the offset of the PHPdoc comment if available - * @param phpdocLength - * the length of the PHPdoc comment if available - */ - private void addIdentifierInformation(char typeOfIdentifier, - char[] identifier, StringBuffer line, int phpdocOffset, - int phpdocLength) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - line.append("\to"); // Offset - line.append(fScanner.getCurrentTokenStartPosition()); - if (phpdocOffset >= 0) { - line.append("\tp"); // phpdoc offset - line.append(phpdocOffset); - line.append("\tl"); // phpdoc length - line.append(phpdocLength); - } - } - - private void addClassVariableInformation(char typeOfIdentifier, - char[] identifier, StringBuffer line, int phpdocOffset, - int phpdocLength) { - line.append('\t'); - line.append(typeOfIdentifier); - line.append(identifier); - line.append("\to"); // Offset - // we don't store the '$' in the index for class variables: - line.append(fScanner.getCurrentTokenStartPosition() + 1); - if (phpdocOffset >= 0) { - line.append("\tp"); // phpdoc offset - line.append(phpdocOffset); - line.append("\tl"); // phpdoc length - line.append(phpdocLength); - } - } - - /** - * Get the next token from input - */ - private void getNextToken() throws InvalidInputException { - // try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner - .getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," - + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - } - - private void skipComments() - { - try { - getNextToken(); - while (fToken == TokenNameCOMMENT_BLOCK || fToken == TokenNameCOMMENT_PHPDOC) { - getNextToken(); - } - } catch (InvalidInputException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - private void parseDeclarations(char[] parent, StringBuffer buf, - boolean goBack) { - char[] ident; - char[] classVariable; - int counter = 0; - boolean hasModifiers = false; - int phpdocOffset = -1; - int phpdocLength = -1; - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - phpdocOffset = -1; - hasModifiers = false; - if (fToken == TokenNameCOMMENT_PHPDOC) { - phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - - fScanner.getCurrentTokenStartPosition() + 1; - getNextToken(); - while (fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate - || fToken == TokenNameabstract) { - hasModifiers = true; - getNextToken(); - } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { - break; - } - } - if (fToken == TokenNamefunction) { - skipComments(); - if (fToken == TokenNameAND) { - getNextToken(); - } - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - if (parent != null - && equalCharArrays(parent, ident)) { - // constructor function - addIdentifierInformation('k', ident, buf, - phpdocOffset, phpdocLength); - } else { - if (parent != null) { - // class method function - addIdentifierInformation('m', ident, buf, - phpdocOffset, phpdocLength); - } else { - // nested function ?! - addIdentifierInformation('f', ident, buf, - phpdocOffset, phpdocLength); - } - } - skipComments(); - parseDeclarations(null, buf, true); - } - } else if (fToken == TokenNameclass - || fToken == TokenNameinterface) { - skipComments(); - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, - phpdocOffset, phpdocLength); - skipComments(); - if (fToken == TokenNameextends) { - skipComments(); - while (fToken == TokenNameIdentifier) { - ident = fScanner - .getCurrentIdentifierSource(); - // extends ident - addIdentifierInformation('e', ident, buf); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); - } - } - } - if (fToken == TokenNameimplements) { - skipComments(); - while (fToken == TokenNameIdentifier) { - ident = fScanner - .getCurrentIdentifierSource(); - // implements ident - addIdentifierInformation('e', ident, buf); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); -// getNextToken(); - } - } - } - // skip tokens for classname, extends and others - // until we have - // the opening '{' - while (fToken != TokenNameLBRACE - && fToken != TokenNameEOF - && fToken != TokenNameERROR) { - getNextToken(); - } - parseDeclarations(ident, buf, true); - } - } else if (fToken == TokenNamevar || hasModifiers - || fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate) { - while (fToken == TokenNamevar - || fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate) { - skipComments(); - } - while (fToken == TokenNameVariable) { - ident = fScanner.getCurrentIdentifierSource(); - classVariable = new char[ident.length - 1]; - System.arraycopy(ident, 1, classVariable, 0, - ident.length - 1); - addClassVariableInformation('v', classVariable, - buf, phpdocOffset, phpdocLength); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); - } - } - } else if (!hasModifiers && fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - getNextToken(); - if (ident.length == 6 && ident[0] == 'd' - && ident[1] == 'e' && ident[2] == 'f' - && ident[3] == 'i' && ident[4] == 'n' - && ident[5] == 'e') { - if (fToken == TokenNameLPAREN) { - getNextToken(); - if (fToken == TokenNameStringDoubleQuote) { - ident = fScanner - .getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, - phpdocOffset, phpdocLength); - getNextToken(); - } else if (fToken == TokenNameStringSingleQuote) { - ident = fScanner - .getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, - phpdocOffset, phpdocLength); - getNextToken(); - } - } - } - } else if (fToken == TokenNameglobal) { - // global variable - while (fToken != TokenNameEOF - && fToken != TokenNameERROR - && fToken != TokenNameSEMICOLON - && fToken != TokenNameLBRACE - && fToken != TokenNameRBRACE) { - getNextToken(); - if (fToken == TokenNameVariable) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, - phpdocOffset, phpdocLength); - } - } - } else if (fToken == TokenNameLBRACE) { - getNextToken(); - counter++; - } else if (fToken == TokenNameRBRACE) { - getNextToken(); - --counter; - if (counter == 0 && goBack) { - return; - } - } else { - getNextToken(); - } - } - } catch (InvalidInputException e) { - // ignore errors - } catch (SyntaxError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - synchronized public void parseIdentifiers(char[] charArray, - StringBuffer buf) { - char[] ident; - String identifier; - boolean hasModifiers = false; - int phpdocOffset = -1; - int phpdocLength = -1; - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - try { - getNextToken(); - while (fToken != TokenNameEOF) { // && fToken != - // TokenNameERROR) { - phpdocOffset = -1; - hasModifiers = false; - switch (fToken) { - case TokenNameCOMMENT_PHPDOC: - phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - - fScanner.getCurrentTokenStartPosition() + 1; - getNextToken(); - while (fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate - || fToken == TokenNameabstract) { - hasModifiers = true; - getNextToken(); - } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { - break; - } - break; - - case TokenNamefunction: - skipComments(); - if (fToken == TokenNameAND) { - getNextToken(); - } - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('f', ident, buf, - phpdocOffset, phpdocLength); - skipComments(); - if (fToken == TokenNameLPAREN) { - skipComments(); - do { - if (fToken == TokenNameVariable) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('v', ident, buf, - phpdocOffset, phpdocLength); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); - } - } - } while (fToken != TokenNameRPAREN ); - } - parseDeclarations(null, buf, true); - } - break; - - case TokenNameclass: - case TokenNameinterface: - skipComments(); - if (fToken == TokenNameIdentifier) { - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, - phpdocOffset, phpdocLength); - skipComments(); - if (fToken == TokenNameextends) { - skipComments(); - while (fToken == TokenNameIdentifier) { - ident = fScanner - .getCurrentIdentifierSource(); - // extends ident - addIdentifierInformation('e', ident, buf); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); - } - } - } - if (fToken == TokenNameimplements) { - skipComments(); - while (fToken == TokenNameIdentifier) { - ident = fScanner - .getCurrentIdentifierSource(); - // implements ident - addIdentifierInformation('e', ident, buf); - skipComments(); - if (fToken == TokenNameCOMMA) { - skipComments(); - } - } - } - // skip fTokens for classname, extends and others - // until we have - // the opening '{' - while (fToken != TokenNameLBRACE - && fToken != TokenNameEOF - && fToken != TokenNameERROR) { - getNextToken(); - } - parseDeclarations(ident, buf, true); - } - break; - - case TokenNameVariable: - // global variable - ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, phpdocOffset, - phpdocLength); - getNextToken(); - break; - - default: - getNextToken(); - } - - } - } catch (InvalidInputException e) { - // ignore errors - } catch (SyntaxError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - class StringComparator implements Comparator { - public int compare(Object o1, Object o2) { - String s1 = (String) o1; - String s2 = (String) o2; - return s1.compareTo(s2); - // return s1.toUpperCase().compareTo(s2.toUpperCase()); - } - - public boolean equals(Object o) { - //String s = (String) o; - return compare(this, o) == 0; - } - } - - private HashMap fFileMap; - - private String fFilename; - - private TreeMap fIndentifierMap; - - public IdentifierIndexManager(String filename) { - fFilename = filename; - initialize(); - readFile(); - } - - /** - * Check if 2 char arrays are equal - * - * @param a - * @param b - * @return - */ - private static boolean equalCharArrays(char[] a, char[] b) { - if (a.length != b.length) { - return false; - } - for (int i = 0; i < b.length; i++) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - - public LineCreator createLineCreator() { - return new LineCreator(); - } - - /** - * Add the information for a given IFile resource - * - */ - public void addFile(IFile fileToParse) { - LineCreator lineCreator = createLineCreator(); - try { - addInputStream(new BufferedInputStream(fileToParse.getContents()), - fileToParse.getProjectRelativePath().toString(), - lineCreator, fileToParse.getCharset()); - } catch (CoreException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - - /** - * @param fileToParse - * @param lineCreator - * @throws CoreException - */ - public void addInputStream(InputStream stream, String filePath, - LineCreator lineCreator, String charset) throws CoreException { - try { - StringBuffer lineBuffer = new StringBuffer(); - lineBuffer.append(filePath); - lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, - -1, charset), lineBuffer); - addLine(lineBuffer.toString()); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - // do nothing - } - } - } - - /** - * Adds a line of the index file for function, class, class-method and - * class-variable names - * - * @param line - */ - private void addLine(String line) { - addLine(fIndentifierMap, fFileMap, line, null); - } - - public TreeMap getIdentifiers(IFile file) { - TreeMap treeMap = new TreeMap(new StringComparator()); - addIdentifiers(treeMap, file); - return treeMap; - } - - public TreeMap getIdentifiers(String startClazz) { - TreeMap treeMap = new TreeMap(new StringComparator()); - addIdentifiers(treeMap, startClazz); - return treeMap; - } - - public void addIdentifiers(TreeMap treeMap, IFile file) { - String line = (String) fFileMap.get(file.getProjectRelativePath() - .toString()); - if (line != null) { - //PHPIdentifierLocation ident; - ArrayList allClassNames = new ArrayList(); - addLine(treeMap, null, line, allClassNames); - int i = 0; - while (i < allClassNames.size()) { - String clazz = (String) allClassNames.get(i++); - addClassName(treeMap, clazz, allClassNames); - } - } - } - - public void addIdentifiers(TreeMap treeMap, String startClazz) { - //PHPIdentifierLocation ident; - ArrayList allClassNames = new ArrayList(); - addClassName(treeMap, startClazz, allClassNames); - int i = 0; - while (i < allClassNames.size()) { - String clazz = (String) allClassNames.get(i++); - addClassName(treeMap, clazz, allClassNames); - } - } - - /** - * @param treeMap - * @param clazz - * @param allClassNames - */ - private boolean addClassName(TreeMap treeMap, String clazz, - List allClassNames) { - String line; - PHPIdentifierLocation ident; - List list = getLocations(clazz); - if (list == null) { - return false; - } - boolean result = false; - for (int i = 0; i < list.size(); i++) { - ident = (PHPIdentifierLocation) list.get(i); - if (ident.isClass()) { - line = (String) fFileMap.get(ident.getFilename()); - addLine(treeMap, null, line, allClassNames); - result = true; - } - } - return result; - } - - /** - * Adds a line of the index file for function, class, class-method and - * class-variable names - * - * @param line - */ - public void addLine(TreeMap treeMap, HashMap fileMap, String line, - List allClassNames) { - StringTokenizer tokenizer; - String phpFileName = null; - String token; - String identifier = null; - String classname = null; - String offset = null; - PHPIdentifierLocation phpIdentifier = null; - boolean tokenExists = false; - tokenizer = new StringTokenizer(line, "\t"); - // first token contains the filename: - try { - if (tokenizer.hasMoreTokens()) { - phpFileName = tokenizer.nextToken(); - // System.out.println(token); - } else { - return; - } - // all the other tokens are identifiers: - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - // System.out.println(token); - switch (token.charAt(0)) { - case 'c': - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CLASS, phpFileName); - break; - case 'd': - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.DEFINE, phpFileName); - break; - case 'e': - // extends - // not in map - identifier = null; - phpIdentifier = null; - if (allClassNames != null) { - String extName = token.substring(1); - if (!allClassNames.contains(extName)) { - allClassNames.add(extName); - } - } - break; - case 'f': - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g': - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'i': - // implements - // not in map - identifier = null; - phpIdentifier = null; - if (allClassNames != null) { - String implName = token.substring(1); - if (!allClassNames.contains(implName)) { - allClassNames.add(implName); - } - } - break; - case 'k': - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm': - // method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'v': - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.VARIABLE, phpFileName, classname); - break; - case 'o': - // offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setOffset(Integer.parseInt(offset)); - } - break; - case 'p': - // PHPdoc offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocOffset(Integer.parseInt(offset)); - } - break; - case 'l': - // PHPdoc length information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocLength(Integer.parseInt(offset)); - } - break; - default: - PHPeclipsePlugin.log(IStatus.ERROR, - "Unknown token character in IdentifierIndexManager: " - + token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; - } - if (identifier != null && phpIdentifier != null) { - tokenExists = true; - ArrayList list = (ArrayList) treeMap.get(identifier); - if (list == null) { - list = new ArrayList(); - list.add(phpIdentifier); - treeMap.put(identifier, list); - } else { - boolean flag = false; - for (int i = 0; i < list.size(); i++) { - if (list.get(i).equals(phpIdentifier)) { - flag = true; - break; - } - } - if (flag == false) { - list.add(phpIdentifier); - } - } - } - } - if (fileMap != null) { - fileMap.put(phpFileName, line); - } - } catch (Throwable e) { - // write to workspace/.metadata/.log file - PHPeclipsePlugin.log(e); - } - // if (tokenExists) { - - // } - } - - /** - * Change the information for a given IFile resource - * - */ - public void changeFile(IFile fileToParse) { - removeFile(fileToParse); - addFile(fileToParse); - } - - /** - * Get a list of all PHPIdentifierLocation object's associated with an - * identifier - * - * @param identifier - * @return - */ - public List getLocations(String identifier) { - List list = (List) fIndentifierMap.get(identifier); - if (list != null) { - return list; - } - return new ArrayList(); - } - - /** - * Initialize (i.e. clear) the current index information - * - */ - public void initialize() { - fIndentifierMap = new TreeMap(new StringComparator()); - fFileMap = new HashMap(); - } - - private void readFile() { - FileReader fileReader; - try { - fileReader = new FileReader(fFilename); - BufferedReader bufferedReader = new BufferedReader(fileReader); - String line; - while (bufferedReader.ready()) { - // all entries for one file are in a line - // separated by tabs ! - line = bufferedReader.readLine(); - addLine(line); - } - fileReader.close(); - } catch (FileNotFoundException e) { - // ignore this - // TODO DialogBox which asks the user if she/he likes to build new - // index? - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * Remove the information for a given IFile resource - * - */ - public void removeFile(IFile fileToParse) { - // String line = (String) - // fFileMap.get(fileToParse.getLocation().toString()); - String line = (String) fFileMap.get(fileToParse - .getProjectRelativePath().toString()); - if (line != null) { - removeLine(line); - } - } - - /** - * Removes a line of the index file for function, class, class-method and - * class-variable names - * - * @param line - */ - private void removeLine(String line) { - StringTokenizer tokenizer; - String phpFileName = null; - String token; - String identifier = null; - String classname = null; - PHPIdentifier phpIdentifier = null; - boolean tokenExists = false; - tokenizer = new StringTokenizer(line, "\t"); - // first token contains the filename: - if (tokenizer.hasMoreTokens()) { - phpFileName = tokenizer.nextToken(); - // System.out.println(token); - } else { - return; - } - int offset = -1; - // all the other tokens are identifiers: - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - // System.out.println(token); - switch (token.charAt(0)) { - case 'c': - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CLASS, phpFileName); - break; - case 'd': - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.DEFINE, phpFileName); - break; - case 'e': - // extends - identifier = null; - phpIdentifier = null; - break; - case 'f': - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g': - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'i': - // implements - identifier = null; - phpIdentifier = null; - break; - case 'k': - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm': - // method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'o': - // offset information - identifier = null; - break; - case 'p': - // PHPdoc offset information - identifier = null; - break; - case 'l': - // PHPdoc length information - identifier = null; - break; - case 'v': - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.VARIABLE, phpFileName, classname); - break; - default: - PHPeclipsePlugin.log(IStatus.ERROR, - "Unknown token character in IdentifierIndexManager: " - + token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; - } - if (identifier != null && phpIdentifier != null) { - ArrayList list = (ArrayList) fIndentifierMap.get(identifier); - if (list == null) { - } else { - for (int i = 0; i < list.size(); i++) { - if (list.get(i).equals(phpIdentifier)) { - list.remove(i); - break; - } - } - if (list.size() == 0) { - fIndentifierMap.remove(identifier); - } - } - } - } - fFileMap.remove(phpFileName); - } - - /** - * Save the current index information in the projects index file - * - */ - public void writeFile() { - FileWriter fileWriter; - try { - fileWriter = new FileWriter(fFilename); - String line; - Collection collection = fFileMap.values(); - Iterator iterator = collection.iterator(); - while (iterator.hasNext()) { - line = (String) iterator.next(); - fileWriter.write(line + '\n'); - } - fileWriter.close(); - } catch (FileNotFoundException e) { - // ignore exception; project is deleted by user - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * @param fromKey - * @param toKey - * @return - */ - public SortedMap getIdentifierMap() { - return fIndentifierMap; - } - - synchronized public List getFileList(String filePattern) { - Set set = fFileMap.keySet(); - if (set.isEmpty()) { - return null; - } - Iterator iter = set.iterator(); - ArrayList list = new ArrayList(); - String fileName; - int index; - while (iter.hasNext()) { - fileName = (String) iter.next(); - if ((index = fileName.indexOf(filePattern)) != -1 - && fileName.length() == (index + filePattern.length())) { - list.add(fileName); - } - } - return list; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java deleted file mode 100644 index afad5af..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/PHPIdentifierLocation.java +++ /dev/null @@ -1,193 +0,0 @@ -package net.sourceforge.phpeclipse.builder; - -import net.sourceforge.phpeclipse.obfuscator.PHPIdentifier; - -/** - * - */ -public class PHPIdentifierLocation extends PHPIdentifier implements Comparable { - final public static int UNDEFINED_MATCH = 0; - - final public static int PATTERN_MATCH = 1; - - final public static int EXACT_MATCH = 2; - - private int fMatch; - - private String fClassname; - - private String fFilename; - - private int fOffset; - - private int fPHPDocLength; - - private int fPHPDocOffset; - - private String fUsage; - - public PHPIdentifierLocation(String identifier, int type, String filename) { - this(identifier, type, filename, null); - } - - public PHPIdentifierLocation(String identifier, int type, String filename, - String classname) { - super(identifier, type); - fFilename = filename; - fClassname = classname; - fOffset = -1; - fPHPDocLength = -1; - fPHPDocOffset = -1; - fUsage = null; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (!(obj instanceof PHPIdentifierLocation)) { - return false; - } - return super.equals(obj) - && fFilename.equals(((PHPIdentifierLocation) obj).fFilename); - } - - /** - * @return - */ - public String getClassname() { - return fClassname; - } - - /** - * @return - */ - public String getFilename() { - return fFilename; - } - - /** - * @return - */ - public int getOffset() { - return fOffset; - } - - /** - * @return - */ - public int getPHPDocLength() { - return fPHPDocLength; - } - - /** - * @return - */ - public int getPHPDocOffset() { - return fPHPDocOffset; - } - - /** - * @return - */ - public String getUsage() { - return fUsage; - } - - /** - * @param string - */ - public void setClassname(String string) { - fClassname = string; - } - - /** - * @param string - */ - public void setFilename(String string) { - fFilename = string; - } - - /** - * @param i - */ - public void setOffset(int i) { - fOffset = i; - } - - /** - * @param i - */ - public void setPHPDocLength(int i) { - fPHPDocLength = i; - } - - /** - * @param i - */ - public void setPHPDocOffset(int i) { - fPHPDocOffset = i; - } - - /** - * @param string - */ - public void setUsage(String string) { - fUsage = string; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - String result = null; - switch (fMatch) { - case UNDEFINED_MATCH: - result = " ["; - break; - case PATTERN_MATCH: - result = " [pattern include]["; - break; - case EXACT_MATCH: - result = " [exact include]["; - break; - default: - result = ""; - } - return super.toString() + result + fFilename + "]"; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - public int compareTo(Object o) { - PHPIdentifierLocation i = (PHPIdentifierLocation) o; - if (fMatch > i.fMatch) { - return -1; - } else if (fMatch < i.fMatch) { - return 1; - } - return fFilename.compareTo(i.fFilename); - } - - /** - * @return Returns the match. - */ - public int getMatch() { - return fMatch; - } - - /** - * @param match - * The match to set. - */ - public void setMatch(int match) { - fMatch = match; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java deleted file mode 100644 index 19597bb..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java +++ /dev/null @@ -1,258 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.obfuscator; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; - -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.compiler.util.Util; -import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.ui.WebUI; - -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.IPath; -//import org.eclipse.jface.preference.IPreferenceStore; - -/** - * Analyzing php files in a first pass over all resources ! - */ -public class ObfuscatorPass1Exporter implements ITerminalSymbols { - - protected Scanner fScanner; - - protected int fToken; - - protected HashMap fIdentifierMap; - - public ObfuscatorPass1Exporter(Scanner scanner, HashMap identifierMap) { - fScanner = scanner; - fIdentifierMap = identifierMap; - } - - /** - * Get the next token from input - */ - private void getNextToken() { - - try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner - .getCurrentTokenStartPosition(); - - System.out.print(currentStartPosition + "," - + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - } catch (InvalidInputException e) { - - } - fToken = TokenNameERROR; - } - - private void parseIdentifiers(boolean goBack) { - //char[] ident; - String identifier; - PHPIdentifier value; - int counter = 0; - -// IPreferenceStore store = WebUI.getDefault() -// .getPreferenceStore(); - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - if (fToken == TokenNameVariable) { - identifier = new String(fScanner - .getCurrentIdentifierSource()); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value == null) { - fIdentifierMap.put(identifier, new PHPIdentifier(null, - PHPIdentifier.VARIABLE)); - } - getNextToken(); - // } else if (fToken == TokenNamefunction) { - // getNextToken(); - // if (fToken == TokenNameAND) { - // getNextToken(); - // } - // if (fToken == TokenNameIdentifier) { - // ident = fScanner.getCurrentIdentifierSource(); - // outlineInfo.addVariable(new String(ident)); - // temp = new PHPFunctionDeclaration(current, new - // String(ident), fScanner.getCurrentTokenStartPosition()); - // current.add(temp); - // getNextToken(); - // parseDeclarations(outlineInfo, temp, true); - // } - // } else if (fToken == TokenNameclass) { - // getNextToken(); - // if (fToken == TokenNameIdentifier) { - // ident = fScanner.getCurrentIdentifierSource(); - // outlineInfo.addVariable(new String(ident)); - // temp = new PHPClassDeclaration(current, new - // String(ident), fScanner.getCurrentTokenStartPosition()); - // current.add(temp); - // getNextToken(); - // - // //skip fTokens for classname, extends and others until we - // have the opening '{' - // while (fToken != TokenNameLBRACE && fToken != - // TokenNameEOF && fToken != TokenNameERROR) { - // getNextToken(); - // } - // parseDeclarations(outlineInfo, temp, true); - // // stack.pop(); - // } - } else if (fToken == TokenNameStringDoubleQuote) { - char currentCharacter; - int i = fScanner.startPosition; - ArrayList varList = new ArrayList(); - - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (currentCharacter == '$' - && fScanner.source[i - 2] != '\\') { - StringBuffer varName = new StringBuffer(); - varName.append("$"); - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (!Scanner - .isPHPIdentifierPart(currentCharacter)) { - break; // while loop - } - varName.append(currentCharacter); - } - varList.add(varName.toString()); - } - } - - for (i = 0; i < varList.size(); i++) { - identifier = (String) varList.get(i); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value == null) { - fIdentifierMap.put(identifier, new PHPIdentifier( - null, PHPIdentifier.VARIABLE)); - } - } - - getNextToken(); - } else if (fToken == TokenNameLBRACE) { - getNextToken(); - counter++; - } else if (fToken == TokenNameRBRACE) { - getNextToken(); - --counter; - if (counter == 0 && goBack) { - return; - } - } else { - getNextToken(); - } - } - } catch (SyntaxError sytaxErr) { - // do nothing - } - } - - /** - * Do nothing in first pass - */ - public void createFolder(IPath destinationPath) { - // do nothing here - // new File(destinationPath.toOSString()).mkdir(); - } - - /** - * Writes the passed resource to the specified location recursively - */ - public void write(IResource resource, IPath destinationPath) - throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else - writeChildren((IContainer) resource, destinationPath); - } - - /** - * Exports the passed container's children - */ - protected void writeChildren(IContainer folder, IPath destinationPath) - throws CoreException, IOException { - if (folder.isAccessible()) { - IResource[] children = folder.members(); - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - writeResource(child, destinationPath.append(child.getName())); - } - } - } - - /** - * Analyzes the passed file resource for the PHP obfuscator - */ - protected void writeFile(IFile file, IPath destinationPath) - throws IOException, CoreException { - if (!PHPFileUtil.isPHPFile(file)) { - return; - } - InputStream stream = null; - char[] charArray = null; - try { - stream = new BufferedInputStream(file.getContents()); - charArray = Util.getInputStreamAsCharArray(stream, -1, null); - } catch (IOException e) { - return; - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - - if (charArray == null) { - // TODO show error message - return; - } - /* fScanner initialization */ - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - getNextToken(); - parseIdentifiers(false); - } - - /** - * Writes the passed resource to the specified location recursively - */ - protected void writeResource(IResource resource, IPath destinationPath) - throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else { - createFolder(destinationPath); - writeChildren((IContainer) resource, destinationPath); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java deleted file mode 100644 index 1339fa3..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java +++ /dev/null @@ -1,382 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.obfuscator; - -import java.io.BufferedInputStream; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; - -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.compiler.util.Util; -import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.ui.WebUI; - -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.IPath; -//import org.eclipse.jface.preference.IPreferenceStore; - -/** - * Helper class for exporting resources to the file system. - */ -public class ObfuscatorPass2Exporter implements ITerminalSymbols { - private Scanner fScanner; - - private int fToken; - - private int fCounter; - - protected HashMap fIdentifierMap; - - public ObfuscatorPass2Exporter(Scanner scanner, HashMap identifierMap) { - fScanner = scanner; - fIdentifierMap = identifierMap; - fCounter = 0; - } - - /** - * gets the next token from input - */ - private void getNextToken() { - - try { - fToken = fScanner.getNextToken(); - if (Scanner.DEBUG) { - int currentEndPosition = fScanner.getCurrentTokenEndPosition(); - int currentStartPosition = fScanner - .getCurrentTokenStartPosition(); - - System.out.print(currentStartPosition + "," - + currentEndPosition + ": "); - System.out.println(fScanner.toStringAction(fToken)); - } - return; - } catch (InvalidInputException e) { - - } - fToken = TokenNameERROR; - } - - private boolean obfuscate(StringBuffer buf) { - //char[] ident; - String identifier; - PHPIdentifier value; - - int startPosition = 0; - int lastPosition = 0; - -// IPreferenceStore store = WebUI.getDefault() -// .getPreferenceStore(); - try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { - if (fToken == TokenNameVariable) { - identifier = new String(fScanner - .getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - buf.append("$v" + Integer.toString(fCounter)); - value.setIdentifier("$v" - + Integer.toString(fCounter++)); - } else { - buf.append(obfuscatedIdentifier); - } - // System.out.println(hexString.toString()); - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - } else if (fToken == TokenNameIdentifier) { - identifier = new String(fScanner - .getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get(identifier); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - buf.append("_" + Integer.toString(fCounter)); - value.setIdentifier("_" - + Integer.toString(fCounter++)); - } else { - buf.append(obfuscatedIdentifier); - } - // System.out.println(hexString.toString()); - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - - } else if (fToken == TokenNameCOMMENT_LINE - || fToken == TokenNameCOMMENT_BLOCK - || fToken == TokenNameCOMMENT_PHPDOC) { - lastPosition = fScanner.startPosition; - buf.append(fScanner.source, startPosition, lastPosition - - startPosition); - startPosition = fScanner.currentPosition; - getNextToken(); - } else if (fToken == TokenNameStringDoubleQuote) { - char currentCharacter; - int i = fScanner.startPosition; - ArrayList varList = new ArrayList(); - - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (currentCharacter == '$' - && fScanner.source[i - 2] != '\\') { - StringBuffer varName = new StringBuffer(); - varName.append("$"); - while (i < fScanner.currentPosition) { - currentCharacter = fScanner.source[i++]; - if (!Scanner - .isPHPIdentifierPart(currentCharacter)) { - break; // while loop - } - varName.append(currentCharacter); - } - varList.add(varName.toString()); - } - } - StringBuffer stringLiteral = new StringBuffer(); - stringLiteral.append(fScanner.source, - fScanner.startPosition, fScanner.currentPosition - - fScanner.startPosition); - String stringIdent; - String replacement; - int index; - - for (int j = 0; j < varList.size(); j++) { - stringIdent = (String) varList.get(j); - len = stringIdent.length(); - value = (PHPIdentifier) fIdentifierMap.get(stringIdent); - if (value != null) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - replacement = "$v" + Integer.toString(fCounter); - value.setIdentifier("$v" - + Integer.toString(fCounter++)); - } else { - replacement = obfuscatedIdentifier; - } - // System.out.println(hexString.toString()); - } else { - replacement = stringIdent; - } - index = stringLiteral.indexOf(stringIdent); - if (index >= 0) { - if (index > 0 - && stringLiteral.charAt(index - 1) != '\\') { - stringLiteral.replace(index, index - + stringIdent.length(), replacement); - } else if (index == 0) { - stringLiteral.replace(index, index - + stringIdent.length(), replacement); - } - } - } - buf.append(stringLiteral); - startPosition = fScanner.currentPosition; - getNextToken(); - } - if (fToken == TokenNameMINUS_GREATER) { // i.e. $this->var_name - getNextToken(); - if (fToken == TokenNameIdentifier) { - // assuming this is a dereferenced variable - identifier = new String(fScanner - .getCurrentIdentifierSource()); - lastPosition = fScanner.startPosition; - int len = lastPosition - startPosition; - buf.append(fScanner.source, startPosition, len); - value = (PHPIdentifier) fIdentifierMap.get("$" - + identifier); - if (value != null && value.isVariable()) { - String obfuscatedIdentifier = value.getIdentifier(); - if (obfuscatedIdentifier == null) { - // note: don't place a $ before the identifier - buf.append("v" + Integer.toString(fCounter)); - value.setIdentifier("$v" - + Integer.toString(fCounter++)); - } else { - if (obfuscatedIdentifier.charAt(0) == '$') { - buf.append(obfuscatedIdentifier - .substring(1)); - } else { - buf.append(obfuscatedIdentifier); - } - } - } else { - buf.append(identifier); - } - startPosition = fScanner.currentPosition; - getNextToken(); - } - - } else { - getNextToken(); - } - } - if (startPosition < fScanner.source.length) { - buf.append(fScanner.source, startPosition, - fScanner.source.length - startPosition); - } - return true; - } catch (SyntaxError sytaxErr) { - // do nothing - } - - return false; - } - - /** - * Creates the specified file system directory at - * destinationPath. This creates a new file system - * directory. - */ - public void createFolder(IPath destinationPath) { - new File(destinationPath.toOSString()).mkdir(); - } - - /** - * Writes the passed resource to the specified location recursively - */ - public void write(IResource resource, IPath destinationPath) - throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else - writeChildren((IContainer) resource, destinationPath); - } - - /** - * Exports the passed container's children - */ - protected void writeChildren(IContainer folder, IPath destinationPath) - throws CoreException, IOException { - if (folder.isAccessible()) { - IResource[] children = folder.members(); - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - writeResource(child, destinationPath.append(child.getName())); - } - } - } - - /** - * Writes the passed file resource to the specified destination on the local - * file system - */ - protected void writeFile(IFile file, IPath destinationPath) - throws IOException, CoreException { - if (PHPFileUtil.isPHPFile(file)) { - InputStream stream = null; - char[] charArray = null; - try { - stream = new BufferedInputStream(file.getContents()); - charArray = Util.getInputStreamAsCharArray(stream, -1, null); - } catch (IOException e) { - return; - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - - if (charArray == null) { - // TODO show error message - return; - } - - fScanner.setSource(charArray); - fScanner.setPHPMode(false); - fToken = TokenNameEOF; - getNextToken(); - - StringBuffer buf = new StringBuffer(); - if (!obfuscate(buf)) { - copyFile(file, destinationPath); - } else { - // charArray = buf.toString().toCharArray(); - // File targetFile = new File(destinationPath.toOSString()); - BufferedWriter bw = new BufferedWriter(new FileWriter( - destinationPath.toOSString())); - bw.write(buf.toString()); - bw.close(); - } - - } else { - copyFile(file, destinationPath); - } - } - - private void copyFile(IFile file, IPath destinationPath) - throws FileNotFoundException, CoreException, IOException { - FileOutputStream output = null; - InputStream contentStream = null; - - try { - output = new FileOutputStream(destinationPath.toOSString()); - contentStream = file.getContents(false); - int chunkSize = contentStream.available(); - byte[] readBuffer = new byte[chunkSize]; - int n = contentStream.read(readBuffer); - - while (n > 0) { - output.write(readBuffer); - n = contentStream.read(readBuffer); - } - } finally { - if (output != null) - output.close(); - if (contentStream != null) - contentStream.close(); - } - } - - /** - * Writes the passed resource to the specified location recursively - */ - protected void writeResource(IResource resource, IPath destinationPath) - throws CoreException, IOException { - if (resource.getType() == IResource.FILE) - writeFile((IFile) resource, destinationPath); - else { - createFolder(destinationPath); - writeChildren((IContainer) resource, destinationPath); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java deleted file mode 100644 index fe09c63..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java +++ /dev/null @@ -1,742 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.obfuscator.export; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.obfuscator.ObfuscatorIgnores; -import net.sourceforge.phpeclipse.obfuscator.ObfuscatorPass1Exporter; -import net.sourceforge.phpeclipse.obfuscator.ObfuscatorPass2Exporter; -//import net.sourceforge.phpeclipse.ui.WebUI; - -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.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.operation.ModalContext; -//import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.IOverwriteQuery; - -/** - * Operation for exporting the contents of a resource to the local file system. - */ -/* package */ -class ObfuscatorExportOperation implements IRunnableWithProgress { - private IPath fPath; - - private IProgressMonitor fMonitor; - - private ObfuscatorPass1Exporter fExporter1 = null; - - private ObfuscatorPass2Exporter fExporter2 = null; - - private HashMap fCurrentIdentifierMap = null; - - private HashMap fProjectMap = null; - - private String fCurrentProjectName = ""; - - private List fResourcesToExport; - - private IOverwriteQuery fOverwriteCallback; - - private IResource fResource; - - private List errorTable = new ArrayList(1); - - // The constants for the overwrite 3 state - private static final int OVERWRITE_NOT_SET = 0; - - private static final int OVERWRITE_NONE = 1; - - private static final int OVERWRITE_ALL = 2; - - private int overwriteState = OVERWRITE_NOT_SET; - - // private boolean createLeadupStructure = true; - private boolean createContainerDirectories = true; - - /** - * Create an instance of this class. Use this constructor if you wish to - * export specific resources without a common parent resource - */ - // public ObfuscatorExportOperation(List resources, String destinationPath, - // IOverwriteQuery overwriteImplementor) { - // super(); - // - // exporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), - // identifierMap); - // exporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), - // identifierMap); - // identifierMap = null; - // - // // Eliminate redundancies in list of resources being exported - // Iterator elementsEnum = resources.iterator(); - // while (elementsEnum.hasNext()) { - // IResource currentResource = (IResource) elementsEnum.next(); - // if (isDescendent(resources, currentResource)) - // elementsEnum.remove(); //Remove currentResource - // } - // - // resourcesToExport = resources; - // path = new Path(destinationPath); - // overwriteCallback = overwriteImplementor; - // } - /** - * Create an instance of this class. Use this constructor if you wish to - * recursively export a single resource - */ - public ObfuscatorExportOperation(IResource res, String destinationPath, - IOverwriteQuery overwriteImplementor) { - super(); - - fResource = res; - fPath = new Path(destinationPath); - fOverwriteCallback = overwriteImplementor; - } - - /** - * Create an instance of this class. Use this constructor if you wish to - * export specific resources with a common parent resource (affects - * container directory creation) - */ - public ObfuscatorExportOperation(IResource res, List resources, - String destinationPath, IOverwriteQuery overwriteImplementor) { - this(res, destinationPath, overwriteImplementor); - fResourcesToExport = resources; - } - - /** - * Add a new entry to the error table with the passed information - */ - protected void addError(String message, Throwable e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - message, e)); - } - - /** - * Answer the total number of file resources that exist at or below self in - * the resources hierarchy. - * - * @return int - * @param resource - * org.eclipse.core.resources.IResource - */ - protected int countChildrenOf(IResource resource) throws CoreException { - if (resource.getType() == IResource.FILE) - return 1; - - int count = 0; - if (resource.isAccessible()) { - IResource[] children = ((IContainer) resource).members(); - for (int i = 0; i < children.length; i++) - count += countChildrenOf(children[i]); - } - - return count; - } - - /** - * Answer a boolean indicating the number of file resources that were - * specified for export - * - * @return int - */ - protected int countSelectedResources() throws CoreException { - int result = 0; - Iterator resources = fResourcesToExport.iterator(); - - while (resources.hasNext()) - result += countChildrenOf((IResource) resources.next()); - - return result; - } - - /** - * Create the directories required for exporting the passed resource, based - * upon its container hierarchy - * - * @param resource - * org.eclipse.core.resources.IResource - */ - protected void createLeadupDirectoriesFor(IResource resource) { - IPath resourcePath = resource.getFullPath().removeLastSegments(1); - - for (int i = 0; i < resourcePath.segmentCount(); i++) { - fPath = fPath.append(resourcePath.segment(i)); - fExporter2.createFolder(fPath); - } - } - - /** - * Recursively export the previously-specified resource - */ - protected void exportAllResources1() throws InterruptedException { - if (fResource.getType() == IResource.FILE) { - exportFile1((IFile) fResource, fPath); - } else { - try { - setExporters(fResource); - exportChildren1(((IContainer) fResource).members(), fPath); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because the file system export wizard - // ensures that the - // single resource chosen for export is both existent and - // accessible - errorTable.add(e); - } - } - } - - /** - * Recursively export the previously-specified resource - */ - protected void exportAllResources2() throws InterruptedException { - if (fResource.getType() == IResource.FILE) { - exportFile2((IFile) fResource, fPath); - } else { - try { - setExporters(fResource); - exportChildren2(((IContainer) fResource).members(), fPath); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because the file system export wizard - // ensures that the - // single resource chosen for export is both existent and - // accessible - errorTable.add(e); - } - } - } - - /** - * Export all of the resources contained in the passed collection - * - * @param children - * java.util.Enumeration - * @param currentPath - * IPath - */ - protected void exportChildren1(IResource[] children, IPath currentPath) - throws InterruptedException { - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - if (!child.isAccessible()) - continue; - - if (child.getType() == IResource.FILE) - exportFile1((IFile) child, currentPath); - else { - IPath destination = currentPath.append(child.getName()); - fExporter1.createFolder(destination); - try { - exportChildren1(((IContainer) child).members(), destination); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because: - // i. this method is called recursively iterating over the - // result of #members, - // which only answers existing children - // ii. there is an #isAccessible check done before #members - // is invoked - errorTable.add(e.getStatus()); - } - } - } - } - - /** - * Export all of the resources contained in the passed collection - * - * @param children - * java.util.Enumeration - * @param currentPath - * IPath - */ - protected void exportChildren2(IResource[] children, IPath currentPath) - throws InterruptedException { - for (int i = 0; i < children.length; i++) { - IResource child = children[i]; - if (!child.isAccessible()) - continue; - - if (child.getType() == IResource.FILE) - exportFile2((IFile) child, currentPath); - else { - IPath destination = currentPath.append(child.getName()); - fExporter2.createFolder(destination); - try { - exportChildren2(((IContainer) child).members(), destination); - } catch (CoreException e) { - // not safe to show a dialog - // should never happen because: - // i. this method is called recursively iterating over the - // result of #members, - // which only answers existing children - // ii. there is an #isAccessible check done before #members - // is invoked - errorTable.add(e.getStatus()); - } - } - } - } - - protected void exportFile1(IFile file, IPath location) - throws InterruptedException { - IPath fullPath = location.append(file.getName()); - fMonitor.subTask(file.getFullPath().toString()); - //String properPathString = fullPath.toOSString(); - //File targetFile = new File(properPathString); - - // if (targetFile.exists()) { - // if (!targetFile.canWrite()) { - // errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - // ObfuscatorExportMessages.format("ObfuscatorTransfer.cannotOverwrite", - // //$NON-NLS-1$ - // new Object[] { targetFile.getAbsolutePath()}), null)); - // monitor.worked(1); - // return; - // } - // - // if (overwriteState == OVERWRITE_NONE) - // return; - // - // if (overwriteState != OVERWRITE_ALL) { - // String overwriteAnswer = - // overwriteCallback.queryOverwrite(properPathString); - // - // if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) - // throw new InterruptedException(); - // - // if (overwriteAnswer.equals(IOverwriteQuery.NO)) { - // monitor.worked(1); - // return; - // } - // - // if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { - // monitor.worked(1); - // overwriteState = OVERWRITE_NONE; - // return; - // } - // - // if (overwriteAnswer.equals(IOverwriteQuery.ALL)) - // overwriteState = OVERWRITE_ALL; - // } - // } - - try { - setExporters(file); - fExporter1.write(file, fullPath); - } catch (IOException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - ObfuscatorExportMessages.format( - "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage() }), e)); - } catch (CoreException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - ObfuscatorExportMessages.format( - "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage() }), e)); - } - - fMonitor.worked(1); - ModalContext.checkCanceled(fMonitor); - } - - /** - * Export the passed file to the specified location - * - * @param file - * org.eclipse.core.resources.IFile - * @param location - * org.eclipse.core.runtime.IPath - */ - protected void exportFile2(IFile file, IPath location) - throws InterruptedException { - IPath fullPath = location.append(file.getName()); - fMonitor.subTask(file.getFullPath().toString()); - String properPathString = fullPath.toOSString(); - File targetFile = new File(properPathString); - - if (targetFile.exists()) { - if (!targetFile.canWrite()) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, - 0, ObfuscatorExportMessages.format( - "ObfuscatorTransfer.cannotOverwrite", //$NON-NLS-1$ - new Object[] { targetFile.getAbsolutePath() }), - null)); - fMonitor.worked(1); - return; - } - - if (overwriteState == OVERWRITE_NONE) - return; - - if (overwriteState != OVERWRITE_ALL) { - String overwriteAnswer = fOverwriteCallback - .queryOverwrite(properPathString); - - if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) - throw new InterruptedException(); - - if (overwriteAnswer.equals(IOverwriteQuery.NO)) { - fMonitor.worked(1); - return; - } - - if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { - fMonitor.worked(1); - overwriteState = OVERWRITE_NONE; - return; - } - - if (overwriteAnswer.equals(IOverwriteQuery.ALL)) - overwriteState = OVERWRITE_ALL; - } - } - - try { - setExporters(file); - fExporter2.write(file, fullPath); - } catch (IOException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - ObfuscatorExportMessages.format( - "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage() }), e)); - } catch (CoreException e) { - errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, - ObfuscatorExportMessages.format( - "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ - new Object[] { fullPath, e.getMessage() }), e)); - } - - fMonitor.worked(1); - ModalContext.checkCanceled(fMonitor); - } - - protected void exportSpecifiedResources1() throws InterruptedException { - Iterator resources = fResourcesToExport.iterator(); - IPath initPath = (IPath) fPath.clone(); - - while (resources.hasNext()) { - IResource currentResource = (IResource) resources.next(); - if (!currentResource.isAccessible()) - continue; - setExporters(currentResource); - fPath = initPath; - - if (fResource == null) { - // No root resource specified and creation of containment - // directories - // is required. Create containers from depth 2 onwards (ie.- - // project's - // child inclusive) for each resource being exported. - // if (createLeadupStructure) - // createLeadupDirectoriesFor(currentResource); - - } else { - // Root resource specified. Must create containment directories - // from this point onwards for each resource being exported - IPath containersToCreate = currentResource.getFullPath() - .removeFirstSegments( - fResource.getFullPath().segmentCount()) - .removeLastSegments(1); - - for (int i = 0; i < containersToCreate.segmentCount(); i++) { - fPath = fPath.append(containersToCreate.segment(i)); - fExporter1.createFolder(fPath); - } - } - - if (currentResource.getType() == IResource.FILE) - exportFile1((IFile) currentResource, fPath); - else { - if (createContainerDirectories) { - fPath = fPath.append(currentResource.getName()); - fExporter1.createFolder(fPath); - } - - try { - exportChildren1(((IContainer) currentResource).members(), - fPath); - } catch (CoreException e) { - // should never happen because #isAccessible is called - // before #members is invoked, - // which implicitly does an existence check - errorTable.add(e.getStatus()); - } - } - } - } - - /** - * Export the resources contained in the previously-defined - * resourcesToExport collection - */ - protected void exportSpecifiedResources2() throws InterruptedException { - Iterator resources = fResourcesToExport.iterator(); - IPath initPath = (IPath) fPath.clone(); - - while (resources.hasNext()) { - IResource currentResource = (IResource) resources.next(); - if (!currentResource.isAccessible()) - continue; - setExporters(currentResource); - - fPath = initPath; - - if (fResource == null) { - // No root resource specified and creation of containment - // directories - // is required. Create containers from depth 2 onwards (ie.- - // project's - // child inclusive) for each resource being exported. - // if (createLeadupStructure) - // createLeadupDirectoriesFor(currentResource); - - } else { - // Root resource specified. Must create containment directories - // from this point onwards for each resource being exported - IPath containersToCreate = currentResource.getFullPath() - .removeFirstSegments( - fResource.getFullPath().segmentCount()) - .removeLastSegments(1); - - for (int i = 0; i < containersToCreate.segmentCount(); i++) { - fPath = fPath.append(containersToCreate.segment(i)); - fExporter2.createFolder(fPath); - } - } - - if (currentResource.getType() == IResource.FILE) - exportFile2((IFile) currentResource, fPath); - else { - if (createContainerDirectories) { - fPath = fPath.append(currentResource.getName()); - fExporter2.createFolder(fPath); - } - - try { - exportChildren2(((IContainer) currentResource).members(), - fPath); - } catch (CoreException e) { - // should never happen because #isAccessible is called - // before #members is invoked, - // which implicitly does an existence check - errorTable.add(e.getStatus()); - } - } - } - } - - /** - * Returns the status of the export operation. If there were any errors, the - * result is a status object containing individual status objects for each - * error. If there were no errors, the result is a status object with error - * code OK. - * - * @return the status - */ - public IStatus getStatus() { - IStatus[] errors = new IStatus[errorTable.size()]; - errorTable.toArray(errors); - return new MultiStatus( - PlatformUI.PLUGIN_ID, - IStatus.OK, - errors, - ObfuscatorExportMessages - .getString("ObfuscatorExportOperation.problemsExporting"), //$NON-NLS-1$ - null); - } - - /** - * Answer a boolean indicating whether the passed child is a descendent of - * one or more members of the passed resources collection - * - * @return boolean - * @param resources - * java.util.List - * @param child - * org.eclipse.core.resources.IResource - */ - protected boolean isDescendent(List resources, IResource child) { - if (child.getType() == IResource.PROJECT) - return false; - - IResource parent = child.getParent(); - if (resources.contains(parent)) - return true; - - return isDescendent(resources, parent); - } - - private void setExporters(IResource resource) { - if (fCurrentIdentifierMap == null) { - if (fProjectMap == null) { - fProjectMap = new HashMap(); - } - createExporters(resource); - } else { - IProject project = resource.getProject(); - if (!fCurrentProjectName.equals(project.getName())) { - HashMap temp = (HashMap) fProjectMap.get(project.getName()); - if (temp != null) { - fCurrentProjectName = project.getName(); - fCurrentIdentifierMap = temp; - fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, - false), fCurrentIdentifierMap); - fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, - true), fCurrentIdentifierMap); - return; - } - createExporters(resource); - } - } - } - - private void createExporters(IResource resource) { - IProject project = resource.getProject(); -// IPreferenceStore store = WebUI.getDefault() -// .getPreferenceStore(); - ObfuscatorIgnores ignore = new ObfuscatorIgnores(project); - fCurrentIdentifierMap = ignore.getIdentifierMap(); - fCurrentProjectName = project.getName(); - fProjectMap.put(fCurrentProjectName, fCurrentIdentifierMap); - fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), - fCurrentIdentifierMap); - fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), - fCurrentIdentifierMap); - } - - /** - * Export the resources that were previously specified for export (or if a - * single resource was specified then export it recursively) - */ - public void run(IProgressMonitor monitor) throws InterruptedException { - this.fMonitor = monitor; - final IPath tempPath = (IPath) fPath.clone(); - if (fResource != null) { - setExporters(fResource); - // if (createLeadupStructure) - // createLeadupDirectoriesFor(resource); - - if (createContainerDirectories - && fResource.getType() != IResource.FILE) { - // ensure it's a container - fPath = fPath.append(fResource.getName()); - fExporter2.createFolder(fPath); - } - } - - try { - // reset variables for this run: - fCurrentIdentifierMap = null; - fProjectMap = null; - fCurrentProjectName = ""; - - // count number of files - int totalWork = IProgressMonitor.UNKNOWN; - try { - if (fResourcesToExport == null) { - totalWork = countChildrenOf(fResource); - } else { - totalWork = countSelectedResources(); - } - } catch (CoreException e) { - // Should not happen - errorTable.add(e.getStatus()); - } - monitor - .beginTask( - ObfuscatorExportMessages - .getString("ObfuscatorTransfer.exportingTitle1"), totalWork); //$NON-NLS-1$ - if (fResourcesToExport == null) { - exportAllResources1(); - } else { - exportSpecifiedResources1(); - } - - // try { - // if (resourcesToExport == null) - // totalWork = countChildrenOf(resource); - // else - // totalWork = countSelectedResources(); - // } catch (CoreException e) { - // // Should not happen - // errorTable.add(e.getStatus()); - // } - - // reset path: - fPath = tempPath; - monitor - .beginTask( - ObfuscatorExportMessages - .getString("ObfuscatorTransfer.exportingTitle2"), totalWork); //$NON-NLS-1$ - if (fResourcesToExport == null) { - exportAllResources2(); - } else { - exportSpecifiedResources2(); - } - } finally { - monitor.done(); - } - } - - /** - * Set this boolean indicating whether a directory should be created for - * Folder resources that are explicitly passed for export - * - * @param value - * boolean - */ - // public void setCreateContainerDirectories(boolean value) { - // createContainerDirectories = value; - // } - /** - * Set this boolean indicating whether each exported resource's complete - * path should include containment hierarchies as dictated by its parents - * - * @param value - * boolean - */ - // public void setCreateLeadupStructure(boolean value) { - // createLeadupStructure = value; - // } - /** - * Set this boolean indicating whether exported resources should - * automatically overwrite existing files when a conflict occurs. If not - * query the user. - * - * @param value - * boolean - */ - public void setOverwriteFiles(boolean value) { - if (value) - overwriteState = OVERWRITE_ALL; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java deleted file mode 100644 index 0e1ed18..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java +++ /dev/null @@ -1,437 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IWorkingCopy; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; -import net.sourceforge.phpdt.ui.JavaUI; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.action.Action; -import org.eclipse.swt.SWT; -import org.eclipse.ui.IEditorDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorRegistry; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * A number of routines for working with JavaElements in editors - * - * Use 'isOpenInEditor' to test if an element is already open in a editor Use - * 'openInEditor' to force opening an element in a editor With 'getWorkingCopy' - * you get the working copy (element in the editor) of an element - */ -public class EditorUtility { - -// public static boolean isEditorInput(Object element, IEditorPart editor) { -// if (editor != null) { -// try { -// return editor.getEditorInput().equals(getEditorInput(element)); -// } catch (JavaModelException x) { -// PHPeclipsePlugin.log(x.getStatus()); -// } -// } -// return false; -// } - - /** - * Tests if a cu is currently shown in an editor - * - * @return the IEditorPart if shown, null if element is not open in an - * editor - */ -// public static IEditorPart isOpenInEditor(Object inputElement) { -// IEditorInput input = null; -// -// try { -// input = getEditorInput(inputElement); -// } catch (JavaModelException x) { -// PHPeclipsePlugin.log(x.getStatus()); -// } -// -// if (input != null) { -// IWorkbenchPage p = WebUI.getActivePage(); -// if (p != null) { -// return p.findEditor(input); -// } -// } -// -// return null; -// } - - /** - * Opens a Java editor for an element such as IJavaElement, - * IFile, or IStorage. The editor is - * activated by default. - * - * @return the IEditorPart or null if wrong element type or opening failed - */ - public static IEditorPart openInEditor(Object inputElement) - throws JavaModelException, PartInitException { - return openInEditor(inputElement, true); - } - - /** - * Opens a Java editor for an element (IJavaElement, IFile, IStorage...) - * - * @return the IEditorPart or null if wrong element type or opening failed - */ - public static IEditorPart openInEditor(Object inputElement, boolean activate) - throws JavaModelException, PartInitException { - - if (inputElement instanceof IFile) - return openInEditor((IFile) inputElement, activate); - - IEditorInput input = getEditorInput(inputElement); - if (input instanceof IFileEditorInput) { - IFileEditorInput fileInput = (IFileEditorInput) input; - return openInEditor(fileInput.getFile(), activate); - } - - if (input != null) - return openInEditor(input, getEditorID(input, inputElement), - activate); - - return null; - } - - /** - * Selects a Java Element in an editor - */ - public static void revealInEditor(IEditorPart part, IJavaElement element) { - if (element != null && part instanceof PHPEditor) { - ((PHPEditor) part).setSelection(element); - } - } - - private static IEditorPart openInEditor(IFile file, boolean activate) - throws PartInitException { - if (file != null) { - IWorkbenchPage p = WebUI.getActivePage(); - if (p != null) { - IEditorPart editorPart = IDE.openEditor(p, file, activate); - initializeHighlightRange(editorPart); - return editorPart; - } - } - return null; - } - - private static IEditorPart openInEditor(IEditorInput input, - String editorID, boolean activate) throws PartInitException { - if (input != null) { - IWorkbenchPage p = WebUI.getActivePage(); - if (p != null) { - IEditorPart editorPart = p - .openEditor(input, editorID, activate); - initializeHighlightRange(editorPart); - return editorPart; - } - } - return null; - } - - private static void initializeHighlightRange(IEditorPart editorPart) { - if (editorPart instanceof ITextEditor) { - TogglePresentationAction toggleAction = new TogglePresentationAction(); - // Initialize editor - toggleAction.setEditor((ITextEditor) editorPart); - // Reset action - toggleAction.setEditor(null); - } - } - - /** - * @deprecated Made it public again for java debugger UI. - */ - public static String getEditorID(IEditorInput input, Object inputObject) { - IEditorRegistry registry = PlatformUI.getWorkbench() - .getEditorRegistry(); - IEditorDescriptor descriptor = registry.getDefaultEditor(input - .getName()); - if (descriptor != null) - return descriptor.getId(); - return null; - } - - private static IEditorInput getEditorInput(IJavaElement element) - throws JavaModelException { - while (element != null) { - if (element instanceof IWorkingCopy - && ((IWorkingCopy) element).isWorkingCopy()) - element = ((IWorkingCopy) element).getOriginalElement(); - - if (element instanceof ICompilationUnit) { - ICompilationUnit unit = (ICompilationUnit) element; - IResource resource = unit.getResource(); - if (resource instanceof IFile) - return new FileEditorInput((IFile) resource); - } - - // if (element instanceof IClassFile) - // return new InternalClassFileEditorInput((IClassFile) element); - // - element = element.getParent(); - } - - return null; - } - - public static IEditorInput getEditorInput(Object input) - throws JavaModelException { - - if (input instanceof IJavaElement) - return getEditorInput((IJavaElement) input); - - if (input instanceof IFile) - return new FileEditorInput((IFile) input); - - // if (input instanceof IStorage) - // return new JarEntryEditorInput((IStorage)input); - - return null; - } - - /** - * If the current active editor edits a java element return it, else return - * null - */ -// public static IJavaElement getActiveEditorJavaInput() { -// IWorkbenchPage page = WebUI.getActivePage(); -// if (page != null) { -// IEditorPart part = page.getActiveEditor(); -// if (part != null) { -// IEditorInput editorInput = part.getEditorInput(); -// if (editorInput != null) { -// return (IJavaElement) editorInput -// .getAdapter(IJavaElement.class); -// } -// } -// } -// return null; -// } - - /** - * Gets the working copy of an compilation unit opened in an editor - * - * @param part - * the editor part - * @param cu - * the original compilation unit (or another working copy) - * @return the working copy of the compilation unit, or null if not found - */ - public static ICompilationUnit getWorkingCopy(ICompilationUnit cu) { - if (cu == null) - return null; - if (cu.isWorkingCopy()) - return cu; - - return (ICompilationUnit) cu.findSharedWorkingCopy(JavaUI - .getBufferFactory()); - } - - /** - * Gets the working copy of an member opened in an editor - * - * @param member - * the original member or a member in a working copy - * @return the corresponding member in the shared working copy or - * null if not found - */ -// public static IMember getWorkingCopy(IMember member) -// throws JavaModelException { -// ICompilationUnit cu = member.getCompilationUnit(); -// if (cu != null) { -// ICompilationUnit workingCopy = getWorkingCopy(cu); -// if (workingCopy != null) { -// return JavaModelUtil.findMemberInCompilationUnit(workingCopy, -// member); -// } -// } -// return null; -// } - - /** - * Returns the compilation unit for the given java element. - * - * @param element - * the java element whose compilation unit is searched for - * @return the compilation unit of the given java element - */ - private static ICompilationUnit getCompilationUnit(IJavaElement element) { - - if (element == null) - return null; - - if (element instanceof IMember) - return ((IMember) element).getCompilationUnit(); - - int type = element.getElementType(); - if (IJavaElement.COMPILATION_UNIT == type) - return (ICompilationUnit) element; - if (IJavaElement.CLASS_FILE == type) - return null; - - return getCompilationUnit(element.getParent()); - } - - /** - * Returns the working copy of the given java element. - * - * @param javaElement - * the javaElement for which the working copyshould be found - * @param reconcile - * indicates whether the working copy must be reconcile prior to - * searching it - * @return the working copy of the given element or null if - * none - */ - public static IJavaElement getWorkingCopy(IJavaElement element, - boolean reconcile) throws JavaModelException { - ICompilationUnit unit = getCompilationUnit(element); - if (unit == null) - return null; - - if (unit.isWorkingCopy()) - return element; - - ICompilationUnit workingCopy = getWorkingCopy(unit); - if (workingCopy != null) { - if (reconcile) { - synchronized (workingCopy) { - workingCopy.reconcile(); - return JavaModelUtil.findInCompilationUnit(workingCopy, - element); - } - } else { - return JavaModelUtil - .findInCompilationUnit(workingCopy, element); - } - } - - return null; - } - - /** - * Maps the localized modifier name to a code in the same manner as - * #findModifier. - * - * @return the SWT modifier bit, or 0 if no match was found - * @see findModifier - * @since 2.1.1 - */ - public static int findLocalizedModifier(String token) { - if (token == null) - return 0; - - if (token.equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) - return SWT.CTRL; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) - return SWT.SHIFT; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.ALT))) - return SWT.ALT; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.COMMAND))) - return SWT.COMMAND; - - return 0; - } - - /** - * Returns the modifier string for the given SWT modifier modifier bits. - * - * @param stateMask - * the SWT modifier bits - * @return the modifier string - * @since 2.1.1 - */ - public static String getModifierString(int stateMask) { - String modifierString = ""; //$NON-NLS-1$ - if ((stateMask & SWT.CTRL) == SWT.CTRL) - modifierString = appendModifierString(modifierString, SWT.CTRL); - if ((stateMask & SWT.ALT) == SWT.ALT) - modifierString = appendModifierString(modifierString, SWT.ALT); - if ((stateMask & SWT.SHIFT) == SWT.SHIFT) - modifierString = appendModifierString(modifierString, SWT.SHIFT); - if ((stateMask & SWT.COMMAND) == SWT.COMMAND) - modifierString = appendModifierString(modifierString, SWT.COMMAND); - - return modifierString; - } - - /** - * Appends to modifier string of the given SWT modifier bit to the given - * modifierString. - * - * @param modifierString - * the modifier string - * @param modifier - * an int with SWT modifier bit - * @return the concatenated modifier string - * @since 2.1.1 - */ - private static String appendModifierString(String modifierString, - int modifier) { - if (modifierString == null) - modifierString = ""; //$NON-NLS-1$ - String newModifierString = Action.findModifierString(modifier); - if (modifierString.length() == 0) - return newModifierString; - return PHPEditorMessages - .getFormattedString( - "EditorUtility.concatModifierStrings", new String[] { modifierString, newModifierString }); //$NON-NLS-1$ - } - - /** - * Returns the Java project for a given editor input or null - * if no corresponding Java project exists. - * - * @param input - * the editor input - * @return the corresponding Java project - * - * @since 3.0 - */ - public static IJavaProject getJavaProject(IEditorInput input) { - IJavaProject jProject = null; - if (input instanceof IFileEditorInput) { - IProject project = ((IFileEditorInput) input).getFile() - .getProject(); - if (project != null) { - jProject = JavaCore.create(project); - if (!jProject.exists()) - jProject = null; - } - } - // else if (input instanceof IClassFileEditorInput) { - // jProject= - // ((IClassFileEditorInput)input).getClassFile().getJavaProject(); - // } - return jProject; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java deleted file mode 100644 index 535750c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java +++ /dev/null @@ -1,38 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2003 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.filebuffers.IDocumentSetupParticipant; -import org.eclipse.jface.text.IDocument; - -/** - * The document setup participant for PHPDT. - */ -public class HTMLDocumentSetupParticipant implements IDocumentSetupParticipant { - - public HTMLDocumentSetupParticipant() { - } - - /* - * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) - */ - public void setup(IDocument document) { - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupHTMLDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, - // null); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java deleted file mode 100644 index 7f90b10..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java +++ /dev/null @@ -1,41 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2003 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.filebuffers.IDocumentSetupParticipant; -import org.eclipse.jface.text.IDocument; - -/** - * The document setup participant for PHPDT. - */ -public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant { - - public JavaDocumentSetupParticipant() { - } - - /* - * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) - */ - public void setup(IDocument document) { - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - - // tools.setupJavaDocumentPartitioner(document, - // IPHPPartitions.PHP_PARTITIONING, null); - // //IPHPPartitions.PHP_PARTITIONING, null); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java deleted file mode 100644 index a694062..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.internal.ui.viewsupport.IProblemChangedListener; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaUILabelProvider; -import net.sourceforge.phpdt.ui.ProblemsLabelDecorator; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IResource; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; - -/** - * The JavaEditorErrorTickUpdater will register as a - * IProblemChangedListener to listen on problem changes of the editor's input. - * It updates the title images when the annotation model changed. - */ -public class JavaEditorErrorTickUpdater implements IProblemChangedListener { - - private PHPEditor fJavaEditor; - - private JavaUILabelProvider fLabelProvider; - - public JavaEditorErrorTickUpdater(PHPEditor editor) { - Assert.isNotNull(editor); - fJavaEditor = editor; - fLabelProvider = new JavaUILabelProvider(0, - JavaElementImageProvider.SMALL_ICONS); - fLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null)); - WebUI.getDefault().getProblemMarkerManager().addListener( - this); - } - - /* - * (non-Javadoc) - * - * @see IProblemChangedListener#problemsChanged(IResource[], boolean) - */ - public void problemsChanged(IResource[] changedResources, - boolean isMarkerChange) { - if (isMarkerChange) { - return; - } - IEditorInput input = fJavaEditor.getEditorInput(); - if (input != null) { // might run async, tests needed - IJavaElement jelement = (IJavaElement) input - .getAdapter(IJavaElement.class); - if (jelement != null) { - IResource resource = jelement.getResource(); - for (int i = 0; i < changedResources.length; i++) { - if (changedResources[i].equals(resource)) { - updateEditorImage(jelement); - } - } - } - } - } - - public void updateEditorImage(IJavaElement jelement) { - Image titleImage = fJavaEditor.getTitleImage(); - if (titleImage == null) { - return; - } - Image newImage = fLabelProvider.getImage(jelement); - if (titleImage != newImage) { - postImageChange(newImage); - } - } - - private void postImageChange(final Image newImage) { - Shell shell = fJavaEditor.getEditorSite().getShell(); - if (shell != null && !shell.isDisposed()) { - shell.getDisplay().syncExec(new Runnable() { - public void run() { - fJavaEditor.updatedTitleImage(newImage); - } - }); - } - } - - public void dispose() { - fLabelProvider.dispose(); - WebUI.getDefault().getProblemMarkerManager().removeListener( - this); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java deleted file mode 100644 index 89e41c1..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java +++ /dev/null @@ -1,1430 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.List; -import java.util.ResourceBundle; -import java.util.Vector; - -import net.sourceforge.phpdt.core.ElementChangedEvent; -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IElementChangedListener; -import net.sourceforge.phpdt.core.IField; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaElementDelta; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IMethod; -import net.sourceforge.phpdt.core.IParent; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; -import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.internal.ui.actions.AbstractToggleLinkingAction; -import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; -import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; -import net.sourceforge.phpdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; -import net.sourceforge.phpdt.internal.ui.viewsupport.StatusBarUpdater; -import net.sourceforge.phpdt.ui.JavaElementSorter; -import net.sourceforge.phpdt.ui.JavaUI; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; -import net.sourceforge.phpdt.ui.actions.CustomFiltersActionGroup; -import net.sourceforge.phpdt.ui.actions.GenerateActionGroup; -import net.sourceforge.phpdt.ui.actions.MemberFilterActionGroup; -import net.sourceforge.phpdt.ui.actions.PHPdtActionConstants; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.IPostSelectionProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.LabelProviderChangedEvent; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.BusyIndicator; -//import org.eclipse.swt.dnd.DND; -//import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Item; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.Widget; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.actions.ActionContext; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.model.IWorkbenchAdapter; -import org.eclipse.ui.model.WorkbenchAdapter; -import org.eclipse.ui.part.IPageSite; -import org.eclipse.ui.part.IShowInSource; -import org.eclipse.ui.part.IShowInTarget; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.part.Page; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.texteditor.GotoAnnotationAction; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -//import org.eclipse.ui.views.navigator.LocalSelectionTransfer; - -/** - * The content outline page of the Java editor. The viewer implements a - * proprietary update mechanism based on Java model deltas. It does not react on - * domain changes. It is specified to show the content of ICompilationUnits and - * IClassFiles. Publishes its context menu under - * PHPeclipsePlugin.getDefault().getPluginId() + ".outline". - */ -public class JavaOutlinePage extends Page implements IContentOutlinePage, - IAdaptable, IPostSelectionProvider { - - static Object[] NO_CHILDREN = new Object[0]; - - /** - * The element change listener of the java outline viewer. - * - * @see IElementChangedListener - */ - class ElementChangedListener implements IElementChangedListener { - - public void elementChanged(final ElementChangedEvent e) { - - if (getControl() == null) - return; - - Display d = getControl().getDisplay(); - if (d != null) { - d.asyncExec(new Runnable() { - public void run() { - //ICompilationUnit cu = (ICompilationUnit) fInput; - //IJavaElement base = cu; - // if (fTopLevelTypeOnly) { - // base= getMainType(cu); - // if (base == null) { - if (fOutlineViewer != null) - fOutlineViewer.refresh(true); - return; - // } - // } - // IJavaElementDelta delta= findElement(base, - // e.getDelta()); - // if (delta != null && fOutlineViewer != null) { - // fOutlineViewer.reconcile(delta); - // } - } - }); - } - } - - private boolean isPossibleStructuralChange(IJavaElementDelta cuDelta) { - if (cuDelta.getKind() != IJavaElementDelta.CHANGED) { - return true; // add or remove - } - int flags = cuDelta.getFlags(); - if ((flags & IJavaElementDelta.F_CHILDREN) != 0) { - return true; - } - return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT; - } - - protected IJavaElementDelta findElement(IJavaElement unit, - IJavaElementDelta delta) { - - if (delta == null || unit == null) - return null; - - IJavaElement element = delta.getElement(); - - if (unit.equals(element)) { - if (isPossibleStructuralChange(delta)) { - return delta; - } - return null; - } - - if (element.getElementType() > IJavaElement.CLASS_FILE) - return null; - - IJavaElementDelta[] children = delta.getAffectedChildren(); - if (children == null || children.length == 0) - return null; - - for (int i = 0; i < children.length; i++) { - IJavaElementDelta d = findElement(unit, children[i]); - if (d != null) - return d; - } - - return null; - } - } - - static class NoClassElement extends WorkbenchAdapter implements IAdaptable { - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return PHPEditorMessages - .getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) - */ - public Object getAdapter(Class clas) { - if (clas == IWorkbenchAdapter.class) - return this; - return null; - } - } - - /** - * Content provider for the children of an ICompilationUnit or an IClassFile - * - * @see ITreeContentProvider - */ - class ChildrenProvider implements ITreeContentProvider { - - private Object[] NO_CLASS = new Object[] { new NoClassElement() }; - - private ElementChangedListener fListener; - - protected boolean matches(IJavaElement element) { - if (element.getElementType() == IJavaElement.METHOD) { - String name = element.getElementName(); - return (name != null && name.indexOf('<') >= 0); - } - return false; - } - - protected IJavaElement[] filter(IJavaElement[] children) { - boolean initializers = false; - for (int i = 0; i < children.length; i++) { - if (matches(children[i])) { - initializers = true; - break; - } - } - - if (!initializers) - return children; - - Vector v = new Vector(); - for (int i = 0; i < children.length; i++) { - if (matches(children[i])) - continue; - v.addElement(children[i]); - } - - IJavaElement[] result = new IJavaElement[v.size()]; - v.copyInto(result); - return result; - } - - public Object[] getChildren(Object parent) { - if (parent instanceof IParent) { - IParent c = (IParent) parent; - try { - return filter(c.getChildren()); - } catch (JavaModelException x) { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 - // don't log NotExist exceptions as this is a valid case - // since we might have been posted and the element - // removed in the meantime. - if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) - PHPeclipsePlugin.log(x); - } - } - return NO_CHILDREN; - } - - public Object[] getElements(Object parent) { - if (fTopLevelTypeOnly) { - if (parent instanceof ICompilationUnit) { - try { - IType type = getMainType((ICompilationUnit) parent); - return type != null ? type.getChildren() : NO_CLASS; - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); - } - } - // else if (parent instanceof IClassFile) { - // try { - // IType type= getMainType((IClassFile) parent); - // return type != null ? type.getChildren() : NO_CLASS; - // } catch (JavaModelException e) { - // PHPeclipsePlugin.log(e); - // } - // } - } - return getChildren(parent); - } - - public Object getParent(Object child) { - if (child instanceof IJavaElement) { - IJavaElement e = (IJavaElement) child; - return e.getParent(); - } - return null; - } - - public boolean hasChildren(Object parent) { - if (parent instanceof IParent) { - IParent c = (IParent) parent; - try { - IJavaElement[] children = filter(c.getChildren()); - return (children != null && children.length > 0); - } catch (JavaModelException x) { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 - // don't log NotExist exceptions as this is a valid case - // since we might have been posted and the element - // removed in the meantime. - if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) - PHPeclipsePlugin.log(x); - } - } - return false; - } - - public boolean isDeleted(Object o) { - return false; - } - - public void dispose() { - if (fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener = null; - } - } - - /* - * @see IContentProvider#inputChanged(Viewer, Object, Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - boolean isCU = (newInput instanceof ICompilationUnit); - - if (isCU && fListener == null) { - fListener = new ElementChangedListener(); - JavaCore.addElementChangedListener(fListener); - } else if (!isCU && fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener = null; - } - } - } - - class JavaOutlineViewer extends TreeViewer { - - /** - * Indicates an item which has been reused. At the point of its reuse it - * has been expanded. This field is used to communicate between - * internalExpandToLevel and reuseTreeItem. - */ - private Item fReusedExpandedItem; - - private boolean fReorderedMembers; - - private boolean fForceFireSelectionChanged; - - public JavaOutlineViewer(Tree tree) { - super(tree); - setAutoExpandLevel(ALL_LEVELS); - setUseHashlookup(true); - } - - /** - * Investigates the given element change event and if affected - * incrementally updates the Java outline. - * - * @param delta - * the Java element delta used to reconcile the Java outline - */ - public void reconcile(IJavaElementDelta delta) { - fReorderedMembers = false; - fForceFireSelectionChanged = false; - if (getSorter() == null) { - if (fTopLevelTypeOnly && delta.getElement() instanceof IType - && (delta.getKind() & IJavaElementDelta.ADDED) != 0) { - refresh(true); - - } else { - Widget w = findItem(fInput); - if (w != null && !w.isDisposed()) - update(w, delta); - if (fForceFireSelectionChanged) - fireSelectionChanged(new SelectionChangedEvent( - getSite().getSelectionProvider(), this - .getSelection())); - if (fReorderedMembers) { - refresh(false); - fReorderedMembers = false; - } - } - } else { - // just for now - refresh(true); - } - } - - /* - * @see TreeViewer#internalExpandToLevel - */ - protected void internalExpandToLevel(Widget node, int level) { - if (node instanceof Item) { - Item i = (Item) node; - if (i.getData() instanceof IJavaElement) { - IJavaElement je = (IJavaElement) i.getData(); - if (je.getElementType() == IJavaElement.IMPORT_CONTAINER - || isInnerType(je)) { - if (i != fReusedExpandedItem) { - setExpanded(i, false); - return; - } - } - } - } - super.internalExpandToLevel(node, level); - } - - protected void reuseTreeItem(Item item, Object element) { - - // remove children - Item[] c = getChildren(item); - if (c != null && c.length > 0) { - - if (getExpanded(item)) - fReusedExpandedItem = item; - - for (int k = 0; k < c.length; k++) { - if (c[k].getData() != null) - disassociate(c[k]); - c[k].dispose(); - } - } - - updateItem(item, element); - updatePlus(item, element); - internalExpandToLevel(item, ALL_LEVELS); - - fReusedExpandedItem = null; - fForceFireSelectionChanged = true; - } - - protected boolean mustUpdateParent(IJavaElementDelta delta, - IJavaElement element) { - if (element instanceof IMethod) { - if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { - try { - return ((IMethod) element).isMainMethod(); - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e.getStatus()); - } - } - return "main".equals(element.getElementName()); //$NON-NLS-1$ - } - return false; - } - - /* - * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) - */ - public boolean isExpandable(Object element) { - if (hasFilters()) { - return getFilteredChildren(element).length > 0; - } - return super.isExpandable(element); - } - - protected ISourceRange getSourceRange(IJavaElement element) - throws JavaModelException { - if (element instanceof ISourceReference) - return ((ISourceReference) element).getSourceRange(); - if (element instanceof IMember)// && !(element instanceof - // IInitializer)) - return ((IMember) element).getNameRange(); - return null; - } - - protected boolean overlaps(ISourceRange range, int start, int end) { - return start <= (range.getOffset() + range.getLength() - 1) - && range.getOffset() <= end; - } - - protected boolean filtered(IJavaElement parent, IJavaElement child) { - - Object[] result = new Object[] { child }; - ViewerFilter[] filters = getFilters(); - for (int i = 0; i < filters.length; i++) { - result = filters[i].filter(this, parent, result); - if (result.length == 0) - return true; - } - - return false; - } - - protected void update(Widget w, IJavaElementDelta delta) { - - Item item; - - IJavaElement parent = delta.getElement(); - IJavaElementDelta[] affected = delta.getAffectedChildren(); - Item[] children = getChildren(w); - - boolean doUpdateParent = false; - boolean doUpdateParentsPlus = false; - - Vector deletions = new Vector(); - Vector additions = new Vector(); - - for (int i = 0; i < affected.length; i++) { - IJavaElementDelta affectedDelta = affected[i]; - IJavaElement affectedElement = affectedDelta.getElement(); - int status = affected[i].getKind(); - - // find tree item with affected element - int j; - for (j = 0; j < children.length; j++) - if (affectedElement.equals(children[j].getData())) - break; - - if (j == children.length) { - // remove from collapsed parent - if ((status & IJavaElementDelta.REMOVED) != 0) { - doUpdateParentsPlus = true; - continue; - } - // addition - if ((status & IJavaElementDelta.CHANGED) != 0 - && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 - && !filtered(parent, affectedElement)) { - additions.addElement(affectedDelta); - } - continue; - } - - item = children[j]; - - // removed - if ((status & IJavaElementDelta.REMOVED) != 0) { - deletions.addElement(item); - doUpdateParent = doUpdateParent - || mustUpdateParent(affectedDelta, affectedElement); - - // changed - } else if ((status & IJavaElementDelta.CHANGED) != 0) { - int change = affectedDelta.getFlags(); - doUpdateParent = doUpdateParent - || mustUpdateParent(affectedDelta, affectedElement); - - if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { - if (filtered(parent, affectedElement)) - deletions.addElement(item); - else - updateItem(item, affectedElement); - } - - if ((change & IJavaElementDelta.F_CONTENT) != 0) - updateItem(item, affectedElement); - - if ((change & IJavaElementDelta.F_CHILDREN) != 0) - update(item, affectedDelta); - - if ((change & IJavaElementDelta.F_REORDER) != 0) - fReorderedMembers = true; - } - } - - // find all elements to add - IJavaElementDelta[] add = delta.getAddedChildren(); - if (additions.size() > 0) { - IJavaElementDelta[] tmp = new IJavaElementDelta[add.length - + additions.size()]; - System.arraycopy(add, 0, tmp, 0, add.length); - for (int i = 0; i < additions.size(); i++) - tmp[i + add.length] = (IJavaElementDelta) additions - .elementAt(i); - add = tmp; - } - - // add at the right position - go2: for (int i = 0; i < add.length; i++) { - - try { - - IJavaElement e = add[i].getElement(); - if (filtered(parent, e)) - continue go2; - - doUpdateParent = doUpdateParent - || mustUpdateParent(add[i], e); - ISourceRange rng = getSourceRange(e); - int start = rng.getOffset(); - int end = start + rng.getLength() - 1; - int nameOffset = Integer.MAX_VALUE; - if (e instanceof IField) { - ISourceRange nameRange = ((IField) e).getNameRange(); - if (nameRange != null) - nameOffset = nameRange.getOffset(); - } - - Item last = null; - item = null; - children = getChildren(w); - - for (int j = 0; j < children.length; j++) { - item = children[j]; - IJavaElement r = (IJavaElement) item.getData(); - - if (r == null) { - // parent node collapsed and not be opened before -> - // do nothing - continue go2; - } - - try { - rng = getSourceRange(r); - - // multi-field declarations always start at - // the same offset. They also have the same - // end offset if the field sequence is terminated - // with a semicolon. If not, the source range - // ends behind the identifier / initializer - // see - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51851 - boolean multiFieldDeclaration = r.getElementType() == IJavaElement.FIELD - && e.getElementType() == IJavaElement.FIELD - && rng.getOffset() == start; - - // elements are inserted by occurrence - // however, multi-field declarations have - // equal source ranges offsets, therefore we - // compare name-range offsets. - boolean multiFieldOrderBefore = false; - if (multiFieldDeclaration) { - if (r instanceof IField) { - ISourceRange nameRange = ((IField) r) - .getNameRange(); - if (nameRange != null) { - if (nameRange.getOffset() > nameOffset) - multiFieldOrderBefore = true; - } - } - } - - if (!multiFieldDeclaration - && overlaps(rng, start, end)) { - - // be tolerant if the delta is not correct, or - // if - // the tree has been updated other than by a - // delta - reuseTreeItem(item, e); - continue go2; - - } else if (multiFieldOrderBefore - || rng.getOffset() > start) { - - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, e); - } else { - // nothing to reuse - createTreeItem(w, e, j); - } - continue go2; - } - - } catch (JavaModelException x) { - // stumbled over deleted element - } - - last = item; - } - - // add at the end of the list - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, e); - } else { - // nothing to reuse - createTreeItem(w, e, -1); - } - - } catch (JavaModelException x) { - // the element to be added is not present -> don't add it - } - } - - // remove items which haven't been reused - Enumeration e = deletions.elements(); - while (e.hasMoreElements()) { - item = (Item) e.nextElement(); - disassociate(item); - item.dispose(); - } - - if (doUpdateParent) - updateItem(w, delta.getElement()); - if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item) - updatePlus((Item) w, delta.getElement()); - } - - /* - * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) - */ - protected void handleLabelProviderChanged( - LabelProviderChangedEvent event) { - Object input = getInput(); - if (event instanceof ProblemsLabelChangedEvent) { - ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; - if (e.isMarkerChange() && input instanceof ICompilationUnit) { - return; // marker changes can be ignored - } - } - // look if the underlying resource changed - Object[] changed = event.getElements(); - if (changed != null) { - IResource resource = getUnderlyingResource(); - if (resource != null) { - for (int i = 0; i < changed.length; i++) { - if (changed[i] != null && changed[i].equals(resource)) { - // change event to a full refresh - event = new LabelProviderChangedEvent( - (IBaseLabelProvider) event.getSource()); - break; - } - } - } - } - super.handleLabelProviderChanged(event); - } - - private IResource getUnderlyingResource() { - Object input = getInput(); - if (input instanceof ICompilationUnit) { - ICompilationUnit cu = (ICompilationUnit) input; - cu = JavaModelUtil.toOriginal(cu); - return cu.getResource(); - } - // else if (input instanceof IClassFile) { - // return ((IClassFile) input).getResource(); - // } - return null; - } - - } - - class LexicalSortingAction extends Action { - - private JavaElementSorter fSorter = new JavaElementSorter(); - - public LexicalSortingAction() { - super(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, - IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); - setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages - .getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages - .getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ - - boolean checked = WebUI.getDefault() - .getPreferenceStore().getBoolean( - "LexicalSortingAction.isChecked"); //$NON-NLS-1$ - valueChanged(checked, false); - } - - public void run() { - valueChanged(isChecked(), true); - } - - private void valueChanged(final boolean on, boolean store) { - setChecked(on); - BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), - new Runnable() { - public void run() { - fOutlineViewer.setSorter(on ? fSorter : null); - } - }); - - if (store) - WebUI.getDefault().getPreferenceStore().setValue( - "LexicalSortingAction.isChecked", on); //$NON-NLS-1$ - } - } - - class ClassOnlyAction extends Action { - - public ClassOnlyAction() { - super(); - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, - IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); - setText(PHPEditorMessages - .getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages - .getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages - .getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, - "gointo_toplevel_type.gif"); //$NON-NLS-1$ - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - boolean showclass = preferenceStore - .getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ - setTopLevelTypeOnly(showclass); - } - - /* - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - setTopLevelTypeOnly(!fTopLevelTypeOnly); - } - - private void setTopLevelTypeOnly(boolean show) { - fTopLevelTypeOnly = show; - setChecked(show); - fOutlineViewer.refresh(false); - - IPreferenceStore preferenceStore = WebUI.getDefault() - .getPreferenceStore(); - preferenceStore - .setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ - } - } - - /** - * This action toggles whether this Java Outline page links its selection to - * the active editor. - * - * @since 3.0 - */ - public class ToggleLinkingAction extends AbstractToggleLinkingAction { - - JavaOutlinePage fJavaOutlinePage; - - /** - * Constructs a new action. - * - * @param outlinePage - * the Java outline page - */ - public ToggleLinkingAction(JavaOutlinePage outlinePage) { - boolean isLinkingEnabled = PreferenceConstants - .getPreferenceStore() - .getBoolean( - PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); - setChecked(isLinkingEnabled); - fJavaOutlinePage = outlinePage; - } - - /** - * Runs the action. - */ - public void run() { - PreferenceConstants.getPreferenceStore().setValue( - PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, - isChecked()); - if (isChecked() && fEditor != null) - fEditor.synchronizeOutlinePage(fEditor - .computeHighlightRangeSourceReference(), false); - } - - } - - /** A flag to show contents of top level type only */ - private boolean fTopLevelTypeOnly; - - private IJavaElement fInput; - - private String fContextMenuID; - - private Menu fMenu; - - private JavaOutlineViewer fOutlineViewer; - - private PHPEditor fEditor; - - private MemberFilterActionGroup fMemberFilterActionGroup; - - private ListenerList fSelectionChangedListeners = new ListenerList(); - - private ListenerList fPostSelectionChangedListeners = new ListenerList(); - - private Hashtable fActions = new Hashtable(); - - private TogglePresentationAction fTogglePresentation; - - private GotoAnnotationAction fPreviousAnnotation; - - private GotoAnnotationAction fNextAnnotation; - - private TextEditorAction fShowJavadoc; - - private IAction fUndo; - - private IAction fRedo; - - private ToggleLinkingAction fToggleLinkingAction; - - private CompositeActionGroup fActionGroups; - - private IPropertyChangeListener fPropertyChangeListener; - - /** - * Custom filter action group. - * - * @since 3.0 - */ - private CustomFiltersActionGroup fCustomFiltersActionGroup; - - public JavaOutlinePage(String contextMenuID, PHPEditor editor) { - super(); - - Assert.isNotNull(editor); - - fContextMenuID = contextMenuID; - fEditor = editor; - fTogglePresentation = new TogglePresentationAction(); - ResourceBundle bundle = PHPEditorMessages.getResourceBundle(); - fPreviousAnnotation = new GotoAnnotationAction(bundle, - "PreviousAnnotation.", null, false); //$NON-NLS-1$ - fNextAnnotation = new GotoAnnotationAction(bundle, - "NextAnnotation.", null, true); //$NON-NLS-1$ - fShowJavadoc = (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ - fUndo = fEditor.getAction(ITextEditorActionConstants.UNDO); - fRedo = fEditor.getAction(ITextEditorActionConstants.REDO); - - fTogglePresentation.setEditor(editor); - fPreviousAnnotation.setEditor(editor); - fNextAnnotation.setEditor(editor); - - fPropertyChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - doPropertyChange(event); - } - }; - WebUI.getDefault().getPreferenceStore() - .addPropertyChangeListener(fPropertyChangeListener); - } - - /** - * Returns the primary type of a compilation unit (has the same name as the - * compilation unit). - * - * @param compilationUnit - * the compilation unit - * @return returns the primary type of the compilation unit, or - * null if is does not have one - */ - protected IType getMainType(ICompilationUnit compilationUnit) { - - if (compilationUnit == null) - return null; - - String name = compilationUnit.getElementName(); - int index = name.indexOf('.'); - if (index != -1) - name = name.substring(0, index); - IType type = compilationUnit.getType(name); - return type.exists() ? type : null; - } - - /** - * Returns the primary type of a class file. - * - * @param classFile - * the class file - * @return returns the primary type of the class file, or null - * if is does not have one - */ - // protected IType getMainType(IClassFile classFile) { - // try { - // IType type= classFile.getType(); - // return type != null && type.exists() ? type : null; - // } catch (JavaModelException e) { - // return null; - // } - // } - /* - * (non-Javadoc) Method declared on Page - */ - public void init(IPageSite pageSite) { - super.init(pageSite); - } - - private void doPropertyChange(PropertyChangeEvent event) { - if (fOutlineViewer != null) { - if (MembersOrderPreferenceCache.isMemberOrderProperty(event - .getProperty())) { - fOutlineViewer.refresh(false); - } - } - } - - /* - * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) - */ - public void addSelectionChangedListener(ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.addSelectionChangedListener(listener); - else - fSelectionChangedListeners.add(listener); - } - - /* - * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) - */ - public void removeSelectionChangedListener( - ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.removeSelectionChangedListener(listener); - else - fSelectionChangedListeners.remove(listener); - } - - /* - * @see ISelectionProvider#setSelection(ISelection) - */ - public void setSelection(ISelection selection) { - if (fOutlineViewer != null) - fOutlineViewer.setSelection(selection); - } - - /* - * @see ISelectionProvider#getSelection() - */ - public ISelection getSelection() { - if (fOutlineViewer == null) - return StructuredSelection.EMPTY; - return fOutlineViewer.getSelection(); - } - - /* - * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void addPostSelectionChangedListener( - ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.addPostSelectionChangedListener(listener); - else - fPostSelectionChangedListeners.add(listener); - } - - /* - * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void removePostSelectionChangedListener( - ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.removePostSelectionChangedListener(listener); - else - fPostSelectionChangedListeners.remove(listener); - } - - private void registerToolbarActions(IActionBars actionBars) { - - IToolBarManager toolBarManager = actionBars.getToolBarManager(); - if (toolBarManager != null) { - toolBarManager.add(new LexicalSortingAction()); - - fMemberFilterActionGroup = new MemberFilterActionGroup( - fOutlineViewer, - "net.sourceforge.phpeclipse.JavaOutlinePage"); //$NON-NLS-1$ - fMemberFilterActionGroup.contributeToToolBar(toolBarManager); - - fCustomFiltersActionGroup.fillActionBars(actionBars); - - IMenuManager menu = actionBars.getMenuManager(); - menu.add(new Separator("EndFilterGroup")); //$NON-NLS-1$ - - fToggleLinkingAction = new ToggleLinkingAction(this); - menu.add(new ClassOnlyAction()); - menu.add(fToggleLinkingAction); - } - } - - /* - * @see IPage#createControl - */ - public void createControl(Composite parent) { - - Tree tree = new Tree(parent, SWT.MULTI); - - AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( - AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS - | JavaElementLabels.F_APP_TYPE_SIGNATURE, - AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); - - fOutlineViewer = new JavaOutlineViewer(tree); - initDragAndDrop(); - fOutlineViewer.setContentProvider(new ChildrenProvider()); - fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider( - lprovider)); - - Object[] listeners = fSelectionChangedListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) { - fSelectionChangedListeners.remove(listeners[i]); - fOutlineViewer - .addSelectionChangedListener((ISelectionChangedListener) listeners[i]); - } - - listeners = fPostSelectionChangedListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) { - fPostSelectionChangedListeners.remove(listeners[i]); - fOutlineViewer - .addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); - } - - MenuManager manager = new MenuManager(fContextMenuID, fContextMenuID); - manager.setRemoveAllWhenShown(true); - manager.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager m) { - contextMenuAboutToShow(m); - } - }); - fMenu = manager.createContextMenu(tree); - tree.setMenu(fMenu); - - IPageSite site = getSite(); - site - .registerContextMenu(PHPeclipsePlugin.getPluginId() - + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ - site.setSelectionProvider(fOutlineViewer); - - // we must create the groups after we have set the selection provider to - // the site - fActionGroups = new CompositeActionGroup(new ActionGroup[] { - // new OpenViewActionGroup(this), - // new CCPActionGroup(this), - new GenerateActionGroup(this) }); - // new RefactorActionGroup(this), - // new JavaSearchActionGroup(this)}); - - // register global actions - IActionBars bars = site.getActionBars(); - - bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); - bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); - bars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), - fPreviousAnnotation); - bars - .setGlobalActionHandler(ActionFactory.NEXT.getId(), - fNextAnnotation); - bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, - fShowJavadoc); - bars - .setGlobalActionHandler( - ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, - fTogglePresentation); - bars.setGlobalActionHandler( - ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, - fNextAnnotation); - bars.setGlobalActionHandler( - ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, - fPreviousAnnotation); - - fActionGroups.fillActionBars(bars); - - IStatusLineManager statusLineManager = bars.getStatusLineManager(); - if (statusLineManager != null) { - StatusBarUpdater updater = new StatusBarUpdater(statusLineManager); - fOutlineViewer.addPostSelectionChangedListener(updater); - } - // Custom filter group - fCustomFiltersActionGroup = new CustomFiltersActionGroup( - "net.sourceforge.phpdt.ui.JavaOutlinePage", fOutlineViewer); //$NON-NLS-1$ - - registerToolbarActions(bars); - - fOutlineViewer.setInput(fInput); - } - - public void dispose() { - - if (fEditor == null) - return; - - if (fMemberFilterActionGroup != null) { - fMemberFilterActionGroup.dispose(); - fMemberFilterActionGroup = null; - } - - if (fCustomFiltersActionGroup != null) { - fCustomFiltersActionGroup.dispose(); - fCustomFiltersActionGroup = null; - } - - fEditor.outlinePageClosed(); - fEditor = null; - - fSelectionChangedListeners.clear(); - fSelectionChangedListeners = null; - - fPostSelectionChangedListeners.clear(); - fPostSelectionChangedListeners = null; - - if (fPropertyChangeListener != null) { - WebUI.getDefault().getPreferenceStore() - .removePropertyChangeListener(fPropertyChangeListener); - fPropertyChangeListener = null; - } - - if (fMenu != null && !fMenu.isDisposed()) { - fMenu.dispose(); - fMenu = null; - } - - if (fActionGroups != null) - fActionGroups.dispose(); - - fTogglePresentation.setEditor(null); - fPreviousAnnotation.setEditor(null); - fNextAnnotation.setEditor(null); - - fOutlineViewer = null; - - super.dispose(); - } - - public Control getControl() { - if (fOutlineViewer != null) - return fOutlineViewer.getControl(); - return null; - } - - public void setInput(IJavaElement inputElement) { - fInput = inputElement; - if (fOutlineViewer != null) - fOutlineViewer.setInput(fInput); - } - - public void select(ISourceReference reference) { - if (fOutlineViewer != null) { - - ISelection s = fOutlineViewer.getSelection(); - if (s instanceof IStructuredSelection) { - IStructuredSelection ss = (IStructuredSelection) s; - List elements = ss.toList(); - if (!elements.contains(reference)) { - s = (reference == null ? StructuredSelection.EMPTY - : new StructuredSelection(reference)); - fOutlineViewer.setSelection(s, true); - } - } - } - } - - public void setAction(String actionID, IAction action) { - Assert.isNotNull(actionID); - if (action == null) - fActions.remove(actionID); - else - fActions.put(actionID, action); - } - - public IAction getAction(String actionID) { - Assert.isNotNull(actionID); - return (IAction) fActions.get(actionID); - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class key) { - if (key == IShowInSource.class) { - return getShowInSource(); - } - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { JavaUI.ID_PACKAGES }; - } - - }; - } - if (key == IShowInTarget.class) { - return getShowInTarget(); - } - - return null; - } - - /** - * Convenience method to add the action installed under the given actionID - * to the specified group of the menu. - * - * @param menu - * the menu manager - * @param group - * the group to which to add the action - * @param actionID - * the ID of the new action - */ - protected void addAction(IMenuManager menu, String group, String actionID) { - IAction action = getAction(actionID); - if (action != null) { - if (action instanceof IUpdate) - ((IUpdate) action).update(); - - if (action.isEnabled()) { - IMenuManager subMenu = menu.findMenuUsingPath(group); - if (subMenu != null) - subMenu.add(action); - else - menu.appendToGroup(group, action); - } - } - } - - protected void contextMenuAboutToShow(IMenuManager menu) { - - WebUI.createStandardGroups(menu); - - IStructuredSelection selection = (IStructuredSelection) getSelection(); - fActionGroups.setContext(new ActionContext(selection)); - fActionGroups.fillContextMenu(menu); - } - - /* - * @see Page#setFocus() - */ - public void setFocus() { - if (fOutlineViewer != null) - fOutlineViewer.getControl().setFocus(); - } - - /** - * Checks whether a given Java element is an inner type. - * - * @param element - * the java element - * @return true iff the given element is an inner type - */ - private boolean isInnerType(IJavaElement element) { - - if (element != null && element.getElementType() == IJavaElement.TYPE) { - IType type = (IType) element; - try { - return type.isMember(); - } catch (JavaModelException e) { - IJavaElement parent = type.getParent(); - if (parent != null) { - int parentElementType = parent.getElementType(); - return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE); - } - } - } - - return false; - } - - /** - * Returns the IShowInSource for this view. - * - * @return the {@link IShowInSource} - */ - protected IShowInSource getShowInSource() { - return new IShowInSource() { - public ShowInContext getShowInContext() { - return new ShowInContext(null, getSite().getSelectionProvider() - .getSelection()); - } - }; - } - - /** - * Returns the IShowInTarget for this view. - * - * @return the {@link IShowInTarget} - */ - protected IShowInTarget getShowInTarget() { - return new IShowInTarget() { - public boolean show(ShowInContext context) { - ISelection sel = context.getSelection(); - if (sel instanceof ITextSelection) { - ITextSelection tsel = (ITextSelection) sel; - int offset = tsel.getOffset(); - IJavaElement element = fEditor.getElementAt(offset); - if (element != null) { - setSelection(new StructuredSelection(element)); - return true; - } - } - return false; - } - }; - } - - private void initDragAndDrop() { -// int ops = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; -// Transfer[] transfers = new Transfer[] { LocalSelectionTransfer -// .getInstance() }; - - // Drop Adapter - // TransferDropTargetListener[] dropListeners= new - // TransferDropTargetListener[] { - // new SelectionTransferDropAdapter(fOutlineViewer) - // }; - // fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new - // DelegatingDropAdapter(dropListeners)); - - // Drag Adapter - // TransferDragSourceListener[] dragListeners= new - // TransferDragSourceListener[] { - // new SelectionTransferDragAdapter(fOutlineViewer) - // }; - // fOutlineViewer.addDragSupport(ops, transfers, new - // JdtViewerDragAdapter(fOutlineViewer, dragListeners)); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java deleted file mode 100644 index b80e336..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2003 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.ui.editors.text.StorageDocumentProvider; - -/** - * @since 3.0 - */ -public class JavaStorageDocumentProvider extends StorageDocumentProvider { - - public JavaStorageDocumentProvider() { - super(); - } - - /* - * @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, - * org.eclipse.jface.text.IDocument) - */ - protected void setupDocument(Object element, IDocument document) { - - if (document != null) { - JavaTextTools tools = WebUI.getDefault() - .getJavaTextTools(); - tools.setupJavaDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING); - - // tools.setupJavaDocumentPartitioner(document, - // IDocument.DEFAULT_CONTENT_TYPE, element); //IPHPPartitions.HTML, - // element); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java deleted file mode 100644 index a5dd6d6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java +++ /dev/null @@ -1,1734 +0,0 @@ -package net.sourceforge.phpeclipse.phpeditor; - -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IProblemRequestor; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.core.compiler.IProblem; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension; -import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy.SpellProblem; -import net.sourceforge.phpdt.ui.PreferenceConstants; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceRuleFactory; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.jface.preference.IPreferenceStore; -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultLineTracker; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ILineTracker; -import org.eclipse.jface.text.ISynchronizable; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.AnnotationModelEvent; -import org.eclipse.jface.text.source.IAnnotationAccessExtension; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelListener; -import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; -import org.eclipse.jface.text.source.IAnnotationPresentation; -import org.eclipse.jface.text.source.ImageUtilities; -import org.eclipse.jface.util.IPropertyChangeListener; -//incastrix -//import org.eclipse.jface.util.ListenerList; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.editors.text.ForwardingDocumentProvider; -import org.eclipse.ui.editors.text.TextFileDocumentProvider; -import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.ui.texteditor.MarkerUtilities; -import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; - -/** - * The PHPDocumentProvider provides the IDocuments used by java editors. - */ - -public class PHPDocumentProvider extends TextFileDocumentProvider implements - ICompilationUnitDocumentProvider { - /** - * Here for visibility issues only. - */ - - /** - * Bundle of all required informations to allow working copy management. - */ - /** - * Bundle of all required informations to allow working copy management. - */ - static protected class CompilationUnitInfo extends FileInfo { - public ICompilationUnit fCopy; - } - - /** - * Annotation model dealing with java marker annotations and temporary - * problems. Also acts as problem requestor for its compilation unit. - * Initialiy inactive. Must explicitly be activated. - */ - protected static class CompilationUnitAnnotationModel extends - ResourceMarkerAnnotationModel implements IProblemRequestor, - IProblemRequestorExtension { - - private static class ProblemRequestorState { - boolean fInsideReportingSequence = false; - - List fReportedProblems; - } - - private ThreadLocal fProblemRequestorState = new ThreadLocal(); - - private int fStateCount = 0; - - private ICompilationUnit fCompilationUnit; - - private List fGeneratedAnnotations; - - private IProgressMonitor fProgressMonitor; - - private boolean fIsActive = false; - - private ReverseMap fReverseMap = new ReverseMap(); - - private List fPreviouslyOverlaid = null; - - private List fCurrentlyOverlaid = new ArrayList(); - - public CompilationUnitAnnotationModel(IResource resource) { - super(resource); - } - - public void setCompilationUnit(ICompilationUnit unit) { - fCompilationUnit = unit; - } - - protected MarkerAnnotation createMarkerAnnotation(IMarker marker) { - String markerType = MarkerUtilities.getMarkerType(marker); - if (markerType != null - && markerType - .startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX)) - return new JavaMarkerAnnotation(marker); - return super.createMarkerAnnotation(marker); - } - - /* - * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent() - */ - protected AnnotationModelEvent createAnnotationModelEvent() { - return new CompilationUnitAnnotationModelEvent(this, getResource()); - } - - protected Position createPositionFromProblem(IProblem problem) { - int start = problem.getSourceStart(); - if (start < 0) - return null; - - int length = problem.getSourceEnd() - problem.getSourceStart() + 1; - if (length < 0) - return null; - - return new Position(start, length); - } - - /* - * @see IProblemRequestor#beginReporting() - */ - public void beginReporting() { - ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState - .get(); - if (state == null) - internalBeginReporting(false); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence() - */ - public void beginReportingSequence() { - ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState - .get(); - if (state == null) - internalBeginReporting(true); - } - - /** - * Sets up the infrastructure necessary for problem reporting. - * - * @param insideReportingSequence - * true if this method call is issued from - * inside a reporting sequence - */ - private void internalBeginReporting(boolean insideReportingSequence) { - if (fCompilationUnit != null) { - // && - // fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) - // { - ProblemRequestorState state = new ProblemRequestorState(); - state.fInsideReportingSequence = insideReportingSequence; - state.fReportedProblems = new ArrayList(); - synchronized (getLockObject()) { - fProblemRequestorState.set(state); - ++fStateCount; - } - } - } - - /* - * @see IProblemRequestor#acceptProblem(IProblem) - */ - public void acceptProblem(IProblem problem) { - if (isActive()) { - ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState - .get(); - if (state != null) - state.fReportedProblems.add(problem); - } - } - - /* - * @see IProblemRequestor#endReporting() - */ - public void endReporting() { - ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState - .get(); - if (state != null && !state.fInsideReportingSequence) - internalEndReporting(state); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence() - */ - public void endReportingSequence() { - ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState - .get(); - if (state != null && state.fInsideReportingSequence) - internalEndReporting(state); - } - - private void internalEndReporting(ProblemRequestorState state) { - int stateCount = 0; - synchronized (getLockObject()) { - --fStateCount; - stateCount = fStateCount; - fProblemRequestorState.set(null); - } - - if (stateCount == 0 && isActive()) - reportProblems(state.fReportedProblems); - } - - /** - * Signals the end of problem reporting. - */ - private void reportProblems(List reportedProblems) { - if (fProgressMonitor != null && fProgressMonitor.isCanceled()) - return; - - boolean temporaryProblemsChanged = false; - - synchronized (getLockObject()) { - - boolean isCanceled = false; - - fPreviouslyOverlaid = fCurrentlyOverlaid; - fCurrentlyOverlaid = new ArrayList(); - - if (fGeneratedAnnotations.size() > 0) { - temporaryProblemsChanged = true; - removeAnnotations(fGeneratedAnnotations, false, true); - fGeneratedAnnotations.clear(); - } - - if (reportedProblems != null && reportedProblems.size() > 0) { - - Iterator e = reportedProblems.iterator(); - while (e.hasNext()) { - - if (fProgressMonitor != null - && fProgressMonitor.isCanceled()) { - isCanceled = true; - break; - } - - IProblem problem = (IProblem) e.next(); - Position position = createPositionFromProblem(problem); - if (position != null) { - - try { - ProblemAnnotation annotation = new ProblemAnnotation( - problem, fCompilationUnit); - overlayMarkers(position, annotation); - addAnnotation(annotation, position, false); - fGeneratedAnnotations.add(annotation); - - temporaryProblemsChanged = true; - } catch (BadLocationException x) { - // ignore invalid position - } - } - } - } - - removeMarkerOverlays(isCanceled); - fPreviouslyOverlaid = null; - } - - if (temporaryProblemsChanged) - fireModelChanged(); - } - - private void removeMarkerOverlays(boolean isCanceled) { - if (isCanceled) { - fCurrentlyOverlaid.addAll(fPreviouslyOverlaid); - } else if (fPreviouslyOverlaid != null) { - Iterator e = fPreviouslyOverlaid.iterator(); - while (e.hasNext()) { - JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) e - .next(); - annotation.setOverlay(null); - } - } - } - - /** - * Overlays value with problem annotation. - * - * @param problemAnnotation - */ - private void setOverlay(Object value, - ProblemAnnotation problemAnnotation) { - if (value instanceof JavaMarkerAnnotation) { - JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) value; - if (annotation.isProblem()) { - annotation.setOverlay(problemAnnotation); - fPreviouslyOverlaid.remove(annotation); - fCurrentlyOverlaid.add(annotation); - } - } else { - } - } - - private void overlayMarkers(Position position, - ProblemAnnotation problemAnnotation) { - Object value = getAnnotations(position); - if (value instanceof List) { - List list = (List) value; - for (Iterator e = list.iterator(); e.hasNext();) - setOverlay(e.next(), problemAnnotation); - } else { - setOverlay(value, problemAnnotation); - } - } - - /** - * Tells this annotation model to collect temporary problems from now - * on. - */ - private void startCollectingProblems() { - fGeneratedAnnotations = new ArrayList(); - } - - /** - * Tells this annotation model to no longer collect temporary problems. - */ - private void stopCollectingProblems() { - if (fGeneratedAnnotations != null) - removeAnnotations(fGeneratedAnnotations, true, true); - fGeneratedAnnotations = null; - } - - /* - * @see IProblemRequestor#isActive() - */ - public boolean isActive() { - return fIsActive; - } - - /* - * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor) - */ - public void setProgressMonitor(IProgressMonitor monitor) { - fProgressMonitor = monitor; - } - - /* - * @see IProblemRequestorExtension#setIsActive(boolean) - */ - public void setIsActive(boolean isActive) { - if (fIsActive != isActive) { - fIsActive = isActive; - if (fIsActive) - startCollectingProblems(); - else - stopCollectingProblems(); - } - } - - private Object getAnnotations(Position position) { - return fReverseMap.get(position); - } - - /* - * @see AnnotationModel#addAnnotation(Annotation, Position, boolean) - */ - protected void addAnnotation(Annotation annotation, Position position, - boolean fireModelChanged) throws BadLocationException { - super.addAnnotation(annotation, position, fireModelChanged); - - Object cached = fReverseMap.get(position); - if (cached == null) - fReverseMap.put(position, annotation); - else if (cached instanceof List) { - List list = (List) cached; - list.add(annotation); - } else if (cached instanceof Annotation) { - List list = new ArrayList(2); - list.add(cached); - list.add(annotation); - fReverseMap.put(position, list); - } - } - - /* - * @see AnnotationModel#removeAllAnnotations(boolean) - */ - protected void removeAllAnnotations(boolean fireModelChanged) { - super.removeAllAnnotations(fireModelChanged); - fReverseMap.clear(); - } - - /* - * @see AnnotationModel#removeAnnotation(Annotation, boolean) - */ - protected void removeAnnotation(Annotation annotation, - boolean fireModelChanged) { - Position position = getPosition(annotation); - Object cached = fReverseMap.get(position); - if (cached instanceof List) { - List list = (List) cached; - list.remove(annotation); - if (list.size() == 1) { - fReverseMap.put(position, list.get(0)); - list.clear(); - } - } else if (cached instanceof Annotation) { - fReverseMap.remove(position); - } - super.removeAnnotation(annotation, fireModelChanged); - } - } - - protected static class GlobalAnnotationModelListener implements - IAnnotationModelListener, IAnnotationModelListenerExtension { - - private ListenerList fListenerList; - - public GlobalAnnotationModelListener() { - fListenerList = new ListenerList(); - } - - public void addListener(IAnnotationModelListener listener) { - fListenerList.add(listener); - } - - /** - * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) - */ - public void modelChanged(AnnotationModelEvent event) { - Object[] listeners = fListenerList.getListeners(); - for (int i = 0; i < listeners.length; i++) { - Object curr = listeners[i]; - if (curr instanceof IAnnotationModelListenerExtension) { - ((IAnnotationModelListenerExtension) curr) - .modelChanged(event); - } - } - } - - /** - * @see IAnnotationModelListener#modelChanged(IAnnotationModel) - */ - public void modelChanged(IAnnotationModel model) { - Object[] listeners = fListenerList.getListeners(); - for (int i = 0; i < listeners.length; i++) { - ((IAnnotationModelListener) listeners[i]).modelChanged(model); - } - } - - public void removeListener(IAnnotationModelListener listener) { - fListenerList.remove(listener); - } - } - - /** - * Annotation representating an IProblem. - */ - static public class ProblemAnnotation extends Annotation implements - IJavaAnnotation, IAnnotationPresentation { - - private static final String SPELLING_ANNOTATION_TYPE = "org.eclipse.ui.workbench.texteditor.spelling"; - - // XXX: To be fully correct these constants should be non-static - /** - * The layer in which task problem annotations are located. - */ - private static final int TASK_LAYER; - - /** - * The layer in which info problem annotations are located. - */ - private static final int INFO_LAYER; - - /** - * The layer in which warning problem annotations representing are - * located. - */ - private static final int WARNING_LAYER; - - /** - * The layer in which error problem annotations representing are - * located. - */ - private static final int ERROR_LAYER; - - static { - AnnotationPreferenceLookup lookup = EditorsUI - .getAnnotationPreferenceLookup(); - TASK_LAYER = computeLayer( - "org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$ - INFO_LAYER = computeLayer("net.sourceforge.phpdt.ui.info", lookup); //$NON-NLS-1$ - WARNING_LAYER = computeLayer( - "net.sourceforge.phpdt.ui.warning", lookup); //$NON-NLS-1$ - ERROR_LAYER = computeLayer("net.sourceforge.phpdt.ui.error", lookup); //$NON-NLS-1$ - } - - private static int computeLayer(String annotationType, - AnnotationPreferenceLookup lookup) { - Annotation annotation = new Annotation(annotationType, false, null); - AnnotationPreference preference = lookup - .getAnnotationPreference(annotation); - if (preference != null) - return preference.getPresentationLayer() + 1; - else - return IAnnotationAccessExtension.DEFAULT_LAYER + 1; - } - - // private static Image fgQuickFixImage; - // private static Image fgQuickFixErrorImage; - // private static boolean fgQuickFixImagesInitialized= false; - - private ICompilationUnit fCompilationUnit; - - private List fOverlaids; - - private IProblem fProblem; - - private Image fImage; - - //private boolean fQuickFixImagesInitialized = false; - - private int fLayer = IAnnotationAccessExtension.DEFAULT_LAYER; - - public ProblemAnnotation(IProblem problem, ICompilationUnit cu) { - - fProblem = problem; - fCompilationUnit = cu; - - if (SpellProblem.Spelling == fProblem.getID()) { - setType(SPELLING_ANNOTATION_TYPE); - fLayer = WARNING_LAYER; - } else if (IProblem.Task == fProblem.getID()) { - setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE); - fLayer = TASK_LAYER; - } else if (fProblem.isWarning()) { - setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE); - fLayer = WARNING_LAYER; - } else if (fProblem.isError()) { - setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE); - fLayer = ERROR_LAYER; - } else { - setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE); - fLayer = INFO_LAYER; - } - } - - /* - * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() - */ - public int getLayer() { - return fLayer; - } - - private void initializeImages() { - // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936 - // if (!fQuickFixImagesInitialized) { - // if (isProblem() && indicateQuixFixableProblems() && - // JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb - // for tasks - // if (!fgQuickFixImagesInitialized) { - // fgQuickFixImage= - // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); - // fgQuickFixErrorImage= - // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); - // fgQuickFixImagesInitialized= true; - // } - // if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType())) - // fImage= fgQuickFixErrorImage; - // else - // fImage= fgQuickFixImage; - // } - // fQuickFixImagesInitialized= true; - // } - } - -// private boolean indicateQuixFixableProblems() { -// return PreferenceConstants.getPreferenceStore().getBoolean( -// PreferenceConstants.EDITOR_CORRECTION_INDICATION); -// } - - /* - * @see Annotation#paint - */ - public void paint(GC gc, Canvas canvas, Rectangle r) { - initializeImages(); - if (fImage != null) - ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, - SWT.TOP); - } - - /* - * @see IJavaAnnotation#getImage(Display) - */ - public Image getImage(Display display) { - initializeImages(); - return fImage; - } - - /* - * @see IJavaAnnotation#getMessage() - */ - public String getText() { - return fProblem.getMessage(); - } - - /* - * @see IJavaAnnotation#getArguments() - */ - public String[] getArguments() { - return isProblem() ? fProblem.getArguments() : null; - } - - /* - * @see IJavaAnnotation#getId() - */ - public int getId() { - return fProblem.getID(); - } - - /* - * @see IJavaAnnotation#isProblem() - */ - public boolean isProblem() { - String type = getType(); - return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) - || JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) - || SPELLING_ANNOTATION_TYPE.equals(type); - } - - /* - * @see IJavaAnnotation#hasOverlay() - */ - public boolean hasOverlay() { - return false; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay() - */ - public IJavaAnnotation getOverlay() { - return null; - } - - /* - * @see IJavaAnnotation#addOverlaid(IJavaAnnotation) - */ - public void addOverlaid(IJavaAnnotation annotation) { - if (fOverlaids == null) - fOverlaids = new ArrayList(1); - fOverlaids.add(annotation); - } - - /* - * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation) - */ - public void removeOverlaid(IJavaAnnotation annotation) { - if (fOverlaids != null) { - fOverlaids.remove(annotation); - if (fOverlaids.size() == 0) - fOverlaids = null; - } - } - - /* - * @see IJavaAnnotation#getOverlaidIterator() - */ - public Iterator getOverlaidIterator() { - if (fOverlaids != null) - return fOverlaids.iterator(); - return null; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit() - */ - public ICompilationUnit getCompilationUnit() { - return fCompilationUnit; - } - } - - /** - * Internal structure for mapping positions to some value. The reason for - * this specific structure is that positions can change over time. Thus a - * lookup is based on value and not on hash value. - */ - protected static class ReverseMap { - - static class Entry { - Position fPosition; - - Object fValue; - } - - private int fAnchor = 0; - - private List fList = new ArrayList(2); - - public ReverseMap() { - } - - public void clear() { - fList.clear(); - } - - public Object get(Position position) { - - Entry entry; - - // behind anchor - int length = fList.size(); - for (int i = fAnchor; i < length; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) { - fAnchor = i; - return entry.fValue; - } - } - - // before anchor - for (int i = 0; i < fAnchor; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) { - fAnchor = i; - return entry.fValue; - } - } - - return null; - } - - private int getIndex(Position position) { - Entry entry; - int length = fList.size(); - for (int i = 0; i < length; i++) { - entry = (Entry) fList.get(i); - if (entry.fPosition.equals(position)) - return i; - } - return -1; - } - - public void put(Position position, Object value) { - int index = getIndex(position); - if (index == -1) { - Entry entry = new Entry(); - entry.fPosition = position; - entry.fValue = value; - fList.add(entry); - } else { - Entry entry = (Entry) fList.get(index); - entry.fValue = value; - } - } - - public void remove(Position position) { - int index = getIndex(position); - if (index > -1) - fList.remove(index); - } - } - - /** - * Document that can also be used by a background reconciler. - */ - protected static class PartiallySynchronizedDocument extends Document { - - /* - * @see IDocumentExtension#startSequentialRewrite(boolean) - */ - synchronized public void startSequentialRewrite(boolean normalized) { - super.startSequentialRewrite(normalized); - } - - /* - * @see IDocumentExtension#stopSequentialRewrite() - */ - synchronized public void stopSequentialRewrite() { - super.stopSequentialRewrite(); - } - - /* - * @see IDocument#get() - */ - synchronized public String get() { - return super.get(); - } - - /* - * @see IDocument#get(int, int) - */ - synchronized public String get(int offset, int length) - throws BadLocationException { - return super.get(offset, length); - } - - /* - * @see IDocument#getChar(int) - */ - synchronized public char getChar(int offset) - throws BadLocationException { - return super.getChar(offset); - } - - /* - * @see IDocument#replace(int, int, String) - */ - synchronized public void replace(int offset, int length, String text) - throws BadLocationException { - super.replace(offset, length, text); - } - - /* - * @see IDocument#set(String) - */ - synchronized public void set(String text) { - super.set(text); - } - }; - - // - // private static PHPPartitionScanner HTML_PARTITION_SCANNER = null; - // - // private static PHPPartitionScanner PHP_PARTITION_SCANNER = null; - // private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null; - // - // // private final static String[] TYPES= new String[] { - // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, - // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; - // private final static String[] TYPES = - // new String[] { - // IPHPPartitionScannerConstants.PHP, - // IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT, - // IPHPPartitionScannerConstants.HTML, - // IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT, - // IPHPPartitionScannerConstants.JAVASCRIPT, - // IPHPPartitionScannerConstants.CSS, - // IPHPPartitionScannerConstants.SMARTY, - // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT }; - // private static PHPPartitionScanner XML_PARTITION_SCANNER = null; - - /* Preference key for temporary problems */ - private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS; - - /** Indicates whether the save has been initialized by this provider */ - private boolean fIsAboutToSave = false; - - /** The save policy used by this provider */ - private ISavePolicy fSavePolicy; - - /** Internal property changed listener */ - private IPropertyChangeListener fPropertyListener; - - /** annotation model listener added to all created CU annotation models */ - private GlobalAnnotationModelListener fGlobalAnnotationModelListener; - - public PHPDocumentProvider() { - // IDocumentProvider provider= new TextFileDocumentProvider(new - // JavaStorageDocumentProvider()); - IDocumentProvider provider = new TextFileDocumentProvider(); - provider = new ForwardingDocumentProvider( - IPHPPartitions.PHP_PARTITIONING, - new JavaDocumentSetupParticipant(), provider); - setParentDocumentProvider(provider); - - fGlobalAnnotationModelListener = new GlobalAnnotationModelListener(); - fPropertyListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty())) - enableHandlingTemporaryProblems(); - } - }; - WebUI.getDefault().getPreferenceStore() - .addPropertyChangeListener(fPropertyListener); - - } - - /** - * Sets the document provider's save policy. - */ - public void setSavePolicy(ISavePolicy savePolicy) { - fSavePolicy = savePolicy; - } - - /** - * Creates a compilation unit from the given file. - * - * @param file - * the file from which to create the compilation unit - */ - protected ICompilationUnit createCompilationUnit(IFile file) { - Object element = JavaCore.create(file); - if (element instanceof ICompilationUnit) - return (ICompilationUnit) element; - return null; - } - - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo() - */ - protected FileInfo createEmptyFileInfo() { - return new CompilationUnitInfo(); - } - - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile) - */ - protected IAnnotationModel createAnnotationModel(IFile file) { - return new CompilationUnitAnnotationModel(file); - } - - /* - * @see AbstractDocumentProvider#createElementInfo(Object) - */ - // protected ElementInfo createElementInfo(Object element) throws - // CoreException { - // - // if (!(element instanceof IFileEditorInput)) - // return super.createElementInfo(element); - // - // IFileEditorInput input = (IFileEditorInput) element; - // ICompilationUnit original = createCompilationUnit(input.getFile()); - // if (original != null) { - // - // try { - // - // try { - // refreshFile(input.getFile()); - // } catch (CoreException x) { - // handleCoreException(x, - // PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); - // //$NON-NLS-1$ - // } - // - // IAnnotationModel m = createCompilationUnitAnnotationModel(input); - // IProblemRequestor r = m instanceof IProblemRequestor ? - // (IProblemRequestor) m : null; - // ICompilationUnit c = (ICompilationUnit) - // original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r); - // - // DocumentAdapter a = null; - // try { - // a = (DocumentAdapter) c.getBuffer(); - // } catch (ClassCastException x) { - // IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, - // PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong - // buffer", x); //$NON-NLS-1$ - // throw new CoreException(status); - // } - // - // _FileSynchronizer f = new _FileSynchronizer(input); - // f.install(); - // - // CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, - // c); - // info.setModificationStamp(computeModificationStamp(input.getFile())); - // info.fStatus = a.getStatus(); - // info.fEncoding = getPersistedEncoding(input); - // - // if (r instanceof IProblemRequestorExtension) { - // IProblemRequestorExtension extension = (IProblemRequestorExtension) r; - // extension.setIsActive(isHandlingTemporaryProblems()); - // } - // m.addAnnotationModelListener(fGlobalAnnotationModelListener); - // - // return info; - // - // } catch (JavaModelException x) { - // throw new CoreException(x.getStatus()); - // } - // } else { - // return super.createElementInfo(element); - // } - // } - /* - * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo) - */ - // protected void disposeElementInfo(Object element, ElementInfo info) { - // - // if (info instanceof CompilationUnitInfo) { - // CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; - // cuInfo.fCopy.destroy(); - // cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); - // } - // - // super.disposeElementInfo(element, info); - // } - /* - * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, - * IDocument, boolean) - */ - // protected void doSaveDocument(IProgressMonitor monitor, Object element, - // IDocument document, boolean overwrite) - // throws CoreException { - // - // ElementInfo elementInfo = getElementInfo(element); - // if (elementInfo instanceof CompilationUnitInfo) { - // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; - // - // // update structure, assumes lock on info.fCopy - // info.fCopy.reconcile(); - // - // ICompilationUnit original = (ICompilationUnit) - // info.fCopy.getOriginalElement(); - // IResource resource = original.getResource(); - // - // if (resource == null) { - // // underlying resource has been deleted, just recreate file, ignore the - // rest - // super.doSaveDocument(monitor, element, document, overwrite); - // return; - // } - // - // if (resource != null && !overwrite) - // checkSynchronizationState(info.fModificationStamp, resource); - // - // if (fSavePolicy != null) - // fSavePolicy.preSave(info.fCopy); - // - // // inform about the upcoming content change - // fireElementStateChanging(element); - // try { - // fIsAboutToSave = true; - // // commit working copy - // info.fCopy.commit(overwrite, monitor); - // } catch (CoreException x) { - // // inform about the failure - // fireElementStateChangeFailed(element); - // throw x; - // } catch (RuntimeException x) { - // // inform about the failure - // fireElementStateChangeFailed(element); - // throw x; - // } finally { - // fIsAboutToSave = false; - // } - // - // // If here, the dirty state of the editor will change to "not dirty". - // // Thus, the state changing flag will be reset. - // - // AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) - // info.fModel; - // model.updateMarkers(info.fDocument); - // - // if (resource != null) - // info.setModificationStamp(computeModificationStamp(resource)); - // - // if (fSavePolicy != null) { - // ICompilationUnit unit = fSavePolicy.postSave(original); - // if (unit != null) { - // IResource r = unit.getResource(); - // IMarker[] markers = r.findMarkers(IMarker.MARKER, true, - // IResource.DEPTH_ZERO); - // if (markers != null && markers.length > 0) { - // for (int i = 0; i < markers.length; i++) - // model.updateMarker(markers[i], info.fDocument, null); - // } - // } - // } - // - // } else { - // super.doSaveDocument(monitor, element, document, overwrite); - // } - // } - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object) - */ - protected FileInfo createFileInfo(Object element) throws CoreException { - if (!(element instanceof IFileEditorInput)) - return null; - - IFileEditorInput input = (IFileEditorInput) element; - ICompilationUnit original = createCompilationUnit(input.getFile()); - if (original == null) - return null; - - FileInfo info = super.createFileInfo(element); - if (!(info instanceof CompilationUnitInfo)) - return null; - - CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; - setUpSynchronization(cuInfo); - - IProblemRequestor requestor = cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel - : null; - - original.becomeWorkingCopy(requestor, getProgressMonitor()); - cuInfo.fCopy = original; - - if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) { - CompilationUnitAnnotationModel model = (CompilationUnitAnnotationModel) cuInfo.fModel; - model.setCompilationUnit(cuInfo.fCopy); - } - - if (cuInfo.fModel != null) - cuInfo.fModel - .addAnnotationModelListener(fGlobalAnnotationModelListener); - - if (requestor instanceof IProblemRequestorExtension) { - IProblemRequestorExtension extension = (IProblemRequestorExtension) requestor; - extension.setIsActive(isHandlingTemporaryProblems()); - } - - return cuInfo; - } - - private void setUpSynchronization(CompilationUnitInfo cuInfo) { - IDocument document = cuInfo.fTextFileBuffer.getDocument(); - IAnnotationModel model = cuInfo.fModel; - - if (document instanceof ISynchronizable - && model instanceof ISynchronizable) { - Object lock = ((ISynchronizable) document).getLockObject(); - ((ISynchronizable) model).setLockObject(lock); - } - } - - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, - * org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo) - */ - protected void disposeFileInfo(Object element, FileInfo info) { - if (info instanceof CompilationUnitInfo) { - CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; - - try { - cuInfo.fCopy.discardWorkingCopy(); - } catch (JavaModelException x) { - handleCoreException(x, x.getMessage()); - } - - if (cuInfo.fModel != null) - cuInfo.fModel - .removeAnnotationModelListener(fGlobalAnnotationModelListener); - } - super.disposeFileInfo(element, info); - } - - protected void commitWorkingCopy(IProgressMonitor monitor, Object element, - CompilationUnitInfo info, boolean overwrite) throws CoreException { - synchronized (info.fCopy) { - info.fCopy.reconcile(); - } - - IDocument document = info.fTextFileBuffer.getDocument(); - IResource resource = info.fCopy.getResource(); - - Assert.isTrue(resource instanceof IFile); - if (!resource.exists()) { - // underlying resource has been deleted, just recreate file, ignore - // the rest - createFileFromDocument(monitor, (IFile) resource, document); - return; - } - - if (fSavePolicy != null) - fSavePolicy.preSave(info.fCopy); - - try { - - fIsAboutToSave = true; - info.fCopy.commitWorkingCopy(overwrite, monitor); - - } catch (CoreException x) { - // inform about the failure - fireElementStateChangeFailed(element); - throw x; - } catch (RuntimeException x) { - // inform about the failure - fireElementStateChangeFailed(element); - throw x; - } finally { - fIsAboutToSave = false; - } - - // If here, the dirty state of the editor will change to "not dirty". - // Thus, the state changing flag will be reset. - if (info.fModel instanceof AbstractMarkerAnnotationModel) { - AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; - model.updateMarkers(document); - } - - if (fSavePolicy != null) { - ICompilationUnit unit = fSavePolicy.postSave(info.fCopy); - if (unit != null - && info.fModel instanceof AbstractMarkerAnnotationModel) { - IResource r = unit.getResource(); - IMarker[] markers = r.findMarkers(IMarker.MARKER, true, - IResource.DEPTH_ZERO); - if (markers != null && markers.length > 0) { - AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; - for (int i = 0; i < markers.length; i++) - model.updateMarker(document, markers[i], null); - } - } - } - - } - - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, - * org.eclipse.jface.text.IDocument, boolean) - */ - protected DocumentProviderOperation createSaveOperation( - final Object element, final IDocument document, - final boolean overwrite) throws CoreException { - // final FileInfo info= getFileInfo(element); - // if (info instanceof CompilationUnitInfo) { - // return new DocumentProviderOperation() { - // /* - // * @see - // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) - // */ - // protected void execute(IProgressMonitor monitor) throws CoreException - // { - // commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, - // overwrite); - // } - // /* - // * @see - // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() - // */ - // public ISchedulingRule getSchedulingRule() { - // if (info.fElement instanceof IFileEditorInput) { - // IFile file= ((IFileEditorInput) info.fElement).getFile(); - // IResourceRuleFactory ruleFactory= - // ResourcesPlugin.getWorkspace().getRuleFactory(); - // if (file == null || !file.exists()) - // return ruleFactory.createRule(file); - // else - // return ruleFactory.modifyRule(file); - // } else - // return null; - // } - // }; - // } - // return null; - final FileInfo info = getFileInfo(element); - if (info instanceof CompilationUnitInfo) { - return new DocumentProviderOperation() { - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) - */ - protected void execute(IProgressMonitor monitor) - throws CoreException { - commitWorkingCopy(monitor, element, - (CompilationUnitInfo) info, overwrite); - } - - /* - * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() - */ - public ISchedulingRule getSchedulingRule() { - if (info.fElement instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) info.fElement) - .getFile(); - return computeSchedulingRule(file); - } else - return null; - } - }; - } - return null; - } - - /* - * (non-Javadoc) Method declared on AbstractDocumentProvider - */ - // protected IDocument createDocument(Object element) throws CoreException { - // if (element instanceof IEditorInput) { - // Document document = new PartiallySynchronizedDocument(); - // if (setDocumentContent(document, (IEditorInput) element, - // getEncoding(element))) { - // initializeDocument(document, (IEditorInput) element); - // - // // - // // IDocument document = super.createDocument(element); - // // if (document != null) { - // // IDocumentPartitioner partitioner = null; - // // if (element instanceof FileEditorInput) { - // // IFile file = (IFile) ((FileEditorInput) - // element).getAdapter(IFile.class); - // // String filename = file.getLocation().toString(); - // // String extension = filename.substring(filename.lastIndexOf("."), - // filename.length()); - // // // System.out.println(extension); - // // if (extension.equalsIgnoreCase(".html") || - // extension.equalsIgnoreCase(".htm")) { - // // // html - // // partitioner = createHTMLPartitioner(); - // // } else if (extension.equalsIgnoreCase(".xml")) { - // // // xml - // // partitioner = createXMLPartitioner(); - // // } else if (extension.equalsIgnoreCase(".js")) { - // // // javascript - // // partitioner = createJavaScriptPartitioner(); - // // } else if (extension.equalsIgnoreCase(".css")) { - // // // cascading style sheets - // // partitioner = createCSSPartitioner(); - // // } else if (extension.equalsIgnoreCase(".tpl")) { - // // // smarty ? - // // partitioner = createSmartyPartitioner(); - // // } else if (extension.equalsIgnoreCase(".inc")) { - // // // php include files ? - // // partitioner = createIncludePartitioner(); - // // } - // // } - // // - // // if (partitioner == null) { - // // partitioner = createPHPPartitioner(); - // // } - // // document.setDocumentPartitioner(partitioner); - // // partitioner.connect(document); - // } - // return document; - // } - // return null; - // } - // /** - // * Return a partitioner for .html files. - // */ - // private IDocumentPartitioner createHTMLPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createIncludePartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createJavaScriptPartitioner() { - // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); - // } - /** - * Creates a line tracker working with the same line delimiters as the - * document of the given element. Assumes the element to be managed by this - * document provider. - * - * @param element - * the element serving as blue print - * @return a line tracker based on the same line delimiters as the element's - * document - */ - public ILineTracker createLineTracker(Object element) { - return new DefaultLineTracker(); - } - - // /** - // * Return a partitioner for .php files. - // */ - // private IDocumentPartitioner createPHPPartitioner() { - // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createSmartyPartitioner() { - // return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES); - // } - // - // private IDocumentPartitioner createXMLPartitioner() { - // return new DefaultPartitioner(getXMLPartitionScanner(), TYPES); - // } - // - // /** - // * Return a scanner for creating html partitions. - // */ - // private PHPPartitionScanner getHTMLPartitionScanner() { - // if (HTML_PARTITION_SCANNER == null) - // HTML_PARTITION_SCANNER = new - // PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE); - // return HTML_PARTITION_SCANNER; - // } - // /** - // * Return a scanner for creating php partitions. - // */ - // private PHPPartitionScanner getPHPPartitionScanner() { - // if (PHP_PARTITION_SCANNER == null) - // PHP_PARTITION_SCANNER = new - // PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE); - // return PHP_PARTITION_SCANNER; - // } - // - // /** - // * Return a scanner for creating smarty partitions. - // */ - // private PHPPartitionScanner getSmartyPartitionScanner() { - // if (SMARTY_PARTITION_SCANNER == null) - // SMARTY_PARTITION_SCANNER = new - // PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE); - // return SMARTY_PARTITION_SCANNER; - // } - // - // /** - // * Return a scanner for creating xml partitions. - // */ - // private PHPPartitionScanner getXMLPartitionScanner() { - // if (XML_PARTITION_SCANNER == null) - // XML_PARTITION_SCANNER = new - // PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE); - // return XML_PARTITION_SCANNER; - // } - - // protected void initializeDocument(IDocument document, IEditorInput - // editorInput) { - // if (document != null) { - // JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); - // IDocumentPartitioner partitioner = null; - // if (editorInput != null && editorInput instanceof FileEditorInput) { - // IFile file = (IFile) ((FileEditorInput) - // editorInput).getAdapter(IFile.class); - // String filename = file.getLocation().toString(); - // String extension = filename.substring(filename.lastIndexOf("."), - // filename.length()); - // partitioner = tools.createDocumentPartitioner(extension); - // } else { - // partitioner = tools.createDocumentPartitioner(".php"); - // } - // document.setDocumentPartitioner(partitioner); - // partitioner.connect(document); - // } - // } - - /* - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, - * org.eclipse.core.runtime.IProgressMonitor) - */ - // protected void doResetDocument(Object element, IProgressMonitor monitor) - // throws CoreException { - // if (element == null) - // return; - // - // ElementInfo elementInfo= getElementInfo(element); - // if (elementInfo instanceof CompilationUnitInfo) { - // CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; - // - // IDocument document; - // IStatus status= null; - // - // try { - // - // ICompilationUnit original= (ICompilationUnit) - // info.fCopy.getOriginalElement(); - // IResource resource= original.getResource(); - // if (resource instanceof IFile) { - // - // IFile file= (IFile) resource; - // - // try { - // refreshFile(file, monitor); - // } catch (CoreException x) { - // handleCoreException(x, - // PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); - // //$NON-NLS-1$ - // } - // - // IFileEditorInput input= new FileEditorInput(file); - // document= super.createDocument(input); - // - // } else { - // document= createEmptyDocument(); - // } - // - // } catch (CoreException x) { - // document= createEmptyDocument(); - // status= x.getStatus(); - // } - // - // fireElementContentAboutToBeReplaced(element); - // - // removeUnchangedElementListeners(element, info); - // info.fDocument.set(document.get()); - // info.fCanBeSaved= false; - // info.fStatus= status; - // addUnchangedElementListeners(element, info); - // - // fireElementContentReplaced(element); - // fireElementDirtyStateChanged(element, false); - // - // } else { - // super.doResetDocument(element, monitor); - // } - // } - /* - * @see AbstractDocumentProvider#resetDocument(Object) - */ - // public void resetDocument(Object element) throws CoreException { - // if (element == null) - // return; - // - // ElementInfo elementInfo = getElementInfo(element); - // if (elementInfo instanceof CompilationUnitInfo) { - // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; - // - // IDocument document; - // IStatus status = null; - // - // try { - // - // ICompilationUnit original = (ICompilationUnit) - // info.fCopy.getOriginalElement(); - // IResource resource = original.getResource(); - // if (resource instanceof IFile) { - // - // IFile file = (IFile) resource; - // - // try { - // refreshFile(file); - // } catch (CoreException x) { - // handleCoreException(x, - // PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); - // //$NON-NLS-1$ - // } - // - // IFileEditorInput input = new FileEditorInput(file); - // document = super.createDocument(input); - // - // } else { - // document = new Document(); - // } - // - // } catch (CoreException x) { - // document = new Document(); - // status = x.getStatus(); - // } - // - // fireElementContentAboutToBeReplaced(element); - // - // removeUnchangedElementListeners(element, info); - // info.fDocument.set(document.get()); - // info.fCanBeSaved = false; - // info.fStatus = status; - // addUnchangedElementListeners(element, info); - // - // fireElementContentReplaced(element); - // fireElementDirtyStateChanged(element, false); - // - // } else { - // super.resetDocument(element); - // } - // } - /** - * Saves the content of the given document to the given element. This is - * only performed when this provider initiated the save. - * - * @param monitor - * the progress monitor - * @param element - * the element to which to save - * @param document - * the document to save - * @param overwrite - * true if the save should be enforced - */ - public void saveDocumentContent(IProgressMonitor monitor, Object element, - IDocument document, boolean overwrite) throws CoreException { - if (!fIsAboutToSave) - return; - super.saveDocument(monitor, element, document, overwrite); - // if (!fIsAboutToSave) - // return; - // - // if (element instanceof IFileEditorInput) { - // IFileEditorInput input = (IFileEditorInput) element; - // try { - // String encoding = getEncoding(element); - // if (encoding == null) - // encoding = ResourcesPlugin.getEncoding(); - // InputStream stream = new - // ByteArrayInputStream(document.get().getBytes(encoding)); - // IFile file = input.getFile(); - // file.setContents(stream, overwrite, true, monitor); - // } catch (IOException x) { - // IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, - // IStatus.OK, x.getMessage(), x); - // throw new CoreException(s); - // } - // } - } - - /** - * Returns the underlying resource for the given element. - * - * @param the - * element - * @return the underlying resource of the given element - */ - // public IResource getUnderlyingResource(Object element) { - // if (element instanceof IFileEditorInput) { - // IFileEditorInput input = (IFileEditorInput) element; - // return input.getFile(); - // } - // return null; - // } - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object) - */ - public ICompilationUnit getWorkingCopy(Object element) { - FileInfo fileInfo = getFileInfo(element); - if (fileInfo instanceof CompilationUnitInfo) { - CompilationUnitInfo info = (CompilationUnitInfo) fileInfo; - return info.fCopy; - } - return null; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown() - */ - public void shutdown() { - WebUI.getDefault().getPreferenceStore() - .removePropertyChangeListener(fPropertyListener); - Iterator e = getConnectedElementsIterator(); - while (e.hasNext()) - disconnect(e.next()); - } - - /** - * Returns the preference whether handling temporary problems is enabled. - */ - protected boolean isHandlingTemporaryProblems() { - IPreferenceStore store = WebUI.getDefault() - .getPreferenceStore(); - return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS); - } - - /** - * Switches the state of problem acceptance according to the value in the - * preference store. - */ - protected void enableHandlingTemporaryProblems() { - boolean enable = isHandlingTemporaryProblems(); - for (Iterator iter = getFileInfosIterator(); iter.hasNext();) { - FileInfo info = (FileInfo) iter.next(); - if (info.fModel instanceof IProblemRequestorExtension) { - IProblemRequestorExtension extension = (IProblemRequestorExtension) info.fModel; - extension.setIsActive(enable); - } - } - } - - /** - * Adds a listener that reports changes from all compilation unit annotation - * models. - */ - public void addGlobalAnnotationModelListener( - IAnnotationModelListener listener) { - fGlobalAnnotationModelListener.addListener(listener); - } - - /** - * Removes the listener. - */ - public void removeGlobalAnnotationModelListener( - IAnnotationModelListener listener) { - fGlobalAnnotationModelListener.removeListener(listener); - } - - /** - * Computes the scheduling rule needed to create or modify a resource. If - * the resource exists, its modify rule is returned. If it does not, the - * resource hierarchy is iterated towards the workspace root to find the - * first parent of toCreateOrModify that exists. Then the - * 'create' rule for the last non-existing resource is returned. - *

- * XXX This is a workaround for - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601 - * IResourceRuleFactory.createRule should iterate the hierarchy itself. - *

- *

- * XXX to be replaced by call to - * TextFileDocumentProvider.computeSchedulingRule after 3.0 - *

- * - * @param toCreateOrModify - * the resource to create or modify - * @return the minimal scheduling rule needed to modify or create a resource - */ - protected ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) { - IResourceRuleFactory factory = ResourcesPlugin.getWorkspace() - .getRuleFactory(); - if (toCreateOrModify.exists()) { - return factory.modifyRule(toCreateOrModify); - } else { - IResource parent = toCreateOrModify; - do { - toCreateOrModify = parent; - parent = toCreateOrModify.getParent(); - } while (parent != null && !parent.exists()); - - return factory.createRule(toCreateOrModify); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java deleted file mode 100644 index 8cc981c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java +++ /dev/null @@ -1,6106 +0,0 @@ -package net.sourceforge.phpeclipse.phpeditor; - -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.BreakIterator; -import java.text.CharacterIterator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.StringTokenizer; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IImportContainer; -import net.sourceforge.phpdt.core.IImportDeclaration; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; -import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup; -import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter; -import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl; -import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator; -import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; -import net.sourceforge.phpdt.internal.ui.text.JavaWordIterator; -import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher; -import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaExpandHover; -import net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST; -import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider; -import net.sourceforge.phpdt.internal.ui.viewsupport.SelectionListenerWithASTManager; -import net.sourceforge.phpdt.ui.IContextMenuConstants; -import net.sourceforge.phpdt.ui.JavaUI; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction; -import net.sourceforge.phpdt.ui.actions.OpenEditorActionGroup; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; -import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.ExternalEditorInput; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.editor.BrowserUtil; -import net.sourceforge.phpeclipse.webbrowser.views.BrowserView; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ISelectionValidator; -import org.eclipse.jface.text.ISynchronizable; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextPresentationListener; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.ITextViewerExtension4; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.InformationPresenter; -import org.eclipse.jface.text.link.LinkedModeModel; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.AnnotationRulerColumn; -import org.eclipse.jface.text.source.CompositeRuler; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelExtension; -import org.eclipse.jface.text.source.IOverviewRuler; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.ISourceViewerExtension2; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.jface.text.source.IVerticalRulerColumn; -import org.eclipse.jface.text.source.OverviewRuler; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -import org.eclipse.jface.text.source.projection.ProjectionSupport; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -//incastrix -//import org.eclipse.jface.util.ListenerList; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IPostSelectionProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.BidiSegmentEvent; -import org.eclipse.swt.custom.BidiSegmentListener; -import org.eclipse.swt.custom.ST; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPartService; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWindowListener; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.actions.ActionContext; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.editors.text.DefaultEncodingSupport; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.editors.text.IEncodingSupport; -import org.eclipse.ui.ide.FileStoreEditorInput; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.part.IShowInSource; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IEditorStatusLine; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.ui.texteditor.TextNavigationAction; -import org.eclipse.ui.texteditor.TextOperationAction; -import org.eclipse.ui.views.contentoutline.ContentOutline; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.ui.views.tasklist.TaskList; - -/** - * PHP specific text editor. - */ -public abstract class PHPEditor extends AbstractDecoratedTextEditor implements - IViewPartInputProvider, IShowInTargetList, IShowInSource { - // extends StatusTextEditor implements IViewPartInputProvider { // extends - // TextEditor { - - /** - * Internal implementation class for a change listener. - * - * @since 3.0 - */ - protected abstract class AbstractSelectionChangedListener implements - ISelectionChangedListener { - - /** - * Installs this selection changed listener with the given selection - * provider. If the selection provider is a post selection provider, - * post selection changed events are the preferred choice, otherwise - * normal selection changed events are requested. - * - * @param selectionProvider - */ - public void install(ISelectionProvider selectionProvider) { - if (selectionProvider == null) - return; - - if (selectionProvider instanceof IPostSelectionProvider) { - IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; - provider.addPostSelectionChangedListener(this); - } else { - selectionProvider.addSelectionChangedListener(this); - } - } - - /** - * Removes this selection changed listener from the given selection - * provider. - * - * @param selectionProvider - * the selection provider - */ - public void uninstall(ISelectionProvider selectionProvider) { - if (selectionProvider == null) - return; - - if (selectionProvider instanceof IPostSelectionProvider) { - IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; - provider.removePostSelectionChangedListener(this); - } else { - selectionProvider.removeSelectionChangedListener(this); - } - } - } - - /** - * Updates the Java outline page selection and this editor's range - * indicator. - * - * @since 3.0 - */ - private class EditorSelectionChangedListener extends - AbstractSelectionChangedListener { - - /* - * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161 - PHPEditor.this.selectionChanged(); - } - } - - /** - * "Smart" runnable for updating the outline page's selection. - */ - // class OutlinePageSelectionUpdater implements Runnable { - // - // /** Has the runnable already been posted? */ - // private boolean fPosted = false; - // - // public OutlinePageSelectionUpdater() { - // } - // - // /* - // * @see Runnable#run() - // */ - // public void run() { - // synchronizeOutlinePageSelection(); - // fPosted = false; - // } - // - // /** - // * Posts this runnable into the event queue. - // */ - // public void post() { - // if (fPosted) - // return; - // - // Shell shell = getSite().getShell(); - // if (shell != null & !shell.isDisposed()) { - // fPosted = true; - // shell.getDisplay().asyncExec(this); - // } - // } - // }; - class SelectionChangedListener implements ISelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - doSelectionChanged(event); - } - }; - - /** - * Adapts an options {@link java.util.Map}to - * {@link org.eclipse.jface.preference.IPreferenceStore}. - *

- * This preference store is read-only i.e. write access throws an - * {@link java.lang.UnsupportedOperationException}. - *

- * - * @since 3.0 - */ - private static class OptionsAdapter implements IPreferenceStore { - - /** - * A property change event filter. - */ - public interface IPropertyChangeEventFilter { - - /** - * Should the given event be filtered? - * - * @param event - * The property change event. - * @return true iff the given event should be - * filtered. - */ - public boolean isFiltered(PropertyChangeEvent event); - - } - - /** - * Property change listener. Listens for events in the options Map and - * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}on this - * adapter with arguments from the received event. - */ - private class PropertyChangeListener implements IPropertyChangeListener { - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent event) { - if (getFilter().isFiltered(event)) - return; - - if (event.getNewValue() == null) - fOptions.remove(event.getProperty()); - else - fOptions.put(event.getProperty(), event.getNewValue()); - - firePropertyChangeEvent(event.getProperty(), event - .getOldValue(), event.getNewValue()); - } - } - - /** Listeners on this adapter */ - private ListenerList fListeners = new ListenerList(); - - /** Listener on the adapted options Map */ - private IPropertyChangeListener fListener = new PropertyChangeListener(); - - /** Adapted options Map */ - private Map fOptions; - - /** Preference store through which events are received. */ - private IPreferenceStore fMockupPreferenceStore; - - /** Property event filter. */ - private IPropertyChangeEventFilter fFilter; - - /** - * Initialize with the given options. - * - * @param options - * The options to wrap - * @param mockupPreferenceStore - * the mock-up preference store - * @param filter - * the property change filter - */ - public OptionsAdapter(Map options, - IPreferenceStore mockupPreferenceStore, - IPropertyChangeEventFilter filter) { - fMockupPreferenceStore = mockupPreferenceStore; - fOptions = options; - setFilter(filter); - } - - /** - * {@inheritDoc} - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - if (fListeners.size() == 0) - fMockupPreferenceStore.addPropertyChangeListener(fListener); - fListeners.add(listener); - } - - /** - * {@inheritDoc} - */ - public void removePropertyChangeListener( - IPropertyChangeListener listener) { - fListeners.remove(listener); - if (fListeners.size() == 0) - fMockupPreferenceStore.removePropertyChangeListener(fListener); - } - - /** - * {@inheritDoc} - */ - public boolean contains(String name) { - return fOptions.containsKey(name); - } - - /** - * {@inheritDoc} - */ - public void firePropertyChangeEvent(String name, Object oldValue, - Object newValue) { - PropertyChangeEvent event = new PropertyChangeEvent(this, name, - oldValue, newValue); - Object[] listeners = fListeners.getListeners(); - for (int i = 0; i < listeners.length; i++) - ((IPropertyChangeListener) listeners[i]).propertyChange(event); - } - - /** - * {@inheritDoc} - */ - public boolean getBoolean(String name) { - boolean value = BOOLEAN_DEFAULT_DEFAULT; - String s = (String) fOptions.get(name); - if (s != null) - value = s.equals(TRUE); - return value; - } - - /** - * {@inheritDoc} - */ - public boolean getDefaultBoolean(String name) { - return BOOLEAN_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public double getDefaultDouble(String name) { - return DOUBLE_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public float getDefaultFloat(String name) { - return FLOAT_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public int getDefaultInt(String name) { - return INT_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public long getDefaultLong(String name) { - return LONG_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public String getDefaultString(String name) { - return STRING_DEFAULT_DEFAULT; - } - - /** - * {@inheritDoc} - */ - public double getDouble(String name) { - double value = DOUBLE_DEFAULT_DEFAULT; - String s = (String) fOptions.get(name); - if (s != null) { - try { - value = new Double(s).doubleValue(); - } catch (NumberFormatException e) { - } - } - return value; - } - - /** - * {@inheritDoc} - */ - public float getFloat(String name) { - float value = FLOAT_DEFAULT_DEFAULT; - String s = (String) fOptions.get(name); - if (s != null) { - try { - value = new Float(s).floatValue(); - } catch (NumberFormatException e) { - } - } - return value; - } - - /** - * {@inheritDoc} - */ - public int getInt(String name) { - int value = INT_DEFAULT_DEFAULT; - String s = (String) fOptions.get(name); - if (s != null) { - try { - value = new Integer(s).intValue(); - } catch (NumberFormatException e) { - } - } - return value; - } - - /** - * {@inheritDoc} - */ - public long getLong(String name) { - long value = LONG_DEFAULT_DEFAULT; - String s = (String) fOptions.get(name); - if (s != null) { - try { - value = new Long(s).longValue(); - } catch (NumberFormatException e) { - } - } - return value; - } - - /** - * {@inheritDoc} - */ - public String getString(String name) { - String value = (String) fOptions.get(name); - if (value == null) - value = STRING_DEFAULT_DEFAULT; - return value; - } - - /** - * {@inheritDoc} - */ - public boolean isDefault(String name) { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean needsSaving() { - return !fOptions.isEmpty(); - } - - /** - * {@inheritDoc} - */ - public void putValue(String name, String value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, double value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, float value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, int value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, long value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, String defaultObject) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setDefault(String name, boolean value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setToDefault(String name) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, double value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, float value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, int value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, long value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, String value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setValue(String name, boolean value) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the adapted options Map. - * - * @return Returns the adapted options Map. - */ - public Map getOptions() { - return fOptions; - } - - /** - * Returns the mock-up preference store, events are received through - * this preference store. - * - * @return Returns the mock-up preference store. - */ - public IPreferenceStore getMockupPreferenceStore() { - return fMockupPreferenceStore; - } - - /** - * Set the event filter to the given filter. - * - * @param filter - * The new filter. - */ - public void setFilter(IPropertyChangeEventFilter filter) { - fFilter = filter; - } - - /** - * Returns the event filter. - * - * @return The event filter. - */ - public IPropertyChangeEventFilter getFilter() { - return fFilter; - } - } - - /* - * Link mode. - */ - // class MouseClickListener implements KeyListener, MouseListener, - // MouseMoveListener, FocusListener, PaintListener, - // IPropertyChangeListener, IDocumentListener, ITextInputListener { - // - // /** The session is active. */ - // private boolean fActive; - // - // /** The currently active style range. */ - // private IRegion fActiveRegion; - // - // /** The currently active style range as position. */ - // private Position fRememberedPosition; - // - // /** The hand cursor. */ - // private Cursor fCursor; - // - // /** The link color. */ - // private Color fColor; - // - // /** The key modifier mask. */ - // private int fKeyModifierMask; - // - // public void deactivate() { - // deactivate(false); - // } - // - // public void deactivate(boolean redrawAll) { - // if (!fActive) - // return; - // - // repairRepresentation(redrawAll); - // fActive = false; - // } - // - // public void install() { - // - // ISourceViewer sourceViewer = getSourceViewer(); - // if (sourceViewer == null) - // return; - // - // StyledText text = sourceViewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // - // updateColor(sourceViewer); - // - // sourceViewer.addTextInputListener(this); - // - // IDocument document = sourceViewer.getDocument(); - // if (document != null) - // document.addDocumentListener(this); - // - // text.addKeyListener(this); - // text.addMouseListener(this); - // text.addMouseMoveListener(this); - // text.addFocusListener(this); - // text.addPaintListener(this); - // - // updateKeyModifierMask(); - // - // IPreferenceStore preferenceStore = getPreferenceStore(); - // preferenceStore.addPropertyChangeListener(this); - // } - // - // private void updateKeyModifierMask() { - // String modifiers = - // getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); - // fKeyModifierMask = computeStateMask(modifiers); - // if (fKeyModifierMask == -1) { - // // Fallback to stored state mask - // fKeyModifierMask = - // getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); - // } - // ; - // } - // - // private int computeStateMask(String modifiers) { - // if (modifiers == null) - // return -1; - // - // if (modifiers.length() == 0) - // return SWT.NONE; - // - // int stateMask = 0; - // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, - // ",;.:+-* - // "); //$NON-NLS-1$ - // while (modifierTokenizer.hasMoreTokens()) { - // int modifier = - // EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); - // if (modifier == 0 || (stateMask & modifier) == modifier) - // return -1; - // stateMask = stateMask | modifier; - // } - // return stateMask; - // } - // - // public void uninstall() { - // - // if (fColor != null) { - // fColor.dispose(); - // fColor = null; - // } - // - // if (fCursor != null) { - // fCursor.dispose(); - // fCursor = null; - // } - // - // ISourceViewer sourceViewer = getSourceViewer(); - // if (sourceViewer == null) - // return; - // - // sourceViewer.removeTextInputListener(this); - // - // IDocument document = sourceViewer.getDocument(); - // if (document != null) - // document.removeDocumentListener(this); - // - // IPreferenceStore preferenceStore = getPreferenceStore(); - // if (preferenceStore != null) - // preferenceStore.removePropertyChangeListener(this); - // - // StyledText text = sourceViewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // - // text.removeKeyListener(this); - // text.removeMouseListener(this); - // text.removeMouseMoveListener(this); - // text.removeFocusListener(this); - // text.removePaintListener(this); - // } - // - // /* - // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - // */ - // public void propertyChange(PropertyChangeEvent event) { - // if (event.getProperty().equals(PHPEditor.LINK_COLOR)) { - // ISourceViewer viewer = getSourceViewer(); - // if (viewer != null) - // updateColor(viewer); - // } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { - // updateKeyModifierMask(); - // } - // } - // - // private void updateColor(ISourceViewer viewer) { - // if (fColor != null) - // fColor.dispose(); - // - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // - // Display display = text.getDisplay(); - // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, - // display); - // } - // - // /** - // * Creates a color from the information stored in the given preference - // store. Returns null if there is no such - // * information available. - // */ - // private Color createColor(IPreferenceStore store, String key, Display - // display) { - // - // RGB rgb = null; - // - // if (store.contains(key)) { - // - // if (store.isDefault(key)) - // rgb = PreferenceConverter.getDefaultColor(store, key); - // else - // rgb = PreferenceConverter.getColor(store, key); - // - // if (rgb != null) - // return new Color(display, rgb); - // } - // - // return null; - // } - // - // private void repairRepresentation() { - // repairRepresentation(false); - // } - // - // private void repairRepresentation(boolean redrawAll) { - // - // if (fActiveRegion == null) - // return; - // - // ISourceViewer viewer = getSourceViewer(); - // if (viewer != null) { - // resetCursor(viewer); - // - // int offset = fActiveRegion.getOffset(); - // int length = fActiveRegion.getLength(); - // - // // remove style - // if (!redrawAll && viewer instanceof ITextViewerExtension2) - // ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, - // length); - // else - // viewer.invalidateTextPresentation(); - // - // // remove underline - // if (viewer instanceof ITextViewerExtension3) { - // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; - // offset = extension.modelOffset2WidgetOffset(offset); - // } else { - // offset -= viewer.getVisibleRegion().getOffset(); - // } - // - // StyledText text = viewer.getTextWidget(); - // try { - // text.redrawRange(offset, length, true); - // } catch (IllegalArgumentException x) { - // PHPeclipsePlugin.log(x); - // } - // } - // - // fActiveRegion = null; - // } - // - // // will eventually be replaced by a method provided by jdt.core - // private IRegion selectWord(IDocument document, int anchor) { - // - // try { - // int offset = anchor; - // char c; - // - // while (offset >= 0) { - // c = document.getChar(offset); - // if (!Scanner.isPHPIdentifierPart(c)) - // break; - // --offset; - // } - // - // int start = offset; - // - // offset = anchor; - // int length = document.getLength(); - // - // while (offset < length) { - // c = document.getChar(offset); - // if (!Scanner.isPHPIdentifierPart(c)) - // break; - // ++offset; - // } - // - // int end = offset; - // - // if (start == end) - // return new Region(start, 0); - // else - // return new Region(start + 1, end - start - 1); - // - // } catch (BadLocationException x) { - // return null; - // } - // } - // - // IRegion getCurrentTextRegion(ISourceViewer viewer) { - // - // int offset = getCurrentTextOffset(viewer); - // if (offset == -1) - // return null; - // - // return null; - // // IJavaElement input= SelectionConverter.getInput(PHPEditor.this); - // // if (input == null) - // // return null; - // // - // // try { - // // - // // IJavaElement[] elements= null; - // // synchronized (input) { - // // elements= ((ICodeAssist) input).codeSelect(offset, 0); - // // } - // // - // // if (elements == null || elements.length == 0) - // // return null; - // // - // // return selectWord(viewer.getDocument(), offset); - // // - // // } catch (JavaModelException e) { - // // return null; - // // } - // } - // - // private int getCurrentTextOffset(ISourceViewer viewer) { - // - // try { - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return -1; - // - // Display display = text.getDisplay(); - // Point absolutePosition = display.getCursorLocation(); - // Point relativePosition = text.toControl(absolutePosition); - // - // int widgetOffset = text.getOffsetAtLocation(relativePosition); - // if (viewer instanceof ITextViewerExtension3) { - // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; - // return extension.widgetOffset2ModelOffset(widgetOffset); - // } else { - // return widgetOffset + viewer.getVisibleRegion().getOffset(); - // } - // - // } catch (IllegalArgumentException e) { - // return -1; - // } - // } - // - // private void highlightRegion(ISourceViewer viewer, IRegion region) { - // - // if (region.equals(fActiveRegion)) - // return; - // - // repairRepresentation(); - // - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // - // // highlight region - // int offset = 0; - // int length = 0; - // - // if (viewer instanceof ITextViewerExtension3) { - // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; - // IRegion widgetRange = extension.modelRange2WidgetRange(region); - // if (widgetRange == null) - // return; - // - // offset = widgetRange.getOffset(); - // length = widgetRange.getLength(); - // - // } else { - // offset = region.getOffset() - viewer.getVisibleRegion().getOffset(); - // length = region.getLength(); - // } - // - // StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset); - // Color foregroundColor = fColor; - // Color backgroundColor = oldStyleRange == null ? text.getBackground() : - // oldStyleRange.background; - // StyleRange styleRange = new StyleRange(offset, length, foregroundColor, - // backgroundColor); - // text.setStyleRange(styleRange); - // - // // underline - // text.redrawRange(offset, length, true); - // - // fActiveRegion = region; - // } - // - // private void activateCursor(ISourceViewer viewer) { - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // Display display = text.getDisplay(); - // if (fCursor == null) - // fCursor = new Cursor(display, SWT.CURSOR_HAND); - // text.setCursor(fCursor); - // } - // - // private void resetCursor(ISourceViewer viewer) { - // StyledText text = viewer.getTextWidget(); - // if (text != null && !text.isDisposed()) - // text.setCursor(null); - // - // if (fCursor != null) { - // fCursor.dispose(); - // fCursor = null; - // } - // } - // - // /* - // * @see - // org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) - // */ - // public void keyPressed(KeyEvent event) { - // - // if (fActive) { - // deactivate(); - // return; - // } - // - // if (event.keyCode != fKeyModifierMask) { - // deactivate(); - // return; - // } - // - // fActive = true; - // - // // removed for #25871 - // // - // // ISourceViewer viewer= getSourceViewer(); - // // if (viewer == null) - // // return; - // // - // // IRegion region= getCurrentTextRegion(viewer); - // // if (region == null) - // // return; - // // - // // highlightRegion(viewer, region); - // // activateCursor(viewer); - // } - // - // /* - // * @see - // org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) - // */ - // public void keyReleased(KeyEvent event) { - // - // if (!fActive) - // return; - // - // deactivate(); - // } - // - // /* - // * @see - // org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) - // */ - // public void mouseDoubleClick(MouseEvent e) { - // } - // - // /* - // * @see - // org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) - // */ - // public void mouseDown(MouseEvent event) { - // - // if (!fActive) - // return; - // - // if (event.stateMask != fKeyModifierMask) { - // deactivate(); - // return; - // } - // - // if (event.button != 1) { - // deactivate(); - // return; - // } - // } - // - // /* - // * @see - // org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) - // */ - // public void mouseUp(MouseEvent e) { - // - // if (!fActive) - // return; - // - // if (e.button != 1) { - // deactivate(); - // return; - // } - // - // boolean wasActive = fCursor != null; - // - // deactivate(); - // - // if (wasActive) { - // IAction action = getAction("OpenEditor"); //$NON-NLS-1$ - // if (action != null) - // action.run(); - // } - // } - // - // /* - // * @see - // org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) - // */ - // public void mouseMove(MouseEvent event) { - // - // if (event.widget instanceof Control && !((Control) - // event.widget).isFocusControl()) { - // deactivate(); - // return; - // } - // - // if (!fActive) { - // if (event.stateMask != fKeyModifierMask) - // return; - // // modifier was already pressed - // fActive = true; - // } - // - // ISourceViewer viewer = getSourceViewer(); - // if (viewer == null) { - // deactivate(); - // return; - // } - // - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) { - // deactivate(); - // return; - // } - // - // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != - // 0) - // { - // deactivate(); - // return; - // } - // - // IRegion region = getCurrentTextRegion(viewer); - // if (region == null || region.getLength() == 0) { - // repairRepresentation(); - // return; - // } - // - // highlightRegion(viewer, region); - // activateCursor(viewer); - // } - // - // /* - // * @see - // org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) - // */ - // public void focusGained(FocusEvent e) { - // } - // - // /* - // * @see - // org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) - // */ - // public void focusLost(FocusEvent event) { - // deactivate(); - // } - // - // /* - // * @see - // org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - // */ - // public void documentAboutToBeChanged(DocumentEvent event) { - // if (fActive && fActiveRegion != null) { - // fRememberedPosition = new Position(fActiveRegion.getOffset(), - // fActiveRegion.getLength()); - // try { - // event.getDocument().addPosition(fRememberedPosition); - // } catch (BadLocationException x) { - // fRememberedPosition = null; - // } - // } - // } - // - // /* - // * @see - // org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - // */ - // public void documentChanged(DocumentEvent event) { - // if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) { - // event.getDocument().removePosition(fRememberedPosition); - // fActiveRegion = new Region(fRememberedPosition.getOffset(), - // fRememberedPosition.getLength()); - // } - // fRememberedPosition = null; - // - // ISourceViewer viewer = getSourceViewer(); - // if (viewer != null) { - // StyledText widget = viewer.getTextWidget(); - // if (widget != null && !widget.isDisposed()) { - // widget.getDisplay().asyncExec(new Runnable() { - // public void run() { - // deactivate(); - // } - // }); - // } - // } - // } - // - // /* - // * @see - // org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, - // * org.eclipse.jface.text.IDocument) - // */ - // public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument - // newInput) { - // if (oldInput == null) - // return; - // deactivate(); - // oldInput.removeDocumentListener(this); - // } - // - // /* - // * @see - // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, - // * org.eclipse.jface.text.IDocument) - // */ - // public void inputDocumentChanged(IDocument oldInput, IDocument newInput) - // { - // if (newInput == null) - // return; - // newInput.addDocumentListener(this); - // } - // - // /* - // * @see PaintListener#paintControl(PaintEvent) - // */ - // public void paintControl(PaintEvent event) { - // if (fActiveRegion == null) - // return; - // - // ISourceViewer viewer = getSourceViewer(); - // if (viewer == null) - // return; - // - // StyledText text = viewer.getTextWidget(); - // if (text == null || text.isDisposed()) - // return; - // - // int offset = 0; - // int length = 0; - // - // if (viewer instanceof ITextViewerExtension3) { - // - // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; - // IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset, - // length)); - // if (widgetRange == null) - // return; - // - // offset = widgetRange.getOffset(); - // length = widgetRange.getLength(); - // - // } else { - // - // IRegion region = viewer.getVisibleRegion(); - // if (!includes(region, fActiveRegion)) - // return; - // - // offset = fActiveRegion.getOffset() - region.getOffset(); - // length = fActiveRegion.getLength(); - // } - // - // // support for bidi - // Point minLocation = getMinimumLocation(text, offset, length); - // Point maxLocation = getMaximumLocation(text, offset, length); - // - // int x1 = minLocation.x; - // int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; - // int y = minLocation.y + text.getLineHeight() - 1; - // - // GC gc = event.gc; - // if (fColor != null && !fColor.isDisposed()) - // gc.setForeground(fColor); - // gc.drawLine(x1, y, x2, y); - // } - // - // private boolean includes(IRegion region, IRegion position) { - // return position.getOffset() >= region.getOffset() - // && position.getOffset() + position.getLength() <= region.getOffset() + - // region.getLength(); - // } - // - // private Point getMinimumLocation(StyledText text, int offset, int length) - // { - // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); - // - // for (int i = 0; i <= length; i++) { - // Point location = text.getLocationAtOffset(offset + i); - // - // if (location.x < minLocation.x) - // minLocation.x = location.x; - // if (location.y < minLocation.y) - // minLocation.y = location.y; - // } - // - // return minLocation; - // } - // - // private Point getMaximumLocation(StyledText text, int offset, int length) - // { - // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); - // - // for (int i = 0; i <= length; i++) { - // Point location = text.getLocationAtOffset(offset + i); - // - // if (location.x > maxLocation.x) - // maxLocation.x = location.x; - // if (location.y > maxLocation.y) - // maxLocation.y = location.y; - // } - // - // return maxLocation; - // } - // }; - /* - * Link mode. - */ - class MouseClickListener implements KeyListener, MouseListener, - MouseMoveListener, FocusListener, PaintListener, - IPropertyChangeListener, IDocumentListener, ITextInputListener, - ITextPresentationListener { - - /** The session is active. */ - private boolean fActive; - - /** The currently active style range. */ - private IRegion fActiveRegion; - - /** The currently active style range as position. */ - private Position fRememberedPosition; - - /** The hand cursor. */ - private Cursor fCursor; - - /** The link color. */ - private Color fColor; - - /** The key modifier mask. */ - private int fKeyModifierMask; - - public void deactivate() { - deactivate(false); - } - - public void deactivate(boolean redrawAll) { - if (!fActive) - return; - - repairRepresentation(redrawAll); - fActive = false; - } - - public void install() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null) - return; - - StyledText text = sourceViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - updateColor(sourceViewer); - - sourceViewer.addTextInputListener(this); - - IDocument document = sourceViewer.getDocument(); - if (document != null) - document.addDocumentListener(this); - - text.addKeyListener(this); - text.addMouseListener(this); - text.addMouseMoveListener(this); - text.addFocusListener(this); - text.addPaintListener(this); - - ((ITextViewerExtension4) sourceViewer) - .addTextPresentationListener(this); - - updateKeyModifierMask(); - - IPreferenceStore preferenceStore = getPreferenceStore(); - preferenceStore.addPropertyChangeListener(this); - } - - private void updateKeyModifierMask() { - String modifiers = getPreferenceStore().getString( - BROWSER_LIKE_LINKS_KEY_MODIFIER); - fKeyModifierMask = computeStateMask(modifiers); - if (fKeyModifierMask == -1) { - // Fall back to stored state mask - fKeyModifierMask = getPreferenceStore().getInt( - BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); - } - } - - private int computeStateMask(String modifiers) { - if (modifiers == null) - return -1; - - if (modifiers.length() == 0) - return SWT.NONE; - - int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, - ",;.:+-* "); //$NON-NLS-1$ - while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility - .findLocalizedModifier(modifierTokenizer.nextToken()); - if (modifier == 0 || (stateMask & modifier) == modifier) - return -1; - stateMask = stateMask | modifier; - } - return stateMask; - } - - public void uninstall() { - - if (fColor != null) { - fColor.dispose(); - fColor = null; - } - - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) - sourceViewer.removeTextInputListener(this); - - IDocumentProvider documentProvider = getDocumentProvider(); - if (documentProvider != null) { - IDocument document = documentProvider - .getDocument(getEditorInput()); - if (document != null) - document.removeDocumentListener(this); - } - - IPreferenceStore preferenceStore = getPreferenceStore(); - if (preferenceStore != null) - preferenceStore.removePropertyChangeListener(this); - - if (sourceViewer == null) - return; - - StyledText text = sourceViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - text.removeKeyListener(this); - text.removeMouseListener(this); - text.removeMouseMoveListener(this); - text.removeFocusListener(this); - text.removePaintListener(this); - - ((ITextViewerExtension4) sourceViewer) - .removeTextPresentationListener(this); - } - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(PHPEditor.LINK_COLOR)) { - ISourceViewer viewer = getSourceViewer(); - if (viewer != null) - updateColor(viewer); - } else if (event.getProperty().equals( - BROWSER_LIKE_LINKS_KEY_MODIFIER)) { - updateKeyModifierMask(); - } - } - - private void updateColor(ISourceViewer viewer) { - if (fColor != null) - fColor.dispose(); - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - Display display = text.getDisplay(); - fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, - display); - } - - /** - * Creates a color from the information stored in the given preference - * store. - * - * @param store - * the preference store - * @param key - * the key - * @param display - * the display - * @return the color or null if there is no such - * information available - */ - private Color createColor(IPreferenceStore store, String key, - Display display) { - - RGB rgb = null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb = PreferenceConverter.getDefaultColor(store, key); - else - rgb = PreferenceConverter.getColor(store, key); - - if (rgb != null) - return new Color(display, rgb); - } - - return null; - } - - private void repairRepresentation() { - repairRepresentation(false); - } - - private void repairRepresentation(boolean redrawAll) { - - if (fActiveRegion == null) - return; - - int offset = fActiveRegion.getOffset(); - int length = fActiveRegion.getLength(); - fActiveRegion = null; - - ISourceViewer viewer = getSourceViewer(); - if (viewer != null) { - - resetCursor(viewer); - - // Invalidate ==> remove applied text presentation - if (!redrawAll && viewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) viewer) - .invalidateTextPresentation(offset, length); - else - viewer.invalidateTextPresentation(); - - // Remove underline - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - offset = extension.modelOffset2WidgetOffset(offset); - } else { - offset -= viewer.getVisibleRegion().getOffset(); - } - try { - StyledText text = viewer.getTextWidget(); - - text.redrawRange(offset, length, false); - } catch (IllegalArgumentException x) { - // JavaPlugin.log(x); - } - } - } - - // will eventually be replaced by a method provided by jdt.core - private IRegion selectWord(IDocument document, int anchor) { - - try { - int offset = anchor; - char c; - - while (offset >= 0) { - c = document.getChar(offset); - if (!Scanner.isPHPIdentifierPart(c) && c != '$') - break; - --offset; - } - - int start = offset; - - offset = anchor; - int length = document.getLength(); - - while (offset < length) { - c = document.getChar(offset); - if (!Scanner.isPHPIdentifierPart(c) && c != '$') - break; - ++offset; - } - - int end = offset; - - if (start == end) - return new Region(start, 0); - else - return new Region(start + 1, end - start - 1); - - } catch (BadLocationException x) { - return null; - } - } - - IRegion getCurrentTextRegion(ISourceViewer viewer) { - - int offset = getCurrentTextOffset(viewer); - if (offset == -1) - return null; - - IJavaElement input = SelectionConverter.getInput(PHPEditor.this); - if (input == null) - return null; - - // try { - - // IJavaElement[] elements= null; - // synchronized (input) { - // elements= ((ICodeAssist) input).codeSelect(offset, 0); - // } - // - // if (elements == null || elements.length == 0) - // return null; - - return selectWord(viewer.getDocument(), offset); - - // } catch (JavaModelException e) { - // return null; - // } - } - - private int getCurrentTextOffset(ISourceViewer viewer) { - - try { - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return -1; - - Display display = text.getDisplay(); - Point absolutePosition = display.getCursorLocation(); - Point relativePosition = text.toControl(absolutePosition); - - int widgetOffset = text.getOffsetAtLocation(relativePosition); - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - return extension.widgetOffset2ModelOffset(widgetOffset); - } else { - return widgetOffset + viewer.getVisibleRegion().getOffset(); - } - - } catch (IllegalArgumentException e) { - return -1; - } - } - - public void applyTextPresentation(TextPresentation textPresentation) { - if (fActiveRegion == null) - return; - IRegion region = textPresentation.getExtent(); - if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region - .getOffset() - && region.getOffset() + region.getLength() > fActiveRegion - .getOffset()) - textPresentation.mergeStyleRange(new StyleRange(fActiveRegion - .getOffset(), fActiveRegion.getLength(), fColor, null)); - } - - private void highlightRegion(ISourceViewer viewer, IRegion region) { - - if (region.equals(fActiveRegion)) - return; - - repairRepresentation(); - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - // Underline - int offset = 0; - int length = 0; - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - IRegion widgetRange = extension.modelRange2WidgetRange(region); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } else { - offset = region.getOffset() - - viewer.getVisibleRegion().getOffset(); - length = region.getLength(); - } - text.redrawRange(offset, length, false); - - // Invalidate region ==> apply text presentation - fActiveRegion = region; - if (viewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) viewer).invalidateTextPresentation( - region.getOffset(), region.getLength()); - else - viewer.invalidateTextPresentation(); - } - - private void activateCursor(ISourceViewer viewer) { - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - Display display = text.getDisplay(); - if (fCursor == null) - fCursor = new Cursor(display, SWT.CURSOR_HAND); - text.setCursor(fCursor); - } - - private void resetCursor(ISourceViewer viewer) { - StyledText text = viewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.setCursor(null); - - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - } - - /* - * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) - */ - public void keyPressed(KeyEvent event) { - - if (fActive) { - deactivate(); - return; - } - - if (event.keyCode != fKeyModifierMask) { - deactivate(); - return; - } - - fActive = true; - - // removed for #25871 - // - // ISourceViewer viewer= getSourceViewer(); - // if (viewer == null) - // return; - // - // IRegion region= getCurrentTextRegion(viewer); - // if (region == null) - // return; - // - // highlightRegion(viewer, region); - // activateCursor(viewer); - } - - /* - * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) - */ - public void keyReleased(KeyEvent event) { - - if (!fActive) - return; - - deactivate(); - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) - */ - public void mouseDoubleClick(MouseEvent e) { - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) - */ - public void mouseDown(MouseEvent event) { - - if (!fActive) - return; - - if (event.stateMask != fKeyModifierMask) { - deactivate(); - return; - } - - if (event.button != 1) { - deactivate(); - return; - } - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) - */ - public void mouseUp(MouseEvent e) { - - if (!fActive) - return; - - if (e.button != 1) { - deactivate(); - return; - } - - boolean wasActive = fCursor != null; - - deactivate(); - - if (wasActive) { - IAction action = getAction("OpenEditor"); //$NON-NLS-1$ - if (action != null) - action.run(); - } - } - - /* - * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) - */ - public void mouseMove(MouseEvent event) { - - if (event.widget instanceof Control - && !((Control) event.widget).isFocusControl()) { - deactivate(); - return; - } - - if (!fActive) { - if (event.stateMask != fKeyModifierMask) - return; - // modifier was already pressed - fActive = true; - } - - ISourceViewer viewer = getSourceViewer(); - if (viewer == null) { - deactivate(); - return; - } - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) { - deactivate(); - return; - } - - if ((event.stateMask & SWT.BUTTON1) != 0 - && text.getSelectionCount() != 0) { - deactivate(); - return; - } - - IRegion region = getCurrentTextRegion(viewer); - if (region == null || region.getLength() == 0) { - repairRepresentation(); - return; - } - - highlightRegion(viewer, region); - activateCursor(viewer); - } - - /* - * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) - */ - public void focusGained(FocusEvent e) { - } - - /* - * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) - */ - public void focusLost(FocusEvent event) { - deactivate(); - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - if (fActive && fActiveRegion != null) { - fRememberedPosition = new Position(fActiveRegion.getOffset(), - fActiveRegion.getLength()); - try { - event.getDocument().addPosition(fRememberedPosition); - } catch (BadLocationException x) { - fRememberedPosition = null; - } - } - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - if (fRememberedPosition != null) { - if (!fRememberedPosition.isDeleted()) { - - event.getDocument().removePosition(fRememberedPosition); - fActiveRegion = new Region(fRememberedPosition.getOffset(), - fRememberedPosition.getLength()); - fRememberedPosition = null; - - ISourceViewer viewer = getSourceViewer(); - if (viewer != null) { - StyledText widget = viewer.getTextWidget(); - if (widget != null && !widget.isDisposed()) { - widget.getDisplay().asyncExec(new Runnable() { - public void run() { - deactivate(); - } - }); - } - } - - } else { - fActiveRegion = null; - fRememberedPosition = null; - deactivate(); - } - } - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, - IDocument newInput) { - if (oldInput == null) - return; - deactivate(); - oldInput.removeDocumentListener(this); - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.IDocument) - */ - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - if (newInput == null) - return; - newInput.addDocumentListener(this); - } - - /* - * @see PaintListener#paintControl(PaintEvent) - */ - public void paintControl(PaintEvent event) { - if (fActiveRegion == null) - return; - - ISourceViewer viewer = getSourceViewer(); - if (viewer == null) - return; - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - int offset = 0; - int length = 0; - - if (viewer instanceof ITextViewerExtension5) { - - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - IRegion widgetRange = extension - .modelRange2WidgetRange(fActiveRegion); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } else { - - IRegion region = viewer.getVisibleRegion(); - if (!includes(region, fActiveRegion)) - return; - - offset = fActiveRegion.getOffset() - region.getOffset(); - length = fActiveRegion.getLength(); - } - - // support for bidi - Point minLocation = getMinimumLocation(text, offset, length); - Point maxLocation = getMaximumLocation(text, offset, length); - - int x1 = minLocation.x; - int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; - int y = minLocation.y + text.getLineHeight() - 1; - - GC gc = event.gc; - if (fColor != null && !fColor.isDisposed()) - gc.setForeground(fColor); - gc.drawLine(x1, y, x2, y); - } - - private boolean includes(IRegion region, IRegion position) { - return position.getOffset() >= region.getOffset() - && position.getOffset() + position.getLength() <= region - .getOffset() - + region.getLength(); - } - - private Point getMinimumLocation(StyledText text, int offset, int length) { - Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x < minLocation.x) - minLocation.x = location.x; - if (location.y < minLocation.y) - minLocation.y = location.y; - } - - return minLocation; - } - - private Point getMaximumLocation(StyledText text, int offset, int length) { - Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x > maxLocation.x) - maxLocation.x = location.x; - if (location.y > maxLocation.y) - maxLocation.y = location.y; - } - - return maxLocation; - } - } - - /** - * This action dispatches into two behaviours: If there is no current text - * hover, the javadoc is displayed using information presenter. If there is - * a current text hover, it is converted into a information presenter in - * order to make it sticky. - */ - class InformationDispatchAction extends TextEditorAction { - - /** The wrapped text operation action. */ - private final TextOperationAction fTextOperationAction; - - /** - * Creates a dispatch action. - */ - public InformationDispatchAction(ResourceBundle resourceBundle, - String prefix, final TextOperationAction textOperationAction) { - super(resourceBundle, prefix, PHPEditor.this); - if (textOperationAction == null) - throw new IllegalArgumentException(); - fTextOperationAction = textOperationAction; - } - - /* - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null) { - fTextOperationAction.run(); - return; - } - - if (!(sourceViewer instanceof ITextViewerExtension2)) { - fTextOperationAction.run(); - return; - } - - ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer; - - // does a text hover exist? - ITextHover textHover = textViewerExtension2.getCurrentTextHover(); - if (textHover == null) { - fTextOperationAction.run(); - return; - } - - Point hoverEventLocation = textViewerExtension2 - .getHoverEventLocation(); - int offset = computeOffsetAtLocation(sourceViewer, - hoverEventLocation.x, hoverEventLocation.y); - if (offset == -1) { - fTextOperationAction.run(); - return; - } - - try { - // get the text hover content - IDocument document = sourceViewer.getDocument(); - String contentType = document.getContentType(offset); - - final IRegion hoverRegion = textHover.getHoverRegion( - sourceViewer, offset); - if (hoverRegion == null) - return; - - final String hoverInfo = textHover.getHoverInfo(sourceViewer, - hoverRegion); - - // with information provider - IInformationProvider informationProvider = new IInformationProvider() { - /* - * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IRegion getSubject(ITextViewer textViewer, int offset) { - return hoverRegion; - } - - /* - * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, - * org.eclipse.jface.text.IRegion) - */ - public String getInformation(ITextViewer textViewer, - IRegion subject) { - return hoverInfo; - } - }; - - fInformationPresenter.setOffset(offset); - fInformationPresenter.setInformationProvider( - informationProvider, contentType); - fInformationPresenter.showInformation(); - - } catch (BadLocationException e) { - } - } - - // modified version from TextViewer - private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { - - StyledText styledText = textViewer.getTextWidget(); - IDocument document = textViewer.getDocument(); - - if (document == null) - return -1; - - try { - int widgetLocation = styledText.getOffsetAtLocation(new Point( - x, y)); - if (textViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer; - return extension.widgetOffset2ModelOffset(widgetLocation); - } else { - IRegion visibleRegion = textViewer.getVisibleRegion(); - return widgetLocation + visibleRegion.getOffset(); - } - } catch (IllegalArgumentException e) { - return -1; - } - - } - }; - - /** - * This action implements smart home. - * - * Instead of going to the start of a line it does the following: - if smart - * home/end is enabled and the caret is after the line's first - * non-whitespace then the caret is moved directly before it, taking JavaDoc - * and multi-line comments into account. - if the caret is before the line's - * first non-whitespace the caret is moved to the beginning of the line - if - * the caret is at the beginning of the line see first case. - * - * @since 3.0 - */ - protected class SmartLineStartAction extends LineStartAction { - - /** - * Creates a new smart line start action - * - * @param textWidget - * the styled text widget - * @param doSelect - * a boolean flag which tells if the text up to the beginning - * of the line should be selected - */ - public SmartLineStartAction(final StyledText textWidget, - final boolean doSelect) { - super(textWidget, doSelect); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, - * int, java.lang.String) - */ - protected int getLineStartPosition(final IDocument document, - final String line, final int length, final int offset) { - - String type = IDocument.DEFAULT_CONTENT_TYPE; - try { - type = TextUtilities.getContentType(document, - IPHPPartitions.PHP_PARTITIONING, offset, true); - } catch (BadLocationException exception) { - // Should not happen - } - - int index = super.getLineStartPosition(document, line, length, - offset); - if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) - || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { - if (index < length - 1 && line.charAt(index) == '*' - && line.charAt(index + 1) != '/') { - do { - ++index; - } while (index < length - && Character.isWhitespace(line.charAt(index))); - } - } else { - if (index < length - 1 && line.charAt(index) == '/' - && line.charAt(index + 1) == '/') { - index++; - do { - ++index; - } while (index < length - && Character.isWhitespace(line.charAt(index))); - } - } - return index; - } - } - - /** - * Text navigation action to navigate to the next sub-word. - * - * @since 3.0 - */ - protected abstract class NextSubWordAction extends TextNavigationAction { - - protected JavaWordIterator fIterator = new JavaWordIterator(); - - /** - * Creates a new next sub-word action. - * - * @param code - * Action code for the default operation. Must be an action - * code from - * @see org.eclipse.swt.custom.ST. - */ - protected NextSubWordAction(int code) { - super(getSourceViewer().getTextWidget(), code); - } - - /* - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - // Check whether we are in a java code partition and the preference - // is - // enabled - final IPreferenceStore store = getPreferenceStore(); - if (!store - .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { - super.run(); - return; - } - - final ISourceViewer viewer = getSourceViewer(); - final IDocument document = viewer.getDocument(); - fIterator - .setText((CharacterIterator) new DocumentCharacterIterator( - document)); - int position = widgetOffset2ModelOffset(viewer, viewer - .getTextWidget().getCaretOffset()); - if (position == -1) - return; - - int next = findNextPosition(position); - if (next != BreakIterator.DONE) { - setCaretPosition(next); - getTextWidget().showSelection(); - fireSelectionChanged(); - } - - } - - /** - * Finds the next position after the given position. - * - * @param position - * the current position - * @return the next position - */ - protected int findNextPosition(int position) { - ISourceViewer viewer = getSourceViewer(); - int widget = -1; - while (position != BreakIterator.DONE && widget == -1) { // TODO: - // optimize - position = fIterator.following(position); - if (position != BreakIterator.DONE) - widget = modelOffset2WidgetOffset(viewer, position); - } - return position; - } - - /** - * Sets the caret position to the sub-word boundary given with - * position. - * - * @param position - * Position where the action should move the caret - */ - protected abstract void setCaretPosition(int position); - } - - /** - * Text navigation action to navigate to the next sub-word. - * - * @since 3.0 - */ - protected class NavigateNextSubWordAction extends NextSubWordAction { - - /** - * Creates a new navigate next sub-word action. - */ - public NavigateNextSubWordAction() { - super(ST.WORD_NEXT); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - getTextWidget().setCaretOffset( - modelOffset2WidgetOffset(getSourceViewer(), position)); - } - } - - /** - * Text operation action to delete the next sub-word. - * - * @since 3.0 - */ - protected class DeleteNextSubWordAction extends NextSubWordAction implements - IUpdate { - - /** - * Creates a new delete next sub-word action. - */ - public DeleteNextSubWordAction() { - super(ST.DELETE_WORD_NEXT); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - if (!validateEditorInputState()) - return; - - final ISourceViewer viewer = getSourceViewer(); - final int caret = widgetOffset2ModelOffset(viewer, viewer - .getTextWidget().getCaretOffset()); - - try { - viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ - } catch (BadLocationException exception) { - // Should not happen - } - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int) - */ - protected int findNextPosition(int position) { - return fIterator.following(position); - } - - /* - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - setEnabled(isEditorInputModifiable()); - } - } - - /** - * Text operation action to select the next sub-word. - * - * @since 3.0 - */ - protected class SelectNextSubWordAction extends NextSubWordAction { - - /** - * Creates a new select next sub-word action. - */ - public SelectNextSubWordAction() { - super(ST.SELECT_WORD_NEXT); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - final ISourceViewer viewer = getSourceViewer(); - - final StyledText text = viewer.getTextWidget(); - if (text != null && !text.isDisposed()) { - - final Point selection = text.getSelection(); - final int caret = text.getCaretOffset(); - final int offset = modelOffset2WidgetOffset(viewer, position); - - if (caret == selection.x) - text.setSelectionRange(selection.y, offset - selection.y); - else - text.setSelectionRange(selection.x, offset - selection.x); - } - } - } - - /** - * Text navigation action to navigate to the previous sub-word. - * - * @since 3.0 - */ - protected abstract class PreviousSubWordAction extends TextNavigationAction { - - protected JavaWordIterator fIterator = new JavaWordIterator(); - - /** - * Creates a new previous sub-word action. - * - * @param code - * Action code for the default operation. Must be an action - * code from - * @see org.eclipse.swt.custom.ST. - */ - protected PreviousSubWordAction(final int code) { - super(getSourceViewer().getTextWidget(), code); - } - - /* - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - // Check whether we are in a java code partition and the preference - // is - // enabled - final IPreferenceStore store = getPreferenceStore(); - if (!store - .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { - super.run(); - return; - } - - final ISourceViewer viewer = getSourceViewer(); - final IDocument document = viewer.getDocument(); - fIterator - .setText((CharacterIterator) new DocumentCharacterIterator( - document)); - int position = widgetOffset2ModelOffset(viewer, viewer - .getTextWidget().getCaretOffset()); - if (position == -1) - return; - - int previous = findPreviousPosition(position); - if (previous != BreakIterator.DONE) { - setCaretPosition(previous); - getTextWidget().showSelection(); - fireSelectionChanged(); - } - - } - - /** - * Finds the previous position before the given position. - * - * @param position - * the current position - * @return the previous position - */ - protected int findPreviousPosition(int position) { - ISourceViewer viewer = getSourceViewer(); - int widget = -1; - while (position != BreakIterator.DONE && widget == -1) { // TODO: - // optimize - position = fIterator.preceding(position); - if (position != BreakIterator.DONE) - widget = modelOffset2WidgetOffset(viewer, position); - } - return position; - } - - /** - * Sets the caret position to the sub-word boundary given with - * position. - * - * @param position - * Position where the action should move the caret - */ - protected abstract void setCaretPosition(int position); - } - - /** - * Text navigation action to navigate to the previous sub-word. - * - * @since 3.0 - */ - protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { - - /** - * Creates a new navigate previous sub-word action. - */ - public NavigatePreviousSubWordAction() { - super(ST.WORD_PREVIOUS); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - getTextWidget().setCaretOffset( - modelOffset2WidgetOffset(getSourceViewer(), position)); - } - } - - /** - * Text operation action to delete the previous sub-word. - * - * @since 3.0 - */ - protected class DeletePreviousSubWordAction extends PreviousSubWordAction - implements IUpdate { - - /** - * Creates a new delete previous sub-word action. - */ - public DeletePreviousSubWordAction() { - super(ST.DELETE_WORD_PREVIOUS); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - if (!validateEditorInputState()) - return; - - final ISourceViewer viewer = getSourceViewer(); - final int caret = widgetOffset2ModelOffset(viewer, viewer - .getTextWidget().getCaretOffset()); - - try { - viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ - } catch (BadLocationException exception) { - // Should not happen - } - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int) - */ - protected int findPreviousPosition(int position) { - return fIterator.preceding(position); - } - - /* - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - setEnabled(isEditorInputModifiable()); - } - } - - /** - * Text operation action to select the previous sub-word. - * - * @since 3.0 - */ - protected class SelectPreviousSubWordAction extends PreviousSubWordAction { - - /** - * Creates a new select previous sub-word action. - */ - public SelectPreviousSubWordAction() { - super(ST.SELECT_WORD_PREVIOUS); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) - */ - protected void setCaretPosition(final int position) { - final ISourceViewer viewer = getSourceViewer(); - - final StyledText text = viewer.getTextWidget(); - if (text != null && !text.isDisposed()) { - - final Point selection = text.getSelection(); - final int caret = text.getCaretOffset(); - final int offset = modelOffset2WidgetOffset(viewer, position); - - if (caret == selection.x) - text.setSelectionRange(selection.y, offset - selection.y); - else - text.setSelectionRange(selection.x, offset - selection.x); - } - } - } - - // static protected class AnnotationAccess implements IAnnotationAccess { - // /* - // * @see - // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation) - // */ - // public Object getType(Annotation annotation) { - // if (annotation instanceof IJavaAnnotation) { - // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; - // // if (javaAnnotation.isRelevant()) - // // return javaAnnotation.getAnnotationType(); - // } - // return null; - // } - // - // /* - // * @see - // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation) - // */ - // public boolean isMultiLine(Annotation annotation) { - // return true; - // } - // - // /* - // * @see - // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation) - // */ - // public boolean isTemporary(Annotation annotation) { - // if (annotation instanceof IJavaAnnotation) { - // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; - // if (javaAnnotation.isRelevant()) - // return javaAnnotation.isTemporary(); - // } - // return false; - // } - // }; - - private class PropertyChangeListener implements - org.eclipse.core.runtime.Preferences.IPropertyChangeListener { - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange( - org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { - handlePreferencePropertyChanged(event); - } - }; - - /** - * Finds and marks occurrence annotations. - * - * @since 3.0 - */ - class OccurrencesFinderJob extends Job { - - private IDocument fDocument; - - private ISelection fSelection; - - private ISelectionValidator fPostSelectionValidator; - - private boolean fCanceled = false; - - private IProgressMonitor fProgressMonitor; - - private Position[] fPositions; - - public OccurrencesFinderJob(IDocument document, Position[] positions, - ISelection selection) { - super(PHPEditorMessages.JavaEditor_markOccurrences_job_name); - fDocument = document; - fSelection = selection; - fPositions = positions; - - if (getSelectionProvider() instanceof ISelectionValidator) - fPostSelectionValidator = (ISelectionValidator) getSelectionProvider(); - } - - // cannot use cancel() because it is declared final - void doCancel() { - fCanceled = true; - cancel(); - } - - private boolean isCanceled() { - return fCanceled - || fProgressMonitor.isCanceled() - || fPostSelectionValidator != null - && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection) - || LinkedModeModel.hasInstalledModel(fDocument); - } - - /* - * @see Job#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor progressMonitor) { - - fProgressMonitor = progressMonitor; - - if (isCanceled()) - return Status.CANCEL_STATUS; - - ITextViewer textViewer = getViewer(); - if (textViewer == null) - return Status.CANCEL_STATUS; - - IDocument document = textViewer.getDocument(); - if (document == null) - return Status.CANCEL_STATUS; - - IDocumentProvider documentProvider = getDocumentProvider(); - if (documentProvider == null) - return Status.CANCEL_STATUS; - - IAnnotationModel annotationModel = documentProvider - .getAnnotationModel(getEditorInput()); - if (annotationModel == null) - return Status.CANCEL_STATUS; - - // Add occurrence annotations - int length = fPositions.length; - Map annotationMap = new HashMap(length); - for (int i = 0; i < length; i++) { - - if (isCanceled()) - return Status.CANCEL_STATUS; - - String message; - Position position = fPositions[i]; - - // Create & add annotation - try { - message = document.get(position.offset, position.length); - } catch (BadLocationException ex) { - // Skip this match - continue; - } - annotationMap - .put( - new Annotation( - "net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ - position); - } - - if (isCanceled()) - return Status.CANCEL_STATUS; - - synchronized (getLockObject(annotationModel)) { - if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension) annotationModel) - .replaceAnnotations(fOccurrenceAnnotations, - annotationMap); - } else { - removeOccurrenceAnnotations(); - Iterator iter = annotationMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry mapEntry = (Map.Entry) iter.next(); - annotationModel.addAnnotation((Annotation) mapEntry - .getKey(), (Position) mapEntry.getValue()); - } - } - fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet() - .toArray(new Annotation[annotationMap.keySet().size()]); - } - - return Status.OK_STATUS; - } - } - - /** - * Cancels the occurrences finder job upon document changes. - * - * @since 3.0 - */ - class OccurrencesFinderJobCanceler implements IDocumentListener, - ITextInputListener { - - public void install() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null) - return; - - StyledText text = sourceViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - sourceViewer.addTextInputListener(this); - - IDocument document = sourceViewer.getDocument(); - if (document != null) - document.addDocumentListener(this); - } - - public void uninstall() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) - sourceViewer.removeTextInputListener(this); - - IDocumentProvider documentProvider = getDocumentProvider(); - if (documentProvider != null) { - IDocument document = documentProvider - .getDocument(getEditorInput()); - if (document != null) - document.removeDocumentListener(this); - } - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - if (fOccurrencesFinderJob != null) - fOccurrencesFinderJob.doCancel(); - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, - IDocument newInput) { - if (oldInput == null) - return; - - oldInput.removeDocumentListener(this); - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.IDocument) - */ - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - if (newInput == null) - return; - newInput.addDocumentListener(this); - } - } - - /** - * Internal activation listener. - * - * @since 3.0 - */ - private class ActivationListener implements IWindowListener { - - /* - * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow) - * @since 3.1 - */ - public void windowActivated(IWorkbenchWindow window) { - if (window == getEditorSite().getWorkbenchWindow() - && fMarkOccurrenceAnnotations && isActivePart()) { - fForcedMarkOccurrencesSelection = getSelectionProvider() - .getSelection(); - SelectionListenerWithASTManager - .getDefault() - .forceSelectionChange( - PHPEditor.this, - (ITextSelection) fForcedMarkOccurrencesSelection); - } - } - - /* - * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow) - * @since 3.1 - */ - public void windowDeactivated(IWorkbenchWindow window) { - if (window == getEditorSite().getWorkbenchWindow() - && fMarkOccurrenceAnnotations && isActivePart()) - removeOccurrenceAnnotations(); - } - - /* - * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow) - * @since 3.1 - */ - public void windowClosed(IWorkbenchWindow window) { - } - - /* - * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow) - * @since 3.1 - */ - public void windowOpened(IWorkbenchWindow window) { - } - } - - /** - * Updates the selection in the editor's widget with the selection of the - * outline page. - */ - class OutlineSelectionChangedListener extends - AbstractSelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - doSelectionChanged(event); - } - } - - /** - * The internal shell activation listener for updating occurrences. - * - * @since 3.0 - */ - private ActivationListener fActivationListener = new ActivationListener(); - - private ISelectionListenerWithAST fPostSelectionListenerWithAST; - - private OccurrencesFinderJob fOccurrencesFinderJob; - - /** The occurrences finder job canceler */ - private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler; - - /** - * Holds the current occurrence annotations. - * - * @since 3.0 - */ - private Annotation[] fOccurrenceAnnotations = null; - - /** - * Tells whether all occurrences of the element at the current caret - * location are automatically marked in this editor. - * - * @since 3.0 - */ - private boolean fMarkOccurrenceAnnotations; - - /** - * The selection used when forcing occurrence marking through code. - * - * @since 3.0 - */ - private ISelection fForcedMarkOccurrencesSelection; - - /** - * The document modification stamp at the time when the last occurrence - * marking took place. - * - * @since 3.1 - */ - private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; - - /** - * The region of the word under the caret used to when computing the current - * occurrence markings. - * - * @since 3.1 - */ - private IRegion fMarkOccurrenceTargetRegion; - - /** - * Tells whether the occurrence annotations are sticky i.e. whether they - * stay even if there's no valid Java element at the current caret position. - * Only valid if {@link #fMarkOccurrenceAnnotations} is true. - * - * @since 3.0 - */ - private boolean fStickyOccurrenceAnnotations; - - /** Preference key for the link color */ - private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR; - - /** Preference key for compiler task tags */ - private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; - - // protected PHPActionGroup fActionGroups; - // /** The outline page */ - // private AbstractContentOutlinePage fOutlinePage; - /** The outline page */ - protected JavaOutlinePage fOutlinePage; - - /** Outliner context menu Id */ - protected String fOutlinerContextMenuId; - - /** - * Indicates whether this editor should react on outline page selection - * changes - */ - private int fIgnoreOutlinePageSelection; - - /** The outline page selection updater */ - // private OutlinePageSelectionUpdater fUpdater; - // protected PHPSyntaxParserThread fValidationThread = null; - // private IPreferenceStore fPHPPrefStore; - /** The selection changed listener */ - // protected ISelectionChangedListener fSelectionChangedListener = new - // SelectionChangedListener(); - /** - * The editor selection changed listener. - * - * @since 3.0 - */ - private EditorSelectionChangedListener fEditorSelectionChangedListener; - - /** The selection changed listener */ - protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener(); - - /** The editor's bracket matcher */ - private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS); - - /** The line number ruler column */ - // private LineNumberRulerColumn fLineNumberRulerColumn; - /** This editor's encoding support */ - private DefaultEncodingSupport fEncodingSupport; - - /** The mouse listener */ - private MouseClickListener fMouseListener; - - /** - * Indicates whether this editor is about to update any annotation views. - * - * @since 3.0 - */ - private boolean fIsUpdatingAnnotationViews = false; - - /** - * The marker that served as last target for a goto marker request. - * - * @since 3.0 - */ - private IMarker fLastMarkerTarget = null; - - protected CompositeActionGroup fActionGroups; - - protected CompositeActionGroup fContextMenuGroup; - - /** - * This editor's projection support - * - * @since 3.0 - */ - private ProjectionSupport fProjectionSupport; - - /** - * This editor's projection model updater - * - * @since 3.0 - */ - private IJavaFoldingStructureProvider fProjectionModelUpdater; - - /** - * The override and implements indicator manager for this editor. - * - * @since 3.0 - */ - // protected OverrideIndicatorManager fOverrideIndicatorManager; - /** - * The action group for folding. - * - * @since 3.0 - */ - private FoldingActionGroup fFoldingGroup; - - /** The information presenter. */ - private InformationPresenter fInformationPresenter; - - /** The annotation access */ - // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess(); - /** The overview ruler */ - protected OverviewRuler isOverviewRulerVisible; - - /** The source viewer decoration support */ - // protected SourceViewerDecorationSupport fSourceViewerDecorationSupport; - /** The overview ruler */ - // protected OverviewRuler fOverviewRuler; - /** The preference property change listener for java core. */ - private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener(); - - /** - * Returns the most narrow java element including the given offset - * - * @param offset - * the offset inside of the requested element - */ - abstract protected IJavaElement getElementAt(int offset); - - /** - * Returns the java element of this editor's input corresponding to the - * given IJavaElement - */ - abstract protected IJavaElement getCorrespondingElement(IJavaElement element); - - /** - * Sets the input of the editor's outline page. - */ - abstract protected void setOutlinePageInput(JavaOutlinePage page, - IEditorInput input); - - /** - * Default constructor. - */ - public PHPEditor() { - super(); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes() - */ - protected void initializeKeyBindingScopes() { - setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor() - */ - protected void initializeEditor() { - // jsurfer old code - // JavaTextTools textTools = - // PHPeclipsePlugin.getDefault().getJavaTextTools(); - // setSourceViewerConfiguration(new - // PHPSourceViewerConfiguration(textTools, - // this, IPHPPartitions.PHP_PARTITIONING)); //, - // IJavaPartitions.JAVA_PARTITIONING)); - IPreferenceStore store = createCombinedPreferenceStore(null); - setPreferenceStore(store); - JavaTextTools textTools = WebUI.getDefault() - .getJavaTextTools(); - setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools - .getColorManager(), store, this, - IPHPPartitions.PHP_PARTITIONING)); - - // TODO changed in 3.x ? - // setRangeIndicator(new DefaultRangeIndicator()); - // if - // (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) - // fUpdater = new OutlinePageSelectionUpdater(); - // jsurfer end - - // IPreferenceStore store= createCombinedPreferenceStore(null); - // setPreferenceStore(store); - // JavaTextTools textTools= - // PHPeclipsePlugin.getDefault().getJavaTextTools(); - // setSourceViewerConfiguration(new - // JavaSourceViewerConfiguration(textTools.getColorManager(), store, - // this, IJavaPartitions.JAVA_PARTITIONING)); - fMarkOccurrenceAnnotations = store - .getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); - fStickyOccurrenceAnnotations = store - .getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); - // fMarkTypeOccurrences= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES); - // fMarkMethodOccurrences= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES); - // fMarkConstantOccurrences= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES); - // fMarkFieldOccurrences= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES); - // fMarkLocalVariableypeOccurrences= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES); - // fMarkExceptions= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES); - // fMarkImplementors= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS); - // fMarkMethodExitPoints= - // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS); - - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() - */ - protected void updatePropertyDependentActions() { - super.updatePropertyDependentActions(); - if (fEncodingSupport != null) - fEncodingSupport.reset(); - } - - /* - * Update the hovering behavior depending on the preferences. - */ - private void updateHoverBehavior() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - String[] types = configuration - .getConfiguredContentTypes(getSourceViewer()); - - for (int i = 0; i < types.length; i++) { - - String t = types[i]; - - int[] stateMasks = configuration.getConfiguredTextHoverStateMasks( - getSourceViewer(), t); - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension2) { - if (stateMasks != null) { - for (int j = 0; j < stateMasks.length; j++) { - int stateMask = stateMasks[j]; - ITextHover textHover = configuration.getTextHover( - sourceViewer, t, stateMask); - ((ITextViewerExtension2) sourceViewer).setTextHover( - textHover, t, stateMask); - } - } else { - ITextHover textHover = configuration.getTextHover( - sourceViewer, t); - ((ITextViewerExtension2) sourceViewer).setTextHover( - textHover, t, - ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); - } - } else - sourceViewer.setTextHover(configuration.getTextHover( - sourceViewer, t), t); - } - } - - public void updatedTitleImage(Image image) { - setTitleImage(image); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() - */ - public Object getViewPartInput() { - return getEditorInput().getAdapter(IResource.class); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) - */ - protected void doSetSelection(ISelection selection) { - super.doSetSelection(selection); - synchronizeOutlinePageSelection(); - } - - boolean isFoldingEnabled() { - return WebUI.getDefault().getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_FOLDING_ENABLED); - } - - /* - * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. - * widgets.Composite) - */ - public void createPartControl(Composite parent) { - super.createPartControl(parent); - - // fSourceViewerDecorationSupport.install(getPreferenceStore()); - - ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); - - fProjectionSupport = new ProjectionSupport(projectionViewer, - getAnnotationAccess(), getSharedColors()); - fProjectionSupport - .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ - fProjectionSupport - .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ - fProjectionSupport - .setHoverControlCreator(new IInformationControlCreator() { - public IInformationControl createInformationControl( - Shell shell) { - return new CustomSourceInformationControl(shell, - IDocument.DEFAULT_CONTENT_TYPE); - } - }); - fProjectionSupport.install(); - - fProjectionModelUpdater = WebUI.getDefault() - .getFoldingStructureProviderRegistry() - .getCurrentFoldingProvider(); - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.install(this, projectionViewer); - - if (isFoldingEnabled()) - projectionViewer.doOperation(ProjectionViewer.TOGGLE); - Preferences preferences = PHPeclipsePlugin.getDefault() - .getPluginPreferences(); - preferences.addPropertyChangeListener(fPropertyChangeListener); - IInformationControlCreator informationControlCreator = new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - boolean cutDown = false; - int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); - return new DefaultInformationControl(parent, SWT.RESIZE, style, - new HTMLTextPresenter(cutDown)); - } - }; - - fInformationPresenter = new InformationPresenter( - informationControlCreator); - fInformationPresenter.setSizeConstraints(60, 10, true, true); - fInformationPresenter.install(getSourceViewer()); - - fEditorSelectionChangedListener = new EditorSelectionChangedListener(); - fEditorSelectionChangedListener.install(getSelectionProvider()); - - if (isBrowserLikeLinks()) - enableBrowserLikeLinks(); - - if (PreferenceConstants.getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) - enableOverwriteMode(false); - - if (fMarkOccurrenceAnnotations) - installOccurrencesFinder(); - - PlatformUI.getWorkbench().addWindowListener(fActivationListener); - - /* - * start of EDITOR_SAVE_ON_BLUR - * ed_mann - */ - final PHPEditor editor = this; - FocusListener focusListener = new FocusListener() { - - public void focusGained(FocusEvent e) { - return; - } - - public void focusLost(FocusEvent e) { - //viewer.get - if(editor.isDirty() && WebUI.getDefault().getPreferenceStore() - .getBoolean(PreferenceConstants.EDITOR_SAVE_ON_BLUR)){ - editor.doSave(null); - } - } - }; - projectionViewer.getTextWidget().addFocusListener(focusListener); - /* - * end of EDITOR_SAVE_ON_BLUR - * ed_mann - */ - - setWordWrap(); - } - - private void setWordWrap() { - if (getSourceViewer() != null) { - getSourceViewer().getTextWidget().setWordWrap( - WebUI.getDefault().getPreferenceStore() - .getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS)); - } - } - - protected void configureSourceViewerDecorationSupport( - SourceViewerDecorationSupport support) { - - support.setCharacterPairMatcher(fBracketMatcher); - support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, - MATCHING_BRACKETS_COLOR); - - super.configureSourceViewerDecorationSupport(support); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker) - */ - public void gotoMarker(IMarker marker) { - fLastMarkerTarget = marker; - if (!fIsUpdatingAnnotationViews) { - super.gotoMarker(marker); - } - } - - /** - * Jumps to the next enabled annotation according to the given direction. An - * annotation type is enabled if it is configured to be in the Next/Previous - * tool bar drop down menu and if it is checked. - * - * @param forward - * true if search direction is forward, - * false if backward - */ - public Annotation gotoAnnotation(boolean forward) { - ITextSelection selection = (ITextSelection) getSelectionProvider() - .getSelection(); - Position position = new Position(0, 0); - Annotation annotation = null; - if (false /* delayed - see bug 18316 */) { - annotation = getNextAnnotation(selection.getOffset(), selection - .getLength(), forward, position); - selectAndReveal(position.getOffset(), position.getLength()); - } else /* no delay - see bug 18316 */{ - annotation = getNextAnnotation(selection.getOffset(), selection - .getLength(), forward, position); - setStatusLineErrorMessage(null); - setStatusLineMessage(null); - if (annotation != null) { - updateAnnotationViews(annotation); - selectAndReveal(position.getOffset(), position.getLength()); - setStatusLineMessage(annotation.getText()); - } - } - return annotation; - } - - /** - * Returns the lock object for the given annotation model. - * - * @param annotationModel - * the annotation model - * @return the annotation model's lock object - * @since 3.0 - */ - private Object getLockObject(IAnnotationModel annotationModel) { - if (annotationModel instanceof ISynchronizable) - return ((ISynchronizable) annotationModel).getLockObject(); - else - return annotationModel; - } - - /** - * Updates the annotation views that show the given annotation. - * - * @param annotation - * the annotation - */ - private void updateAnnotationViews(Annotation annotation) { - IMarker marker = null; - if (annotation instanceof MarkerAnnotation) - marker = ((MarkerAnnotation) annotation).getMarker(); - else if (annotation instanceof IJavaAnnotation) { - Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator(); - if (e != null) { - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof MarkerAnnotation) { - marker = ((MarkerAnnotation) o).getMarker(); - break; - } - } - } - } - - if (marker != null && !marker.equals(fLastMarkerTarget)) { - try { - boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM); - IWorkbenchPage page = getSite().getPage(); - IViewPart view = page - .findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW - : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ - if (view != null) { - Method method = view - .getClass() - .getMethod( - "setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$ - method.invoke(view, new Object[] { - new StructuredSelection(marker), Boolean.TRUE }); - } - } catch (CoreException x) { - } catch (NoSuchMethodException x) { - } catch (IllegalAccessException x) { - } catch (InvocationTargetException x) { - } - // ignore exceptions, don't update any of the lists, just set status - // line - } - } - - /** - * Returns this document's complete text. - * - * @return the document's complete text - */ - public String get() { - IDocument doc = this.getDocumentProvider().getDocument( - this.getEditorInput()); - return doc.get(); - } - - /** - * Sets the outliner's context menu ID. - */ - protected void setOutlinerContextMenuId(String menuId) { - fOutlinerContextMenuId = menuId; - } - - /** - * Returns the standard action group of this editor. - */ - protected ActionGroup getActionGroup() { - return fActionGroups; - } - - // public JavaOutlinePage getfOutlinePage() { - // return fOutlinePage; - // } - - /** - * The PHPEditor implementation of this - * AbstractTextEditor method extend the actions to add those - * specific to the receiver - */ - protected void createActions() { - super.createActions(); - - ActionGroup oeg/*, ovg, jsg, sg*/; - fActionGroups = new CompositeActionGroup( - new ActionGroup[] { oeg = new OpenEditorActionGroup(this), - // sg= new ShowActionGroup(this), - // ovg= new OpenViewActionGroup(this), - // jsg= new JavaSearchActionGroup(this) - }); - fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg }); - // , ovg, sg, jsg}); - - fFoldingGroup = new FoldingActionGroup(this, getViewer()); - - // ResourceAction resAction = new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ - // resAction = new - // InformationDispatchAction(PHPEditorMessages.getResourceBundle(), - // "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ - // resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); - // setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ - - // WorkbenchHelp.setHelp(resAction, - // IJavaHelpContextIds.SHOW_JAVADOC_ACTION); - - Action action = new GotoMatchingBracketAction(this); - action - .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); - setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); - - // action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.", - // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); - // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action); - // // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.SHOW_OUTLINE_ACTION); - // - // action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.", - // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE); - // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE, - // action); - // // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); - // - // action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.", - // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY); - // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY, - // action); - // // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); - - fEncodingSupport = new DefaultEncodingSupport(); - fEncodingSupport.initialize(this); - - // fSelectionHistory= new SelectionHistory(this); - // - // action= new StructureSelectEnclosingAction(this, fSelectionHistory); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); - // setAction(StructureSelectionAction.ENCLOSING, action); - // - // action= new StructureSelectNextAction(this, fSelectionHistory); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); - // setAction(StructureSelectionAction.NEXT, action); - // - // action= new StructureSelectPreviousAction(this, fSelectionHistory); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); - // setAction(StructureSelectionAction.PREVIOUS, action); - // - // StructureSelectHistoryAction historyAction= new - // StructureSelectHistoryAction(this, fSelectionHistory); - // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); - // setAction(StructureSelectionAction.HISTORY, historyAction); - // fSelectionHistory.setHistoryAction(historyAction); - // - // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); - // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); - // - // action= - // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); - // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); - // - // action= new QuickFormatAction(); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT); - // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); - // - // action= new RemoveOccurrenceAnnotations(this); - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); - // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$ - - // add annotation actions - action = new JavaSelectMarkerRulerAction2(PHPEditorMessages - .getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ - setAction("AnnotationAction", action); //$NON-NLS-1$ - } - - private void internalDoSetInput(IEditorInput input) throws CoreException { - super.doSetInput(input); - - if (getSourceViewer() instanceof JavaSourceViewer) { - JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer(); - if (viewer.getReconciler() == null) { - IReconciler reconciler = getSourceViewerConfiguration() - .getReconciler(viewer); - if (reconciler != null) { - reconciler.install(viewer); - viewer.setReconciler(reconciler); - } - } - } - - if (fEncodingSupport != null) - fEncodingSupport.reset(); - - setOutlinePageInput(fOutlinePage, input); - - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.initialize(); - - // if (isShowingOverrideIndicators()) - // installOverrideIndicator(false); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) - * @since 3.0 - */ - protected void setPreferenceStore(IPreferenceStore store) { - super.setPreferenceStore(store); - if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) { - JavaTextTools textTools = WebUI.getDefault() - .getJavaTextTools(); - setSourceViewerConfiguration(new PHPSourceViewerConfiguration( - textTools.getColorManager(), store, this, - IPHPPartitions.PHP_PARTITIONING)); - } - if (getSourceViewer() instanceof JavaSourceViewer) - ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store); - } - - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs any extra disposal - * actions required by the php editor. - */ - public void dispose() { - if (fProjectionModelUpdater != null) { - fProjectionModelUpdater.uninstall(); - fProjectionModelUpdater = null; - } - - if (fProjectionSupport != null) { - fProjectionSupport.dispose(); - fProjectionSupport = null; - } - // PHPEditorEnvironment.disconnect(this); - if (fOutlinePage != null) - fOutlinePage.setInput(null); - - if (fActionGroups != null) - fActionGroups.dispose(); - - if (isBrowserLikeLinks()) - disableBrowserLikeLinks(); - - // cancel possible running computation - fMarkOccurrenceAnnotations = false; - uninstallOccurrencesFinder(); - - uninstallOverrideIndicator(); - - if (fActivationListener != null) { - PlatformUI.getWorkbench().removeWindowListener(fActivationListener); - fActivationListener = null; - } - - if (fEncodingSupport != null) { - fEncodingSupport.dispose(); - fEncodingSupport = null; - } - - if (fPropertyChangeListener != null) { - Preferences preferences = PHPeclipsePlugin.getDefault() - .getPluginPreferences(); - preferences.removePropertyChangeListener(fPropertyChangeListener); - fPropertyChangeListener = null; - } - - // if (fSourceViewerDecorationSupport != null) { - // fSourceViewerDecorationSupport.dispose(); - // fSourceViewerDecorationSupport = null; - // } - - if (fBracketMatcher != null) { - fBracketMatcher.dispose(); - fBracketMatcher = null; - } - - if (fEditorSelectionChangedListener != null) { - fEditorSelectionChangedListener.uninstall(getSelectionProvider()); - fEditorSelectionChangedListener = null; - } - - super.dispose(); - } - - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs any extra revert - * behavior required by the php editor. - */ - // public void doRevertToSaved() { - // super.doRevertToSaved(); - // if (fOutlinePage != null) - // fOutlinePage.update(); - // } - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs any extra save behavior - * required by the php editor. - */ - // public void doSave(IProgressMonitor monitor) { - // super.doSave(monitor); - // compile or not, according to the user preferences - // IPreferenceStore store = getPreferenceStore(); - // the parse on save was changed to the eclipse "builders" concept - // if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) { - // IAction a = PHPParserAction.getInstance(); - // if (a != null) - // a.run(); - // } - // if (SWT.getPlatform().equals("win32")) { - // IAction a = ShowExternalPreviewAction.getInstance(); - // if (a != null) - // a.run(); - // } - // if (fOutlinePage != null) - // fOutlinePage.update(); - // } - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs any extra save as - * behavior required by the php editor. - */ - // public void doSaveAs() { - // super.doSaveAs(); - // if (fOutlinePage != null) - // fOutlinePage.update(); - // } - /* - * @see StatusTextEditor#getStatusHeader(IStatus) - */ - protected String getStatusHeader(IStatus status) { - if (fEncodingSupport != null) { - String message = fEncodingSupport.getStatusHeader(status); - if (message != null) - return message; - } - return super.getStatusHeader(status); - } - - /* - * @see StatusTextEditor#getStatusBanner(IStatus) - */ - protected String getStatusBanner(IStatus status) { - if (fEncodingSupport != null) { - String message = fEncodingSupport.getStatusBanner(status); - if (message != null) - return message; - } - return super.getStatusBanner(status); - } - - /* - * @see StatusTextEditor#getStatusMessage(IStatus) - */ - protected String getStatusMessage(IStatus status) { - if (fEncodingSupport != null) { - String message = fEncodingSupport.getStatusMessage(status); - if (message != null) - return message; - } - return super.getStatusMessage(status); - } - - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs sets the input of the - * outline page after AbstractTextEditor has set input. - */ - // protected void doSetInput(IEditorInput input) throws CoreException { - // super.doSetInput(input); - // if (fEncodingSupport != null) - // fEncodingSupport.reset(); - // setOutlinePageInput(fOutlinePage, input); - // } - /* - * @see AbstractTextEditor#doSetInput - */ - protected void doSetInput(IEditorInput input) throws CoreException { - ISourceViewer sourceViewer = getSourceViewer(); - if (!(sourceViewer instanceof ISourceViewerExtension2)) { - setPreferenceStore(createCombinedPreferenceStore(input)); - internalDoSetInput(input); - return; - } - - // uninstall & unregister preference store listener - if (isBrowserLikeLinks()) - disableBrowserLikeLinks(); - getSourceViewerDecorationSupport(sourceViewer).uninstall(); - ((ISourceViewerExtension2) sourceViewer).unconfigure(); - - setPreferenceStore(createCombinedPreferenceStore(input)); - - // install & register preference store listener - sourceViewer.configure(getSourceViewerConfiguration()); - getSourceViewerDecorationSupport(sourceViewer).install( - getPreferenceStore()); - if (isBrowserLikeLinks()) - enableBrowserLikeLinks(); - - internalDoSetInput(input); - } - - /* - * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() - */ - // public Object getViewPartInput() { - // return getEditorInput().getAdapter(IFile.class); - // } - /** - * The PHPEditor implementation of this - * AbstractTextEditor method adds any PHPEditor specific - * entries. - */ - public void editorContextMenuAboutToShow(MenuManager menu) { - super.editorContextMenuAboutToShow(menu); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, - new Separator(IContextMenuConstants.GROUP_OPEN)); - menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker( - IContextMenuConstants.GROUP_SHOW)); - - ActionContext context = new ActionContext(getSelectionProvider() - .getSelection()); - fContextMenuGroup.setContext(context); - fContextMenuGroup.fillContextMenu(menu); - fContextMenuGroup.setContext(null); - // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); - // //$NON-NLS-1$ - // - // ActionContext context = - // new ActionContext(getSelectionProvider().getSelection()); - // fContextMenuGroup.setContext(context); - // fContextMenuGroup.fillContextMenu(menu); - // fContextMenuGroup.setContext(null); - } - - /** - * Creates the outline page used with this editor. - */ - protected JavaOutlinePage createOutlinePage() { - JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this); - fOutlineSelectionChangedListener.install(page); - setOutlinePageInput(page, getEditorInput()); - return page; - } - - /** - * Informs the editor that its outliner has been closed. - */ - public void outlinePageClosed() { - if (fOutlinePage != null) { - fOutlineSelectionChangedListener.uninstall(fOutlinePage); - fOutlinePage = null; - resetHighlightRange(); - } - } - - /** - * Synchronizes the outliner selection with the given element position in - * the editor. - * - * @param element - * the java element to select - */ - protected void synchronizeOutlinePage(ISourceReference element) { - synchronizeOutlinePage(element, true); - } - - /** - * Synchronizes the outliner selection with the given element position in - * the editor. - * - * @param element - * the java element to select - * @param checkIfOutlinePageActive - * true if check for active outline page needs to - * be done - */ - protected void synchronizeOutlinePage(ISourceReference element, - boolean checkIfOutlinePageActive) { - if (fOutlinePage != null && element != null - && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { - fOutlineSelectionChangedListener.uninstall(fOutlinePage); - fOutlinePage.select(element); - fOutlineSelectionChangedListener.install(fOutlinePage); - } - } - - /** - * Synchronizes the outliner selection with the actual cursor position in - * the editor. - */ - public void synchronizeOutlinePageSelection() { - synchronizeOutlinePage(computeHighlightRangeSourceReference()); - - // ISourceViewer sourceViewer = getSourceViewer(); - // if (sourceViewer == null || fOutlinePage == null) - // return; - // - // StyledText styledText = sourceViewer.getTextWidget(); - // if (styledText == null) - // return; - // - // int caret = 0; - // if (sourceViewer instanceof ITextViewerExtension3) { - // ITextViewerExtension3 extension = (ITextViewerExtension3) - // sourceViewer; - // caret = - // extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); - // } else { - // int offset = sourceViewer.getVisibleRegion().getOffset(); - // caret = offset + styledText.getCaretOffset(); - // } - // - // IJavaElement element = getElementAt(caret); - // if (element instanceof ISourceReference) { - // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); - // fOutlinePage.select((ISourceReference) element); - // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); - // } - } - - protected void setSelection(ISourceReference reference, boolean moveCursor) { - - ISelection selection = getSelectionProvider().getSelection(); - if (selection instanceof TextSelection) { - TextSelection textSelection = (TextSelection) selection; - if (textSelection.getOffset() != 0 - || textSelection.getLength() != 0) - markInNavigationHistory(); - } - - if (reference != null) { - - StyledText textWidget = null; - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) - textWidget = sourceViewer.getTextWidget(); - - if (textWidget == null) - return; - - try { - - ISourceRange range = reference.getSourceRange(); - if (range == null) - return; - - int offset = range.getOffset(); - int length = range.getLength(); - - if (offset < 0 || length < 0) - return; - - textWidget.setRedraw(false); - - setHighlightRange(offset, length, moveCursor); - - if (!moveCursor) - return; - - offset = -1; - length = -1; - - if (reference instanceof IMember) { - range = ((IMember) reference).getNameRange(); - if (range != null) { - offset = range.getOffset(); - length = range.getLength(); - } - } - // else if (reference instanceof IImportDeclaration) { - // String name= ((IImportDeclaration) - // reference).getElementName(); - // if (name != null && name.length() > 0) { - // String content= reference.getSource(); - // if (content != null) { - // offset= range.getOffset() + content.indexOf(name); - // length= name.length(); - // } - // } - // } else if (reference instanceof IPackageDeclaration) { - // String name= ((IPackageDeclaration) - // reference).getElementName(); - // if (name != null && name.length() > 0) { - // String content= reference.getSource(); - // if (content != null) { - // offset= range.getOffset() + content.indexOf(name); - // length= name.length(); - // } - // } - // } - - if (offset > -1 && length > 0) { - sourceViewer.revealRange(offset, length); - sourceViewer.setSelectedRange(offset, length); - } - - } catch (JavaModelException x) { - } catch (IllegalArgumentException x) { - } finally { - if (textWidget != null) - textWidget.setRedraw(true); - } - - } else if (moveCursor) { - resetHighlightRange(); - } - - markInNavigationHistory(); - } - - public void setSelection(IJavaElement element) { - if (element == null || element instanceof ICompilationUnit) { // || - // element - // instanceof - // IClassFile) - // { - /* - * If the element is an ICompilationUnit this unit is either the - * input of this editor or not being displayed. In both cases, - * nothing should happened. - * (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) - */ - return; - } - - IJavaElement corresponding = getCorrespondingElement(element); - if (corresponding instanceof ISourceReference) { - ISourceReference reference = (ISourceReference) corresponding; - // set highlight range - setSelection(reference, true); - // set outliner selection - if (fOutlinePage != null) { - fOutlineSelectionChangedListener.uninstall(fOutlinePage); - fOutlinePage.select(reference); - fOutlineSelectionChangedListener.install(fOutlinePage); - } - } - } - - public synchronized void editingScriptStarted() { - ++fIgnoreOutlinePageSelection; - } - - public synchronized void editingScriptEnded() { - --fIgnoreOutlinePageSelection; - } - - public synchronized boolean isEditingScriptRunning() { - return (fIgnoreOutlinePageSelection > 0); - } - - /** - * The PHPEditor implementation of this - * AbstractTextEditor method performs gets the java content - * outline page if request is for a an outline page. - */ - public Object getAdapter(Class required) { - - if (IContentOutlinePage.class.equals(required)) { - if (fOutlinePage == null) - fOutlinePage = createOutlinePage(); - return fOutlinePage; - } - - if (IEncodingSupport.class.equals(required)) - return fEncodingSupport; - - if (required == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { JavaUI.ID_PACKAGES, - IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; - } - - }; - } - if (fProjectionSupport != null) { - Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), - required); - if (adapter != null) - return adapter; - } - - return super.getAdapter(required); - } - - // public Object getAdapter(Class required) { - // if (IContentOutlinePage.class.equals(required)) { - // if (fOutlinePage == null) { - // fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this); - // if (getEditorInput() != null) - // fOutlinePage.setInput(getEditorInput()); - // } - // return fOutlinePage; - // } - // - // if (IEncodingSupport.class.equals(required)) - // return fEncodingSupport; - // - // return super.getAdapter(required); - // } - - protected void doSelectionChanged(SelectionChangedEvent event) { - ISourceReference reference = null; - - ISelection selection = event.getSelection(); - Iterator iter = ((IStructuredSelection) selection).iterator(); - while (iter.hasNext()) { - Object o = iter.next(); - if (o instanceof ISourceReference) { - reference = (ISourceReference) o; - break; - } - } - - if (!isActivePart() && WebUI.getActivePage() != null) - WebUI.getActivePage().bringToTop(this); - - try { - editingScriptStarted(); - setSelection(reference, !isActivePart()); - } finally { - editingScriptEnded(); - } - } - - /* - * @see AbstractTextEditor#adjustHighlightRange(int, int) - */ - protected void adjustHighlightRange(int offset, int length) { - - try { - - IJavaElement element = getElementAt(offset); - while (element instanceof ISourceReference) { - ISourceRange range = ((ISourceReference) element) - .getSourceRange(); - if (offset < range.getOffset() + range.getLength() - && range.getOffset() < offset + length) { - - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - extension.exposeModelRange(new Region( - range.getOffset(), range.getLength())); - } - - setHighlightRange(range.getOffset(), range.getLength(), - true); - if (fOutlinePage != null) { - fOutlineSelectionChangedListener - .uninstall(fOutlinePage); - fOutlinePage.select((ISourceReference) element); - fOutlineSelectionChangedListener.install(fOutlinePage); - } - - return; - } - element = element.getParent(); - } - - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - } - - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - extension.exposeModelRange(new Region(offset, length)); - } else { - resetHighlightRange(); - } - - } - - protected boolean isActivePart() { - IWorkbenchWindow window = getSite().getWorkbenchWindow(); - IPartService service = window.getPartService(); - IWorkbenchPart part = service.getActivePart(); - return part != null && part.equals(this); - } - - // public void openContextHelp() { - // IDocument doc = - // this.getDocumentProvider().getDocument(this.getEditorInput()); - // ITextSelection selection = (ITextSelection) - // this.getSelectionProvider().getSelection(); - // int pos = selection.getOffset(); - // String word = getFunctionName(doc, pos); - // openContextHelp(word); - // } - // - // private void openContextHelp(String word) { - // open(word); - // } - // - // public static void open(String word) { - // IHelp help = WorkbenchHelp.getHelpSupport(); - // if (help != null) { - // IHelpResource helpResource = new PHPFunctionHelpResource(word); - // WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource); - // } else { - // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help - // not available"), false); //$NON-NLS-1$ - // } - // } - - // private String getFunctionName(IDocument doc, int pos) { - // Point word = PHPWordExtractor.findWord(doc, pos); - // if (word != null) { - // try { - // return doc.get(word.x, word.y).replace('_', '-'); - // } catch (BadLocationException e) { - // } - // } - // return ""; - // } - - /* - * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) - */ - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - - try { - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null) - return; - - String property = event.getProperty(); - - if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) { - Object value = event.getNewValue(); - if (value instanceof Integer) { - sourceViewer.getTextWidget().setTabs( - ((Integer) value).intValue()); - } else if (value instanceof String) { - try { - sourceViewer.getTextWidget().setTabs( - Integer.parseInt((String) value)); - } catch (NumberFormatException e) { - // bug #1038071 - set default tab: - sourceViewer.getTextWidget().setTabs(80); - } - } - return; - } - - // if (OVERVIEW_RULER.equals(property)) { - // if (isOverviewRulerVisible()) - // showOverviewRuler(); - // else - // hideOverviewRuler(); - // return; - // } - - // if (LINE_NUMBER_RULER.equals(property)) { - // if (isLineNumberRulerVisible()) - // showLineNumberRuler(); - // else - // hideLineNumberRuler(); - // return; - // } - - // if (fLineNumberRulerColumn != null - // && (LINE_NUMBER_COLOR.equals(property) || - // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || - // PREFERENCE_COLOR_BACKGROUND.equals(property))) { - // - // initializeLineNumberRulerColumn(fLineNumberRulerColumn); - // } - - if (isJavaEditorHoverProperty(property)) - updateHoverBehavior(); - - if (BROWSER_LIKE_LINKS.equals(property)) { - if (isBrowserLikeLinks()) - enableBrowserLikeLinks(); - else - disableBrowserLikeLinks(); - return; - } - - if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE - .equals(property)) { - if (event.getNewValue() instanceof Boolean) { - Boolean disable = (Boolean) event.getNewValue(); - enableOverwriteMode(!disable.booleanValue()); - } - return; - } - - boolean newBooleanValue = false; - Object newValue = event.getNewValue(); - if (newValue != null) - newBooleanValue = Boolean.valueOf(newValue.toString()) - .booleanValue(); - - if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE - .equals(property)) { - if (newBooleanValue) - selectionChanged(); - return; - } - - if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) { - if (newBooleanValue != fMarkOccurrenceAnnotations) { - fMarkOccurrenceAnnotations = newBooleanValue; - if (!fMarkOccurrenceAnnotations) - uninstallOccurrencesFinder(); - else - installOccurrencesFinder(); - } - return; - } - - if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) { - fStickyOccurrenceAnnotations = newBooleanValue; - return; - } - // } - // } - // if - // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) - // { - // if (event.getNewValue() instanceof Boolean) { - // boolean stickyOccurrenceAnnotations= - // ((Boolean)event.getNewValue()).booleanValue(); - // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) - // { - - ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) - .handlePropertyChangeEvent(event); - - // if (affectsOverrideIndicatorAnnotations(event)) { - // if (isShowingOverrideIndicators()) { - // if (fOverrideIndicatorManager == null) - // installOverrideIndicator(true); - // } else { - // if (fOverrideIndicatorManager != null) - // uninstallOverrideIndicator(); - // } - // return; - // } - - if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) { - if (sourceViewer instanceof ProjectionViewer) { - ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer; - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.uninstall(); - // either freshly enabled or provider changed - fProjectionModelUpdater = WebUI.getDefault() - .getFoldingStructureProviderRegistry() - .getCurrentFoldingProvider(); - if (fProjectionModelUpdater != null) { - fProjectionModelUpdater.install(this, projectionViewer); - } - } - return; - } - } finally { - super.handlePreferenceStoreChanged(event); - } - } - - // /* - // * @see - // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) - // */ - // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - // - // try { - // - // ISourceViewer sourceViewer = getSourceViewer(); - // if (sourceViewer == null) - // return; - // - // String property = event.getProperty(); - // - // // if - // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) { - // // Object value= event.getNewValue(); - // // if (value instanceof Integer) { - // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); - // // } else if (value instanceof String) { - // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) - // value)); - // // } - // // return; - // // } - // - // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) { - // if (isLineNumberRulerVisible()) - // showLineNumberRuler(); - // else - // hideLineNumberRuler(); - // return; - // } - // - // if (fLineNumberRulerColumn != null - // && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property) - // || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) - // || PREFERENCE_COLOR_BACKGROUND.equals(property))) { - // - // initializeLineNumberRulerColumn(fLineNumberRulerColumn); - // } - // - // } finally { - // super.handlePreferenceStoreChanged(event); - // } - // } - - // private boolean isJavaEditorHoverProperty(String property) { - // return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property) - // || PreferenceConstants.EDITOR_NONE_HOVER.equals(property) - // || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property) - // || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property) - // || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property) - // || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property) - // || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property) - // || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property); - // } - - /** - * Shows the line number ruler column. - */ - // private void showLineNumberRuler() { - // IVerticalRuler v = getVerticalRuler(); - // if (v instanceof CompositeRuler) { - // CompositeRuler c = (CompositeRuler) v; - // c.addDecorator(1, createLineNumberRulerColumn()); - // } - // } - private boolean isJavaEditorHoverProperty(String property) { - return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property); - } - - /** - * Return whether the browser like links should be enabled according to the - * preference store settings. - * - * @return true if the browser like links should be enabled - */ - private boolean isBrowserLikeLinks() { - IPreferenceStore store = getPreferenceStore(); - return store.getBoolean(BROWSER_LIKE_LINKS); - } - - /** - * Enables browser like links. - */ - private void enableBrowserLikeLinks() { - if (fMouseListener == null) { - fMouseListener = new MouseClickListener(); - fMouseListener.install(); - } - } - - /** - * Disables browser like links. - */ - private void disableBrowserLikeLinks() { - if (fMouseListener != null) { - fMouseListener.uninstall(); - fMouseListener = null; - } - } - - /** - * Handles a property change event describing a change of the java core's - * preferences and updates the preference related editor properties. - * - * @param event - * the property change event - */ - protected void handlePreferencePropertyChanged( - org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { - if (COMPILER_TASK_TAGS.equals(event.getProperty())) { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null - && affectsTextPresentation(new PropertyChangeEvent(event - .getSource(), event.getProperty(), event - .getOldValue(), event.getNewValue()))) - sourceViewer.invalidateTextPresentation(); - } - if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) { - setWordWrap(); - } - } - - /** - * Return whether the line number ruler column should be visible according - * to the preference store settings. - * - * @return true if the line numbers should be visible - */ - // protected boolean isLineNumberRulerVisible() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(LINE_NUMBER_RULER); - // } - /** - * Hides the line number ruler column. - */ - // private void hideLineNumberRuler() { - // IVerticalRuler v = getVerticalRuler(); - // if (v instanceof CompositeRuler) { - // CompositeRuler c = (CompositeRuler) v; - // try { - // c.removeDecorator(1); - // } catch (Throwable e) { - // } - // } - // } - /* - * @see AbstractTextEditor#handleCursorPositionChanged() - */ - // protected void handleCursorPositionChanged() { - // super.handleCursorPositionChanged(); - // if (!isEditingScriptRunning() && fUpdater != null) - // fUpdater.post(); - // } - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced() - */ - protected void handleElementContentReplaced() { - super.handleElementContentReplaced(); - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.initialize(); - } - - /** - * Initializes the given line number ruler column from the preference store. - * - * @param rulerColumn - * the ruler column to be initialized - */ - // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn - // rulerColumn) { - // JavaTextTools textTools = - // PHPeclipsePlugin.getDefault().getJavaTextTools(); - // IColorManager manager = textTools.getColorManager(); - // - // IPreferenceStore store = getPreferenceStore(); - // if (store != null) { - // - // RGB rgb = null; - // // foreground color - // if (store.contains(LINE_NUMBER_COLOR)) { - // if (store.isDefault(LINE_NUMBER_COLOR)) - // rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); - // else - // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); - // } - // rulerColumn.setForeground(manager.getColor(rgb)); - // - // rgb = null; - // // background color - // if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - // if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { - // if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) - // rgb = PreferenceConverter.getDefaultColor(store, - // PREFERENCE_COLOR_BACKGROUND); - // else - // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); - // } - // } - // rulerColumn.setBackground(manager.getColor(rgb)); - // } - // } - /** - * Creates a new line number ruler column that is appropriately initialized. - */ - // protected IVerticalRulerColumn createLineNumberRulerColumn() { - // fLineNumberRulerColumn = new LineNumberRulerColumn(); - // initializeLineNumberRulerColumn(fLineNumberRulerColumn); - // return fLineNumberRulerColumn; - // } - /* - * @see AbstractTextEditor#createVerticalRuler() - */ - // protected IVerticalRuler createVerticalRuler() { - // CompositeRuler ruler = new CompositeRuler(); - // ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); - // if (isLineNumberRulerVisible()) - // ruler.addDecorator(1, createLineNumberRulerColumn()); - // return ruler; - // } - // private static IRegion getSignedSelection(ITextViewer viewer) { - // - // StyledText text = viewer.getTextWidget(); - // int caretOffset = text.getCaretOffset(); - // Point selection = text.getSelection(); - // - // // caret left - // int offset, length; - // if (caretOffset == selection.x) { - // offset = selection.y; - // length = selection.x - selection.y; - // - // // caret right - // } else { - // offset = selection.x; - // length = selection.y - selection.x; - // } - // - // return new Region(offset, length); - // } - protected IRegion getSignedSelection(ISourceViewer sourceViewer) { - StyledText text = sourceViewer.getTextWidget(); - Point selection = text.getSelectionRange(); - - if (text.getCaretOffset() == selection.x) { - selection.x = selection.x + selection.y; - selection.y = -selection.y; - } - - selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x); - - return new Region(selection.x, selection.y); - } - - /** Preference key for matching brackets */ - protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS; - - /** Preference key for matching brackets color */ - protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; - - /** Preference key for highlighting current line */ - // protected final static String CURRENT_LINE = - // PreferenceConstants.EDITOR_CURRENT_LINE; - /** Preference key for highlight color of current line */ - // protected final static String CURRENT_LINE_COLOR = - // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; - /** Preference key for showing print marging ruler */ - // protected final static String PRINT_MARGIN = - // PreferenceConstants.EDITOR_PRINT_MARGIN; - /** Preference key for print margin ruler color */ - // protected final static String PRINT_MARGIN_COLOR = - // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; - /** Preference key for print margin ruler column */ - // protected final static String PRINT_MARGIN_COLUMN = - // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; - /** Preference key for error indication */ - // protected final static String ERROR_INDICATION = - // PreferenceConstants.EDITOR_PROBLEM_INDICATION; - /** Preference key for error color */ - // protected final static String ERROR_INDICATION_COLOR = - // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; - /** Preference key for warning indication */ - // protected final static String WARNING_INDICATION = - // PreferenceConstants.EDITOR_WARNING_INDICATION; - /** Preference key for warning color */ - // protected final static String WARNING_INDICATION_COLOR = - // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; - /** Preference key for task indication */ - protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; - - /** Preference key for task color */ - protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; - - /** Preference key for bookmark indication */ - protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; - - /** Preference key for bookmark color */ - protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; - - /** Preference key for search result indication */ - protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; - - /** Preference key for search result color */ - protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; - - /** Preference key for unknown annotation indication */ - protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; - - /** Preference key for unknown annotation color */ - protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; - - /** Preference key for shwoing the overview ruler */ - protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; - - /** Preference key for error indication in overview ruler */ - protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for warning indication in overview ruler */ - protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for task indication in overview ruler */ - protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for bookmark indication in overview ruler */ - protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for search result indication in overview ruler */ - protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for unknown annotation indication in overview ruler */ - protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; - - // /** Preference key for compiler task tags */ - // private final static String COMPILER_TASK_TAGS= - // JavaCore.COMPILER_TASK_TAGS; - /** Preference key for browser like links */ - private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS; - - /** Preference key for key modifier of browser like links */ - private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER; - - /** - * Preference key for key modifier mask of browser like links. The value is - * only used if the value of EDITOR_BROWSER_LIKE_LINKS cannot - * be resolved to valid SWT modifier bits. - * - * @since 2.1.1 - */ - private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK; - - private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' }; - - private static boolean isBracket(char character) { - for (int i = 0; i != BRACKETS.length; ++i) - if (character == BRACKETS[i]) - return true; - return false; - } - - private static boolean isSurroundedByBrackets(IDocument document, int offset) { - if (offset == 0 || offset == document.getLength()) - return false; - - try { - return isBracket(document.getChar(offset - 1)) - && isBracket(document.getChar(offset)); - - } catch (BadLocationException e) { - return false; - } - } - - // protected void configureSourceViewerDecorationSupport() { - // - // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher); - // - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.UNKNOWN, - // UNKNOWN_INDICATION_COLOR, - // UNKNOWN_INDICATION, - // UNKNOWN_INDICATION_IN_OVERVIEW_RULER, - // 0); - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.BOOKMARK, - // BOOKMARK_INDICATION_COLOR, - // BOOKMARK_INDICATION, - // BOOKMARK_INDICATION_IN_OVERVIEW_RULER, - // 1); - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.TASK, - // TASK_INDICATION_COLOR, - // TASK_INDICATION, - // TASK_INDICATION_IN_OVERVIEW_RULER, - // 2); - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.SEARCH, - // SEARCH_RESULT_INDICATION_COLOR, - // SEARCH_RESULT_INDICATION, - // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, - // 3); - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.WARNING, - // WARNING_INDICATION_COLOR, - // WARNING_INDICATION, - // WARNING_INDICATION_IN_OVERVIEW_RULER, - // 4); - // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( - // AnnotationType.ERROR, - // ERROR_INDICATION_COLOR, - // ERROR_INDICATION, - // ERROR_INDICATION_IN_OVERVIEW_RULER, - // 5); - // - // fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, - // CURRENT_LINE_COLOR); - // fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, - // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN); - // fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, - // MATCHING_BRACKETS_COLOR); - // - // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey()); - // - // } - /** - * Returns the Java element wrapped by this editors input. - * - * @return the Java element wrapped by this editors input. - * @since 3.0 - */ - abstract protected IJavaElement getInputJavaElement(); - - protected void updateStatusLine() { - ITextSelection selection = (ITextSelection) getSelectionProvider() - .getSelection(); - Annotation annotation = getAnnotation(selection.getOffset(), selection - .getLength()); - setStatusLineErrorMessage(null); - setStatusLineMessage(null); - if (annotation != null) { - try { - fIsUpdatingAnnotationViews = true; - updateAnnotationViews(annotation); - } finally { - fIsUpdatingAnnotationViews = false; - } - if (annotation instanceof IJavaAnnotation - && ((IJavaAnnotation) annotation).isProblem()) - setStatusLineMessage(annotation.getText()); - } - } - - /** - * Jumps to the matching bracket. - */ - public void gotoMatchingBracket() { - - ISourceViewer sourceViewer = getSourceViewer(); - IDocument document = sourceViewer.getDocument(); - if (document == null) - return; - - IRegion selection = getSignedSelection(sourceViewer); - - int selectionLength = Math.abs(selection.getLength()); - if (selectionLength > 1) { - setStatusLineErrorMessage(PHPEditorMessages - .getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - // #26314 - int sourceCaretOffset = selection.getOffset() + selection.getLength(); - if (isSurroundedByBrackets(document, sourceCaretOffset)) - sourceCaretOffset -= selection.getLength(); - - IRegion region = fBracketMatcher.match(document, sourceCaretOffset); - if (region == null) { - setStatusLineErrorMessage(PHPEditorMessages - .getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - int offset = region.getOffset(); - int length = region.getLength(); - - if (length < 1) - return; - - int anchor = fBracketMatcher.getAnchor(); - int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset - + length - 1; - - boolean visible = false; - if (sourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; - visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1); - } else { - IRegion visibleRegion = sourceViewer.getVisibleRegion(); - visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion - .getOffset() - + visibleRegion.getLength()); - } - - if (!visible) { - setStatusLineErrorMessage(PHPEditorMessages - .getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - if (selection.getLength() < 0) - targetOffset -= selection.getLength(); - - sourceViewer.setSelectedRange(targetOffset, selection.getLength()); - sourceViewer.revealRange(targetOffset, selection.getLength()); - } - - /** - * Ses the given message as error message to this editor's status line. - * - * @param msg - * message to be set - */ - protected void setStatusLineErrorMessage(String msg) { - IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); - if (statusLine != null) - statusLine.setMessage(true, msg, null); - } - - /** - * Sets the given message as message to this editor's status line. - * - * @param msg - * message to be set - * @since 3.0 - */ - protected void setStatusLineMessage(String msg) { - IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); - if (statusLine != null) - statusLine.setMessage(false, msg, null); - } - - /** - * Returns the annotation closest to the given range respecting the given - * direction. If an annotation is found, the annotations current position is - * copied into the provided annotation position. - * - * @param offset - * the region offset - * @param length - * the region length - * @param forward - * true for forwards, false for - * backward - * @param annotationPosition - * the position of the found annotation - * @return the found annotation - */ - private Annotation getNextAnnotation(final int offset, final int length, - boolean forward, Position annotationPosition) { - - Annotation nextAnnotation = null; - Position nextAnnotationPosition = null; - Annotation containingAnnotation = null; - Position containingAnnotationPosition = null; - boolean currentAnnotation = false; - - IDocument document = getDocumentProvider() - .getDocument(getEditorInput()); - int endOfDocument = document.getLength(); - int distance = Integer.MAX_VALUE; - - IAnnotationModel model = getDocumentProvider().getAnnotationModel( - getEditorInput()); - Iterator e = new JavaAnnotationIterator(model, true, true); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - if ((a instanceof IJavaAnnotation) - && ((IJavaAnnotation) a).hasOverlay() - || !isNavigationTarget(a)) - continue; - - Position p = model.getPosition(a); - if (p == null) - continue; - - if (forward && p.offset == offset || !forward - && p.offset + p.getLength() == offset + length) {// || - // p.includes(offset)) - // { - if (containingAnnotation == null - || (forward - && p.length >= containingAnnotationPosition.length || !forward - && p.length >= containingAnnotationPosition.length)) { - containingAnnotation = a; - containingAnnotationPosition = p; - currentAnnotation = p.length == length; - } - } else { - int currentDistance = 0; - - if (forward) { - currentDistance = p.getOffset() - offset; - if (currentDistance < 0) - currentDistance = endOfDocument + currentDistance; - - if (currentDistance < distance - || currentDistance == distance - && p.length < nextAnnotationPosition.length) { - distance = currentDistance; - nextAnnotation = a; - nextAnnotationPosition = p; - } - } else { - currentDistance = offset + length - - (p.getOffset() + p.length); - if (currentDistance < 0) - currentDistance = endOfDocument + currentDistance; - - if (currentDistance < distance - || currentDistance == distance - && p.length < nextAnnotationPosition.length) { - distance = currentDistance; - nextAnnotation = a; - nextAnnotationPosition = p; - } - } - } - } - if (containingAnnotationPosition != null - && (!currentAnnotation || nextAnnotation == null)) { - annotationPosition.setOffset(containingAnnotationPosition - .getOffset()); - annotationPosition.setLength(containingAnnotationPosition - .getLength()); - return containingAnnotation; - } - if (nextAnnotationPosition != null) { - annotationPosition.setOffset(nextAnnotationPosition.getOffset()); - annotationPosition.setLength(nextAnnotationPosition.getLength()); - } - - return nextAnnotation; - } - - /** - * Returns the annotation overlapping with the given range or - * null. - * - * @param offset - * the region offset - * @param length - * the region length - * @return the found annotation or null - * @since 3.0 - */ - private Annotation getAnnotation(int offset, int length) { - IAnnotationModel model = getDocumentProvider().getAnnotationModel( - getEditorInput()); - Iterator e = new JavaAnnotationIterator(model, true, true); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - if (!isNavigationTarget(a)) - continue; - - Position p = model.getPosition(a); - if (p != null && p.overlapsWith(offset, length)) - return a; - } - - return null; - } - - /** - * Returns whether the given annotation is configured as a target for the - * "Go to Next/Previous Annotation" actions - * - * @param annotation - * the annotation - * @return true if this is a target, false - * otherwise - * @since 3.0 - */ - protected boolean isNavigationTarget(Annotation annotation) { - Preferences preferences = EditorsUI.getPluginPreferences(); - AnnotationPreference preference = getAnnotationPreferenceLookup() - .getAnnotationPreference(annotation); - // See bug 41689 - // String key= forward ? preference.getIsGoToNextNavigationTargetKey() : - // preference.getIsGoToPreviousNavigationTargetKey(); - String key = preference == null ? null : preference - .getIsGoToNextNavigationTargetKey(); - return (key != null && preferences.getBoolean(key)); - } - - /** - * Returns a segmentation of the line of the given document appropriate for - * bidi rendering. The default implementation returns only the string - * literals of a php code line as segments. - * - * @param document - * the document - * @param lineOffset - * the offset of the line - * @return the line's bidi segmentation - * @throws BadLocationException - * in case lineOffset is not valid in document - */ - public static int[] getBidiLineSegments(IDocument document, int lineOffset) - throws BadLocationException { - - IRegion line = document.getLineInformationOfOffset(lineOffset); - ITypedRegion[] linePartitioning = document.computePartitioning( - lineOffset, line.getLength()); - - List segmentation = new ArrayList(); - for (int i = 0; i < linePartitioning.length; i++) { - if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i] - .getType())) { - segmentation.add(linePartitioning[i]); - } else if (IPHPPartitions.PHP_STRING_HEREDOC - .equals(linePartitioning[i].getType())) { - segmentation.add(linePartitioning[i]); - } - } - - if (segmentation.size() == 0) - return null; - - int size = segmentation.size(); - int[] segments = new int[size * 2 + 1]; - - int j = 0; - for (int i = 0; i < size; i++) { - ITypedRegion segment = (ITypedRegion) segmentation.get(i); - - if (i == 0) - segments[j++] = 0; - - int offset = segment.getOffset() - lineOffset; - if (offset > segments[j - 1]) - segments[j++] = offset; - - if (offset + segment.getLength() >= line.getLength()) - break; - - segments[j++] = offset + segment.getLength(); - } - - if (j < segments.length) { - int[] result = new int[j]; - System.arraycopy(segments, 0, result, 0, j); - segments = result; - } - - return segments; - } - - /** - * Returns a segmentation of the given line appropriate for bidi rendering. - * The default implementation returns only the string literals of a php code - * line as segments. - * - * @param lineOffset - * the offset of the line - * @param line - * the content of the line - * @return the line's bidi segmentation - */ - protected int[] getBidiLineSegments(int lineOffset, String line) { - IDocumentProvider provider = getDocumentProvider(); - if (provider != null && line != null && line.length() > 0) { - IDocument document = provider.getDocument(getEditorInput()); - if (document != null) - try { - return getBidiLineSegments(document, lineOffset); - } catch (BadLocationException x) { - // ignore - } - } - return null; - } - - /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, - * int) - */ - // protected final ISourceViewer createSourceViewer( - // Composite parent, - // IVerticalRuler ruler, - // int styles) { - // ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles); - // StyledText text = viewer.getTextWidget(); - // text.addBidiSegmentListener(new BidiSegmentListener() { - // public void lineGetSegments(BidiSegmentEvent event) { - // event.segments = getBidiLineSegments(event.lineOffset, event.lineText); - // } - // }); - // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); - // return viewer; - // } - public final ISourceViewer getViewer() { - return getSourceViewer(); - } - - // protected void showOverviewRuler() { - // if (fOverviewRuler != null) { - // if (getSourceViewer() instanceof ISourceViewerExtension) { - // ((ISourceViewerExtension) - // getSourceViewer()).showAnnotationsOverview(true); - // fSourceViewerDecorationSupport.updateOverviewDecorations(); - // } - // } - // } - // - // protected void hideOverviewRuler() { - // if (getSourceViewer() instanceof ISourceViewerExtension) { - // fSourceViewerDecorationSupport.hideAnnotationOverview(); - // ((ISourceViewerExtension) - // getSourceViewer()).showAnnotationsOverview(false); - // } - // } - - // protected boolean isOverviewRulerVisible() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(OVERVIEW_RULER); - // } - /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, - * int) - */ - // protected ISourceViewer createJavaSourceViewer( - // Composite parent, - // IVerticalRuler ruler, - // IOverviewRuler overviewRuler, - // boolean isOverviewRulerVisible, - // int styles) { - // return new SourceViewer(parent, ruler, overviewRuler, - // isOverviewRulerVisible(), styles); - // } - /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, - * int) - */ - protected ISourceViewer createJavaSourceViewer(Composite parent, - IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { - return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), - isOverviewRulerVisible(), styles, store); - } - - /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, - * int) - */ - protected final ISourceViewer createSourceViewer(Composite parent, - IVerticalRuler verticalRuler, int styles) { - - ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, - getOverviewRuler(), isOverviewRulerVisible(), styles, - getPreferenceStore()); - - StyledText text = viewer.getTextWidget(); - text.addBidiSegmentListener(new BidiSegmentListener() { - public void lineGetSegments(BidiSegmentEvent event) { - event.segments = getBidiLineSegments(event.lineOffset, - event.lineText); - } - }); - - // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); - - // ensure source viewer decoration support has been created and - // configured - getSourceViewerDecorationSupport(viewer); - - return viewer; - } - - /* - * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) - */ - protected boolean affectsTextPresentation(PropertyChangeEvent event) { - return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) - .affectsTextPresentation(event) - || super.affectsTextPresentation(event); - } - - // - // protected boolean affectsTextPresentation(PropertyChangeEvent event) { - // JavaTextTools textTools = - // PHPeclipsePlugin.getDefault().getJavaTextTools(); - // return textTools.affectsBehavior(event); - // } - /** - * Creates and returns the preference store for this Java editor with the - * given input. - * - * @param input - * The editor input for which to create the preference store - * @return the preference store for this editor - * - * @since 3.0 - */ - private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) { - List stores = new ArrayList(3); - - IJavaProject project = EditorUtility.getJavaProject(input); - if (project != null) - stores.add(new OptionsAdapter(project.getOptions(false), - WebUI.getDefault().getMockupPreferenceStore(), - new OptionsAdapter.IPropertyChangeEventFilter() { - - public boolean isFiltered(PropertyChangeEvent event) { - IJavaElement inputJavaElement = getInputJavaElement(); - IJavaProject javaProject = inputJavaElement != null ? inputJavaElement - .getJavaProject() - : null; - if (javaProject == null) - return true; - - return !javaProject.getProject().equals( - event.getSource()); - } - - })); - - stores.add(WebUI.getDefault().getPreferenceStore()); - stores.add(new PreferencesAdapter(JavaCore.getPlugin() - .getPluginPreferences())); - stores.add(EditorsUI.getPreferenceStore()); - - return new ChainedPreferenceStore((IPreferenceStore[]) stores - .toArray(new IPreferenceStore[stores.size()])); - } - - /** - * Jumps to the error next according to the given direction. - */ - public void gotoError(boolean forward) { - - ISelectionProvider provider = getSelectionProvider(); - - ITextSelection s = (ITextSelection) provider.getSelection(); - Position errorPosition = new Position(0, 0); - IJavaAnnotation nextError = getNextError(s.getOffset(), forward, - errorPosition); - - if (nextError != null) { - - IMarker marker = null; - if (nextError instanceof MarkerAnnotation) - marker = ((MarkerAnnotation) nextError).getMarker(); - else { - Iterator e = nextError.getOverlaidIterator(); - if (e != null) { - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof MarkerAnnotation) { - marker = ((MarkerAnnotation) o).getMarker(); - break; - } - } - } - } - - if (marker != null) { - IWorkbenchPage page = getSite().getPage(); - IViewPart view = view = page - .findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ - if (view instanceof TaskList) { - StructuredSelection ss = new StructuredSelection(marker); - ((TaskList) view).setSelection(ss, true); - } - } - - selectAndReveal(errorPosition.getOffset(), errorPosition - .getLength()); - // setStatusLineErrorMessage(nextError.getMessage()); - - } else { - - setStatusLineErrorMessage(null); - - } - } - - private IJavaAnnotation getNextError(int offset, boolean forward, - Position errorPosition) { - - IJavaAnnotation nextError = null; - Position nextErrorPosition = null; - - IDocument document = getDocumentProvider() - .getDocument(getEditorInput()); - int endOfDocument = document.getLength(); - int distance = 0; - - IAnnotationModel model = getDocumentProvider().getAnnotationModel( - getEditorInput()); - Iterator e = new JavaAnnotationIterator(model, false); - while (e.hasNext()) { - - IJavaAnnotation a = (IJavaAnnotation) e.next(); - if (a.hasOverlay() || !a.isProblem()) - continue; - - Position p = model.getPosition((Annotation) a); - if (!p.includes(offset)) { - - int currentDistance = 0; - - if (forward) { - currentDistance = p.getOffset() - offset; - if (currentDistance < 0) - currentDistance = endOfDocument - offset - + p.getOffset(); - } else { - currentDistance = offset - p.getOffset(); - if (currentDistance < 0) - currentDistance = offset + endOfDocument - - p.getOffset(); - } - - if (nextError == null || currentDistance < distance) { - distance = currentDistance; - nextError = a; - nextErrorPosition = p; - } - } - } - - if (nextErrorPosition != null) { - errorPosition.setOffset(nextErrorPosition.getOffset()); - errorPosition.setLength(nextErrorPosition.getLength()); - } - - return nextError; - } - - protected void uninstallOverrideIndicator() { - // if (fOverrideIndicatorManager != null) { - // fOverrideIndicatorManager.removeAnnotations(); - // fOverrideIndicatorManager= null; - // } - } - - protected void installOverrideIndicator(boolean waitForReconcilation) { - uninstallOverrideIndicator(); - IAnnotationModel model = getDocumentProvider().getAnnotationModel( - getEditorInput()); - final IJavaElement inputElement = getInputJavaElement(); - - if (model == null || inputElement == null) - return; - - // fOverrideIndicatorManager= new OverrideIndicatorManager(model, - // inputElement, null); - // - // if (provideAST) { - // Job job= new - // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) - // { - // //$NON-NLS-1$ - // /* - // * @see - // org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) - // * @since 3.0 - // */ - // protected IStatus run(IProgressMonitor monitor) { - // CompilationUnit ast= - // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, - // null); - // if (fOverrideIndicatorManager != null) // editor might have been - // closed - // in the meanwhile - // fOverrideIndicatorManager.reconciled(ast, true, monitor); - // return Status.OK_STATUS; - // } - // }; - // job.setPriority(Job.DECORATE); - // job.setSystem(true); - // job.schedule(); - // } - } - - /** - * Tells whether override indicators are shown. - * - * @return true if the override indicators are shown - * @since 3.0 - */ - // protected boolean isShowingOverrideIndicators() { - // AnnotationPreference preference= - // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE); - // IPreferenceStore store= getPreferenceStore(); - // return getBoolean(store, preference.getHighlightPreferenceKey()) - // || getBoolean(store, preference.getVerticalRulerPreferenceKey()) - // || getBoolean(store, preference.getOverviewRulerPreferenceKey()) - // || getBoolean(store, preference.getTextPreferenceKey()); - // } - /** - * Returns the boolean preference for the given key. - * - * @param store - * the preference store - * @param key - * the preference key - * @return true if the key exists in the store and its value - * is true - * @since 3.0 - */ -// private boolean getBoolean(IPreferenceStore store, String key) { -// return key != null && store.getBoolean(key); -// } - - protected boolean isPrefQuickDiffAlwaysOn() { - return false; // never show change ruler for the non-editable java - // editor. - // Overridden in subclasses like PHPUnitEditor - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() - */ - protected void createNavigationActions() { - super.createNavigationActions(); - - final StyledText textWidget = getSourceViewer().getTextWidget(); - - IAction action = new SmartLineStartAction(textWidget, false); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); - setAction(ITextEditorActionDefinitionIds.LINE_START, action); - - action = new SmartLineStartAction(textWidget, true); - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); - setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); - - action = new NavigatePreviousSubWordAction(); - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); - setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); - - action = new NavigateNextSubWordAction(); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); - setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); - - action = new SelectPreviousSubWordAction(); - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); - setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, - SWT.NULL); - - action = new SelectNextSubWordAction(); - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); - setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); - textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, - SWT.NULL); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler() - */ - // protected CompositeRuler createCompositeRuler() { - // if - // (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) - // return super.createCompositeRuler(); - // - // CompositeRuler ruler = new CompositeRuler(); - // AnnotationRulerColumn column = new - // AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess()); - // column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new - // IDoubleClickListener() { - // - // public void doubleClick(DoubleClickEvent event) { - // // for now: just invoke ruler double click action - // triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); - // } - // - // private void triggerAction(String actionID) { - // IAction action = getAction(actionID); - // if (action != null) { - // if (action instanceof IUpdate) - // ((IUpdate) action).update(); - // // hack to propagate line change - // if (action instanceof ISelectionListener) { - // ((ISelectionListener) action).selectionChanged(null, null); - // } - // if (action.isEnabled()) - // action.run(); - // } - // } - // - // })); - // ruler.addDecorator(0, column); - // - // if (isLineNumberRulerVisible()) - // ruler.addDecorator(1, createLineNumberRulerColumn()); - // else if (isPrefQuickDiffAlwaysOn()) - // ruler.addDecorator(1, createChangeRulerColumn()); - // - // return ruler; - // } - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler) - * @since 3.2 - */ - protected IVerticalRulerColumn createAnnotationRulerColumn( - CompositeRuler ruler) { - if (!getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) - return super.createAnnotationRulerColumn(ruler); - - AnnotationRulerColumn column = new AnnotationRulerColumn( - VERTICAL_RULER_WIDTH, getAnnotationAccess()); - column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), - new IDoubleClickListener() { - - public void doubleClick(DoubleClickEvent event) { - // for now: just invoke ruler double click action - triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); - } - - private void triggerAction(String actionID) { - IAction action = getAction(actionID); - if (action != null) { - if (action instanceof IUpdate) - ((IUpdate) action).update(); - // hack to propagate line change - if (action instanceof ISelectionListener) { - ((ISelectionListener) action).selectionChanged( - null, null); - } - if (action.isEnabled()) - action.run(); - } - } - - })); - - return column; - } - - /** - * Returns the folding action group, or null if there is - * none. - * - * @return the folding action group, or null if there is none - * @since 3.0 - */ - protected FoldingActionGroup getFoldingActionGroup() { - return fFoldingGroup; - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert() - */ - protected void performRevert() { - ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); - projectionViewer.setRedraw(false); - try { - - boolean projectionMode = projectionViewer.isProjectionMode(); - if (projectionMode) { - projectionViewer.disableProjection(); - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.uninstall(); - } - - super.performRevert(); - - if (projectionMode) { - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.install(this, projectionViewer); - projectionViewer.enableProjection(); - } - - } finally { - projectionViewer.setRedraw(true); - } - } - - /** - * React to changed selection. - * - * @since 3.0 - */ - protected void selectionChanged() { - if (getSelectionProvider() == null) - return; - ISourceReference element = computeHighlightRangeSourceReference(); - if (getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) - synchronizeOutlinePage(element); - setSelection(element, false); - updateStatusLine(); - } - - private boolean isJavaOutlinePageActive() { - IWorkbenchPart part = getActivePart(); - return part instanceof ContentOutline - && ((ContentOutline) part).getCurrentPage() == fOutlinePage; - } - - private IWorkbenchPart getActivePart() { - IWorkbenchWindow window = getSite().getWorkbenchWindow(); - IPartService service = window.getPartService(); - IWorkbenchPart part = service.getActivePart(); - return part; - } - - /** - * Computes and returns the source reference that includes the caret and - * serves as provider for the outline page selection and the editor range - * indication. - * - * @return the computed source reference - * @since 3.0 - */ - protected ISourceReference computeHighlightRangeSourceReference() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null) - return null; - - StyledText styledText = sourceViewer.getTextWidget(); - if (styledText == null) - return null; - - int caret = 0; - if (sourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; - caret = extension.widgetOffset2ModelOffset(styledText - .getCaretOffset()); - } else { - int offset = sourceViewer.getVisibleRegion().getOffset(); - caret = offset + styledText.getCaretOffset(); - } - - IJavaElement element = getElementAt(caret, false); - - if (!(element instanceof ISourceReference)) - return null; - - if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { - - IImportDeclaration declaration = (IImportDeclaration) element; - IImportContainer container = (IImportContainer) declaration - .getParent(); - ISourceRange srcRange = null; - - try { - srcRange = container.getSourceRange(); - } catch (JavaModelException e) { - } - - if (srcRange != null && srcRange.getOffset() == caret) - return container; - } - - return (ISourceReference) element; - } - - /** - * Returns the most narrow java element including the given offset. - * - * @param offset - * the offset inside of the requested element - * @param reconcile - * true if editor input should be reconciled in - * advance - * @return the most narrow java element - * @since 3.0 - */ - protected IJavaElement getElementAt(int offset, boolean reconcile) { - return getElementAt(offset); - } - - public ShowInContext getShowInContext() { - IFile file = null; - if(getEditorInput() instanceof FileStoreEditorInput){ - FileStoreEditorInput fei = (FileStoreEditorInput) getEditorInput(); - file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getURI().getPath())); - } else if (getEditorInput() instanceof FileEditorInput) { - FileEditorInput fei = (FileEditorInput) getEditorInput(); - // added to fix ticket 637 - file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getURI().getPath())); - } else if (getEditorInput() instanceof ExternalEditorInput) { - ExternalEditorInput fei = (ExternalEditorInput) getEditorInput(); - file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getFullPath()/* .getURI().getPath()*/)); - } - - ShowInContext context = BrowserUtil.getShowInContext(file, - false, ""); - if (context != null) { - return context; - } - return new ShowInContext(file, null); - } - - public String[] getShowInTargetIds() { - return new String[] { BrowserView.ID_BROWSER }; - } - - /** - * Updates the occurrences annotations based on the current selection. - * - * @param selection - * the text selection - * @param astRoot - * the compilation unit AST - * @since 3.0 - */ - protected void updateOccurrenceAnnotations(ITextSelection selection) {// , - // CompilationUnit - // astRoot) - // { - - if (fOccurrencesFinderJob != null) - fOccurrencesFinderJob.cancel(); - - if (!fMarkOccurrenceAnnotations) - return; - - // if (astRoot == null || selection == null) - if (selection == null) - return; - - IDocument document = getSourceViewer().getDocument(); - if (document == null) - return; - - fMarkOccurrenceTargetRegion = null; - if (document instanceof IDocumentExtension4) { - int offset = selection.getOffset(); - long currentModificationStamp = ((IDocumentExtension4) document) - .getModificationStamp(); - if (fMarkOccurrenceTargetRegion != null - && currentModificationStamp == fMarkOccurrenceModificationStamp) { - if (fMarkOccurrenceTargetRegion.getOffset() <= offset - && offset <= fMarkOccurrenceTargetRegion.getOffset() - + fMarkOccurrenceTargetRegion.getLength()) - return; - } - fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document, - offset); - fMarkOccurrenceModificationStamp = currentModificationStamp; - } - - if (fMarkOccurrenceTargetRegion == null - || fMarkOccurrenceTargetRegion.getLength() == 0) { - return; - } - - List matches = null; - - if (matches == null) { - try { - matches = new ArrayList(); - - Scanner fScanner = new Scanner(); - fScanner.setSource(document.get().toCharArray()); - fScanner.setPHPMode(false); - String wordStr; - char[] word; - - wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(), - fMarkOccurrenceTargetRegion.getLength()); - if (wordStr != null) { - word = wordStr.toCharArray(); - int fToken = ITerminalSymbols.TokenNameEOF; - try { - fToken = fScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF) { // && - // fToken - // != - // TokenNameERROR) { - if (fToken == ITerminalSymbols.TokenNameVariable - || fToken == ITerminalSymbols.TokenNameIdentifier) { - // global variable - if (fScanner.equalsCurrentTokenSource(word)) { - matches - .add(new Region( - fScanner - .getCurrentTokenStartPosition(), - fScanner - .getCurrentTokenEndPosition() - - fScanner - .getCurrentTokenStartPosition() - + 1)); - } - } - fToken = fScanner.getNextToken(); - } - } catch (InvalidInputException e) { - // ignore errors - } catch (SyntaxError e) { - // ignore errors - } - } - } catch (BadLocationException e1) { - // ignore errors - } catch (Exception e) { - e.printStackTrace(); - // ignore errors - } - - } - - if (matches == null || matches.size() == 0) { - if (!fStickyOccurrenceAnnotations) - removeOccurrenceAnnotations(); - return; - } - - Position[] positions = new Position[matches.size()]; - int i = 0; - for (Iterator each = matches.iterator(); each.hasNext();) { - IRegion currentNode = (IRegion) each.next(); - positions[i++] = new Position(currentNode.getOffset(), currentNode - .getLength()); - } - - fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions, - selection); - // fOccurrencesFinderJob.setPriority(Job.DECORATE); - // fOccurrencesFinderJob.setSystem(true); - // fOccurrencesFinderJob.schedule(); - fOccurrencesFinderJob.run(new NullProgressMonitor()); - } - - protected void installOccurrencesFinder() { - fMarkOccurrenceAnnotations = true; - - fPostSelectionListenerWithAST = new ISelectionListenerWithAST() { - public void selectionChanged(IEditorPart part, - ITextSelection selection) { // , - // CompilationUnit - // astRoot) - // { - updateOccurrenceAnnotations(selection);// , astRoot); - } - }; - SelectionListenerWithASTManager.getDefault().addListener(this, - fPostSelectionListenerWithAST); - if (getSelectionProvider() != null) { - fForcedMarkOccurrencesSelection = getSelectionProvider() - .getSelection(); - SelectionListenerWithASTManager.getDefault().forceSelectionChange( - this, (ITextSelection) fForcedMarkOccurrencesSelection); - } - - if (fOccurrencesFinderJobCanceler == null) { - fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler(); - fOccurrencesFinderJobCanceler.install(); - } - } - - protected void uninstallOccurrencesFinder() { - fMarkOccurrenceAnnotations = false; - - if (fOccurrencesFinderJob != null) { - fOccurrencesFinderJob.cancel(); - fOccurrencesFinderJob = null; - } - - if (fOccurrencesFinderJobCanceler != null) { - fOccurrencesFinderJobCanceler.uninstall(); - fOccurrencesFinderJobCanceler = null; - } - - if (fPostSelectionListenerWithAST != null) { - SelectionListenerWithASTManager.getDefault().removeListener(this, - fPostSelectionListenerWithAST); - fPostSelectionListenerWithAST = null; - } - - removeOccurrenceAnnotations(); - } - - protected boolean isMarkingOccurrences() { - return fMarkOccurrenceAnnotations; - } - - void removeOccurrenceAnnotations() { - fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; - fMarkOccurrenceTargetRegion = null; - - IDocumentProvider documentProvider = getDocumentProvider(); - if (documentProvider == null) - return; - - IAnnotationModel annotationModel = documentProvider - .getAnnotationModel(getEditorInput()); - if (annotationModel == null || fOccurrenceAnnotations == null) - return; - - synchronized (getLockObject(annotationModel)) { - if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension) annotationModel) - .replaceAnnotations(fOccurrenceAnnotations, null); - } else { - for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++) - annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); - } - fOccurrenceAnnotations = null; - } - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java deleted file mode 100644 index 4932717..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java +++ /dev/null @@ -1,349 +0,0 @@ -package net.sourceforge.phpeclipse.phpeditor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import net.sourceforge.phpeclipse.IPreferenceConstants; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant; -import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; -import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword; -import net.sourceforge.phpeclipse.phpeditor.php.PHPType; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.runtime.CoreException; -//import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.preference.IPreferenceStore; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -/** - * PHPSyntaxRdr reads PHP specifics from an XML file (eg. - * keywords) - */ - -public class PHPSyntaxRdr { - // private static final String PHPDEFAULT_FILE = "default-syntax.xml"; - // //$NON-NLS-1$ - private static final String PHPSYNTAX_FILE = "syntax.xml"; //$NON-NLS-1$ - // private static final String USERSYNTAX_FILE = "usersyntax.xml"; - // //$NON-NLS-1$ - // private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; - // //$NON-NLS-1$ - - private static final String PHPSYNTAX_TAG = "s"; //$NON-NLS-1$ - - private static final String KEYWORD_ATTR = "k"; //$NON-NLS-1$ - - private static final String TYPE_ATTR = "t"; //$NON-NLS-1$ - - private static final String CONSTANT_ATTR = "c"; //$NON-NLS-1$ - - private static final String FN_ATTR = "f"; //$NON-NLS-1$ - - private static final String USAGE_ATTR = "u"; //$NON-NLS-1$ - // private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ - - private static IPreferenceStore store; - - //private static boolean hasXMLFileBeenRead = true; - - // The following variable is used to hold the syntax from - // the suers custom file - if that file should be changed, - // then all entries in this variable should be removed from - // the word list, reread from the file and then reinserted. - private static ArrayList userdefsyntaxdata; - - private static ArrayList syntaxdata; - - public PHPSyntaxRdr() { - // see getSyntaxData() - syntaxdata = null; - store = WebUI.getDefault().getPreferenceStore(); - } - - public static void readInSyntax() { - try { -// hasXMLFileBeenRead = true; - /* - * Attempt to read the syntax file from the metadata if this does - * not work, create metadata from default - */ - /*File syntaxFile = getSyntaxFile(); - if (syntaxFile.exists()) { - readFromFile(syntaxFile); - } else {*/ - readFromStream(PHPSyntaxRdr.class - .getResourceAsStream(PHPSYNTAX_FILE)); - //saveToFile(syntaxFile); - /*}*/ - /* Read the user-defined syntax file if it exists */ - // String buffer = new - // String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE)); - /*if (store == null) - store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - String buffer = new String(store - .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); - if (!(buffer.equals("") || buffer == null)) { - readFromFile(buffer); - }*/ - } catch (CoreException ce) { - ce.printStackTrace(); - } - } - - public static void readFromFile(String filename) { - try { - readFromFile(new File(filename)); - } catch (CoreException e) { - } - } - - public static void readFromFile(File file) throws CoreException { - InputStream stream = null; - - if (file.exists()) { - try { - stream = new FileInputStream(file); - readFromStream(stream); - } catch (IOException e) { - throwReadException(e); - } finally { - try { - if (stream != null) { - stream.close(); - } - } catch (IOException e) { - } - } - } - } - - public static void readFromStream(InputStream stream) throws CoreException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - DocumentBuilder parser = factory.newDocumentBuilder(); - Document document = parser.parse(new InputSource(stream)); - // Read in the Standard PHPSyntax "stuff" - NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG); - - int count = elements.getLength(); - for (int i = 0; i != count; i++) { - Node node = elements.item(i); - NamedNodeMap attributes = node.getAttributes(); - - if (attributes == null) - continue; - - String Keyword = getAttributeValue(attributes, KEYWORD_ATTR); - String Type = getAttributeValue(attributes, TYPE_ATTR); - String Function = getAttributeValue(attributes, FN_ATTR); - String Constant = getAttributeValue(attributes, CONSTANT_ATTR); - String usage = getAttributeValue(attributes, USAGE_ATTR); - // String Tokenval = getAttributeValue(attributes, - // TOKENVAL_ATTR); - - StringBuffer buffer = new StringBuffer(); - NodeList children = node.getChildNodes(); - for (int j = 0; j != children.getLength(); j++) { - String value = children.item(j).getNodeValue(); - if (value != null) - buffer.append(value); - } - String description = buffer.toString().trim(); - - if (Keyword == null && Type == null && Function == null - && Constant == null) { - // ignore as it is not a valid phpsyntax tag - } else { - if (Keyword != null) { - // syntaxdata.add(new PHPKeyword(Keyword, usage, - // Tokenval)); - syntaxdata.add(new PHPKeyword(Keyword, usage)); - } else if (Type != null) { - syntaxdata.add(new PHPType(Type, usage)); - } else if (Function != null) { - syntaxdata.add(new PHPFunction(Function, usage, - description)); - } else if (Constant != null) { - syntaxdata.add(new PHPConstant(Constant, null, - description)); - } - } - } - } catch (ParserConfigurationException e) { - throwReadException(e); - } catch (IOException e) { - throwReadException(e); - } catch (SAXParseException e) { - System.out.println("SAXParseException in line:" + e.getLineNumber() - + " column:" + e.getColumnNumber()); - throwReadException(e); - } catch (SAXException e) { - throwReadException(e); - } - } - - public static ArrayList getSyntaxData() { - if (syntaxdata == null) { - syntaxdata = new ArrayList(); - readInSyntax(); - } - return syntaxdata; - } - - public static void replaceUserDefFile() { - /* Replace the user-defined syntax file if it exists */ - String buffer = new String(store - .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); - if (!buffer.equals("") || buffer == null) { - readFromFile(buffer); - } - } - - public static ArrayList getUserSyntaxData() { - return userdefsyntaxdata; - } - -// private static File getSyntaxFile() { -// IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); -// path = path.append(PHPSYNTAX_FILE); -// return path.toFile(); -// } - - private static String getAttributeValue(NamedNodeMap attributes, String name) { - Node node = attributes.getNamedItem(name); - return node == null ? null : node.getNodeValue(); - } - - public static void saveToFile(File file) throws CoreException { - OutputStream stream = null; - try { - stream = new FileOutputStream(file); - saveToStream(stream); - } catch (IOException e) { - throwWriteException(e); - } finally { - try { - if (stream != null) - stream.close(); - } catch (IOException e) { - } - } - } - - public static void saveToStream(OutputStream stream) throws CoreException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ - // //$NON-NLS-1$ - document.appendChild(root); - for (int i = 0; i != syntaxdata.size(); i++) { - Object bufferobj = (Object) syntaxdata.get(i); - Attr name = null; - Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ - // //$NON-NLS-1$ - root.appendChild(node); - NamedNodeMap attributes = node.getAttributes(); - if (bufferobj instanceof PHPType) - name = document.createAttribute(TYPE_ATTR); - if (bufferobj instanceof PHPKeyword) - name = document.createAttribute(KEYWORD_ATTR); - if (bufferobj instanceof PHPFunction) - name = document.createAttribute(FN_ATTR); - if (bufferobj instanceof PHPConstant) - name = document.createAttribute(CONSTANT_ATTR); - name.setValue(((PHPElement) bufferobj).getName()); - attributes.setNamedItem(name); - Attr description = document.createAttribute(USAGE_ATTR); - description.setValue(((PHPElement) bufferobj).getUsage()); - attributes.setNamedItem(description); - // if (bufferobj instanceof PHPKeyword) { - // Attr tokenval = document.createAttribute(TOKENVAL_ATTR); - // tokenval.setValue((new Integer(((PHPKeyword) - // bufferobj).gettokenval())).toString()); - // attributes.setNamedItem(tokenval); - // } - if (bufferobj instanceof PHPFunction) { - // Attr usage = document.createAttribute(USAGE_ATTR); - Text usage = document - .createTextNode(((PHPFunction) bufferobj) - .getDescription()); - node.appendChild(usage); - } - if (bufferobj instanceof PHPConstant) { - // Attr usage = document.createAttribute(USAGE_ATTR); - Text usage = document - .createTextNode(((PHPConstant) bufferobj) - .getDescription()); - node.appendChild(usage); - } - } - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(stream); - - transformer.transform(source, result); - - } catch (ParserConfigurationException e) { - throwWriteException(e); - } catch (TransformerException e) { - throwWriteException(e); - } - // OutputFormat format = new OutputFormat(); - // format.setPreserveSpace(true); - // try { - // Serializer serializer = - // SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, - // format); - // serializer.asDOMSerializer().serialize(document); - // } catch (UnsupportedEncodingException e) { - // } catch (IOException e) { - // } //$NON-NLS-1$ - // // Serializer serializer = - // SerializerFactory.getSerializer().makeSerializer(stream, format); - // //$NON-NLS-1$ - // } catch (ParserConfigurationException e) { - // throwWriteException(e); - // } - } - - private static void throwReadException(Throwable t) throws CoreException { - PHPeclipsePlugin.log(t); - } - - private static void throwWriteException(Throwable t) throws CoreException { - PHPeclipsePlugin.log(t); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java deleted file mode 100644 index 118a77d..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java +++ /dev/null @@ -1,152 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import net.sourceforge.phpdt.internal.corext.phpdoc.PHPDocUtil; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; -import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; -import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; -import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.swt.graphics.Point; - -/** - * Implementation for an ITextHover which hovers over PHP code. - */ -public class PHPTextHover implements ITextHover { - private static HashMap functionDescriptions = null; - - private static HashMap identDescriptions = null; - - /** - * The current project; maybe null for preference pages - */ - private IProject fProject; - - public PHPTextHover(IProject project) { - fProject = project; - } - - /* - * (non-Javadoc) Method declared on ITextHover - */ - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - if (hoverRegion != null) { - try { - if (hoverRegion.getLength() > -1) { - String word = textViewer.getDocument().get( - hoverRegion.getOffset(), hoverRegion.getLength()); - if (functionDescriptions == null) { - functionDescriptions = new HashMap(); - identDescriptions = new HashMap(); - ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData(); - PHPElement elbuffer = null; - if (syntaxbuffer != null) { - for (int i = 0; i < syntaxbuffer.size(); i++) { - elbuffer = (PHPElement) syntaxbuffer.get(i); - if (elbuffer instanceof PHPFunction) { - functionDescriptions.put( - elbuffer.getName(), elbuffer - .getHoverText()); - } else { - identDescriptions.put(elbuffer.getName(), - elbuffer.getHoverText()); - } - } - } - // - // while ((syntaxbuffer != null) - // && (!syntaxbuffer.isEmpty() && ((elbuffer = - // (PHPElement) - // syntaxbuffer.remove(0)) != null))) { - // functionDescriptions.put(elbuffer.getName(), - // elbuffer.getHoverText()); - // } - } - String hoverInfo = (String) identDescriptions.get(word); - if (hoverInfo == null & word.length() > 0) { - hoverInfo = (String) functionDescriptions.get(word - .toLowerCase()); - } - if (hoverInfo == null && fProject != null) { - // get the possible PHPDoc information from the index - // file - IdentifierIndexManager indexManager = WebUI - .getDefault().getIndexManager(fProject); - List list = indexManager.getLocations(word); - if (list.size() > 0) { - try { - PHPIdentifierLocation location; - String filename; - StringBuffer hoverInfoBuffer = new StringBuffer(); - String workspaceLocation; - if (fProject != null) { - workspaceLocation = fProject.getLocation() - .toString() + '/'; - } else { - // should never happen? - workspaceLocation = PHPeclipsePlugin - .getWorkspace().getRoot() - .getLocation().toString(); - } - // boolean foundPHPdoc = false; - for (int i = 0; i < list.size(); i++) { - location = (PHPIdentifierLocation) list - .get(i); - filename = workspaceLocation - + location.getFilename(); - PHPDocUtil.appendPHPDoc(hoverInfoBuffer, - filename, location); - } - hoverInfo = hoverInfoBuffer.toString(); - } catch (Throwable e) { - // ignore exceptions - e.printStackTrace(); - } - } - } - return hoverInfo; - } - // } catch (BadLocationException x) { - } catch (Exception x) { - } - } - return null; - // don't show this annoying text - // return "empty selection"; - } - - /* - * (non-Javadoc) Method declared on ITextHover - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - Point selection = PHPWordExtractor.findWord(textViewer.getDocument(), - offset); - // show the extracted word as a tooltip - if (selection != null && selection.x <= offset - && offset < selection.x + selection.y) - return new Region(selection.x, selection.y); - return new Region(offset, 0); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java deleted file mode 100644 index 370142e..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java +++ /dev/null @@ -1,2781 +0,0 @@ -package net.sourceforge.phpeclipse.phpeditor; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IJavaProject; -import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.ISourceRange; -import net.sourceforge.phpdt.core.ISourceReference; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.JavaModelException; -import net.sourceforge.phpdt.core.dom.CompilationUnit; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; -import net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction; -import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; -import net.sourceforge.phpdt.internal.ui.actions.IndentAction; -import net.sourceforge.phpdt.internal.ui.actions.RemoveBlockCommentAction; -import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference; -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; -import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; -//import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher; -import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager; -import net.sourceforge.phpdt.internal.ui.text.SmartSemicolonAutoEditStrategy; -import net.sourceforge.phpdt.internal.ui.text.comment.CommentFormattingContext; -import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; -import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.actions.GenerateActionGroup; -//import net.sourceforge.phpdt.ui.text.JavaTextTools; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.actions.RTrimAction; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPreferenceStore; -//import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ILineTracker; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextOperationTarget; -import org.eclipse.jface.text.ITextViewerExtension; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.IWidgetTokenKeeper; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.formatter.FormattingContextProperties; -import org.eclipse.jface.text.formatter.IFormattingContext; -import org.eclipse.jface.text.source.IOverviewRuler; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -//incastrix -//import org.eclipse.jface.util.ListenerList; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Point; -//import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.actions.ActionContext; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.dialogs.SaveAsDialog; -import org.eclipse.ui.editors.text.IStorageDocumentProvider; -import org.eclipse.ui.part.FileEditorInput; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.ui.texteditor.ContentAssistAction; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.TextOperationAction; - -/******************************************************************************* - * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Common Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: IBM Corporation - Initial implementation - * www.phpeclipse.de - ******************************************************************************/ -/** - * PHP specific text editor. - */ -public class PHPUnitEditor extends PHPEditor { // implements - // IJavaReconcilingListener { - interface ITextConverter { - void customizeDocumentCommand(IDocument document, - DocumentCommand command); - }; - - // class AdaptedSourceViewer extends JavaSourceViewer { - // private List fTextConverters; - // - // private boolean fIgnoreTextConverters = false; - // - // // private JavaCorrectionAssistant fCorrectionAssistant; - // public AdaptedSourceViewer(Composite parent, IVerticalRuler - // verticalRuler, - // IOverviewRuler overviewRuler, boolean showAnnotationsOverview, - // int styles, IPreferenceStore store) { - // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, - // styles, store); - // } - // - // // public AdaptedSourceViewer(Composite parent, - // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - // // boolean showAnnotationsOverview, int styles) { - // // super(parent, verticalRuler, overviewRuler, - // // showAnnotationsOverview, styles); - // // } - // public IContentAssistant getContentAssistant() { - // return fContentAssistant; - // } - // - // /* - // * @see ITextOperationTarget#doOperation(int) - // */ - // public void doOperation(int operation) { - // if (getTextWidget() == null) - // return; - // switch (operation) { - // case CONTENTASSIST_PROPOSALS: - // String msg = fContentAssistant.showPossibleCompletions(); - // setStatusLineErrorMessage(msg); - // return; - // // case CORRECTIONASSIST_PROPOSALS: - // // fCorrectionAssistant.showPossibleCompletions(); - // // return; - // case UNDO: - // fIgnoreTextConverters = true; - // break; - // case REDO: - // fIgnoreTextConverters = true; - // break; - // } - // super.doOperation(operation); - // } - // - // /* - // * @see ITextOperationTarget#canDoOperation(int) - // */ - // public boolean canDoOperation(int operation) { - // // if (operation == CORRECTIONASSIST_PROPOSALS) - // // return isEditable(); - // return super.canDoOperation(operation); - // } - // - // /* - // * @see TextViewer#handleDispose() - // */ - // protected void handleDispose() { - // // if (fCorrectionAssistant != null) { - // // fCorrectionAssistant.uninstall(); - // // fCorrectionAssistant= null; - // // } - // super.handleDispose(); - // } - // - // public void insertTextConverter(ITextConverter textConverter, int index) - // { - // throw new UnsupportedOperationException(); - // } - // - // public void addTextConverter(ITextConverter textConverter) { - // if (fTextConverters == null) { - // fTextConverters = new ArrayList(1); - // fTextConverters.add(textConverter); - // } else if (!fTextConverters.contains(textConverter)) - // fTextConverters.add(textConverter); - // } - // - // public void removeTextConverter(ITextConverter textConverter) { - // if (fTextConverters != null) { - // fTextConverters.remove(textConverter); - // if (fTextConverters.size() == 0) - // fTextConverters = null; - // } - // } - // - // /* - // * @see TextViewer#customizeDocumentCommand(DocumentCommand) - // */ - // protected void customizeDocumentCommand(DocumentCommand command) { - // super.customizeDocumentCommand(command); - // if (!fIgnoreTextConverters && fTextConverters != null) { - // for (Iterator e = fTextConverters.iterator(); e.hasNext();) - // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), - // command); - // } - // fIgnoreTextConverters = false; - // } - // - // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - // public void updateIndentationPrefixes() { - // SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - // String[] types = configuration.getConfiguredContentTypes(this); - // for (int i = 0; i < types.length; i++) { - // String[] prefixes = configuration.getIndentPrefixes(this, types[i]); - // if (prefixes != null && prefixes.length > 0) - // setIndentPrefixes(prefixes, types[i]); - // } - // } - // - // /* - // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) - // */ - // public boolean requestWidgetToken(IWidgetTokenKeeper requester) { - // if (WorkbenchHelp.isContextHelpDisplayed()) - // return false; - // return super.requestWidgetToken(requester); - // } - // - // // /* - // // * @see - // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) - // // */ - // // public void configure(SourceViewerConfiguration configuration) { - // // super.configure(configuration); - // // // fCorrectionAssistant= new - // // // JavaCorrectionAssistant(CompilationUnitEditor.this); - // // // fCorrectionAssistant.install(this); - // // //TODO install SmartBracesAutoEditStrategy - // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), - // // // IDocument.DEFAULT_CONTENT_TYPE); - // // } - // public void configure(SourceViewerConfiguration configuration) { - // super.configure(configuration); - // // fCorrectionAssistant= new - // JavaCorrectionAssistant(CompilationUnitEditor.this); - // // fCorrectionAssistant.install(this); - // IAutoEditStrategy smartSemi= new - // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING); - // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); - // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); - // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); - // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER); - // } - // }; - class AdaptedSourceViewer extends JavaSourceViewer { - - private List fTextConverters; - - private boolean fIgnoreTextConverters = false; - - // private JavaCorrectionAssistant fCorrectionAssistant; - - public AdaptedSourceViewer(Composite parent, - IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - boolean showAnnotationsOverview, int styles, - IPreferenceStore store) { - super(parent, verticalRuler, overviewRuler, - showAnnotationsOverview, styles, store); - } - - public IContentAssistant getContentAssistant() { - return fContentAssistant; - } - - /* - * @see ITextOperationTarget#doOperation(int) - */ - public void doOperation(int operation) { - - if (getTextWidget() == null) - return; - - switch (operation) { - case CONTENTASSIST_PROPOSALS: - String msg = fContentAssistant.showPossibleCompletions(); - setStatusLineErrorMessage(msg); - return; - // case CORRECTIONASSIST_PROPOSALS: - // msg = fCorrectionAssistant.showPossibleCompletions(); - // setStatusLineErrorMessage(msg); - // return; - case UNDO: - fIgnoreTextConverters = true; - super.doOperation(operation); - fIgnoreTextConverters = false; - return; - case REDO: - fIgnoreTextConverters = true; - super.doOperation(operation); - fIgnoreTextConverters = false; - return; - } - - super.doOperation(operation); - } - - /* - * @see ITextOperationTarget#canDoOperation(int) - */ - public boolean canDoOperation(int operation) { - // if (operation == CORRECTIONASSIST_PROPOSALS) - // return isEditable(); - - return super.canDoOperation(operation); - } - - /* - * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() - * @since 3.0 - */ - public void unconfigure() { - // if (fCorrectionAssistant != null) { - // fCorrectionAssistant.uninstall(); - // fCorrectionAssistant = null; - // } - super.unconfigure(); - } - - public void insertTextConverter(ITextConverter textConverter, int index) { - throw new UnsupportedOperationException(); - } - - public void addTextConverter(ITextConverter textConverter) { - if (fTextConverters == null) { - fTextConverters = new ArrayList(1); - fTextConverters.add(textConverter); - } else if (!fTextConverters.contains(textConverter)) - fTextConverters.add(textConverter); - } - - public void removeTextConverter(ITextConverter textConverter) { - if (fTextConverters != null) { - fTextConverters.remove(textConverter); - if (fTextConverters.size() == 0) - fTextConverters = null; - } - } - - /* - * @see TextViewer#customizeDocumentCommand(DocumentCommand) - */ - protected void customizeDocumentCommand(DocumentCommand command) { - super.customizeDocumentCommand(command); - if (!fIgnoreTextConverters && fTextConverters != null) { - for (Iterator e = fTextConverters.iterator(); e.hasNext();) - ((ITextConverter) e.next()).customizeDocumentCommand( - getDocument(), command); - } - } - - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - public void updateIndentationPrefixes() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - String[] types = configuration.getConfiguredContentTypes(this); - for (int i = 0; i < types.length; i++) { - String[] prefixes = configuration.getIndentPrefixes(this, - types[i]); - if (prefixes != null && prefixes.length > 0) - setIndentPrefixes(prefixes, types[i]); - } - } - - /* - * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) - */ - public boolean requestWidgetToken(IWidgetTokenKeeper requester) { - if (PlatformUI.getWorkbench().getHelpSystem() - .isContextHelpDisplayed()) - return false; - return super.requestWidgetToken(requester); - } - - /* - * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, - * int) - * @since 3.0 - */ - public boolean requestWidgetToken(IWidgetTokenKeeper requester, - int priority) { - if (PlatformUI.getWorkbench().getHelpSystem() - .isContextHelpDisplayed()) - return false; - return super.requestWidgetToken(requester, priority); - } - - /* - * Get the global 'Undo history size' setting - * - */ - protected int getUndoHistorySize () { - IPreferenceStore store= getPreferenceStore (); - - return store != null ? store.getInt("undoHistorySize") : 1000; - } - - - /* - * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) - */ - public void configure(SourceViewerConfiguration configuration) { - super.configure(configuration); - // fCorrectionAssistant = new - // JavaCorrectionAssistant(CompilationUnitEditor.this); - // fCorrectionAssistant.install(this); - IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy( - IPHPPartitions.PHP_PARTITIONING); - prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); - prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); - prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); - prependAutoEditStrategy(smartSemi, - IPHPPartitions.PHP_STRING_HEREDOC); - - fUndoManager.setMaximalUndoLevel (this.getUndoHistorySize ()); // Set every editor to the global 'Undo history size' - } - - /* - * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext() - * @since 3.0 - */ - public IFormattingContext createFormattingContext() { - IFormattingContext context = new CommentFormattingContext(); - - Map preferences; - IJavaElement inputJavaElement = getInputJavaElement(); - IJavaProject javaProject = inputJavaElement != null ? inputJavaElement - .getJavaProject() - : null; - if (javaProject == null) - preferences = new HashMap(JavaCore.getOptions()); - else - preferences = new HashMap(javaProject.getOptions(true)); - - context.storeToMap(PreferenceConstants.getPreferenceStore(), - preferences, false); - context.setProperty( - FormattingContextProperties.CONTEXT_PREFERENCES, - preferences); - - return context; - } - } - - /** - * Remembers data related to the current selection to be able to restore it - * later. - * - * @since 3.0 - */ - private class RememberedSelection { - /** The remembered selection start. */ - private RememberedOffset fStartOffset = new RememberedOffset(); - - /** The remembered selection end. */ - private RememberedOffset fEndOffset = new RememberedOffset(); - - /** - * Remember current selection. - */ - public void remember() { - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method - * may be called inside an async call posted to the UI thread, so - * protect against intermediate disposal of the editor. - */ - ISourceViewer viewer = getSourceViewer(); - if (viewer != null) { - IRegion selection = getSignedSelection(viewer); - int startOffset = selection.getOffset(); - int endOffset = startOffset + selection.getLength(); - - fStartOffset.setOffset(startOffset); - fEndOffset.setOffset(endOffset); - } - } - - /** - * Restore remembered selection. - */ - public void restore() { - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method - * may be called inside an async call posted to the UI thread, so - * protect against intermediate disposal of the editor. - */ - if (getSourceViewer() == null) - return; - - try { - - int startOffset, endOffset; - int revealStartOffset, revealEndOffset; - if (showsHighlightRangeOnly()) { - IJavaElement newStartElement = fStartOffset.getElement(); - startOffset = fStartOffset - .getRememberedOffset(newStartElement); - revealStartOffset = fStartOffset.getRevealOffset( - newStartElement, startOffset); - if (revealStartOffset == -1) - startOffset = -1; - - IJavaElement newEndElement = fEndOffset.getElement(); - endOffset = fEndOffset.getRememberedOffset(newEndElement); - revealEndOffset = fEndOffset.getRevealOffset(newEndElement, - endOffset); - if (revealEndOffset == -1) - endOffset = -1; - } else { - startOffset = fStartOffset.getOffset(); - revealStartOffset = startOffset; - endOffset = fEndOffset.getOffset(); - revealEndOffset = endOffset; - } - - if (startOffset == -1) { - startOffset = endOffset; // fallback to caret offset - revealStartOffset = revealEndOffset; - } - - if (endOffset == -1) { - endOffset = startOffset; // fallback to other offset - revealEndOffset = revealStartOffset; - } - - IJavaElement element; - if (endOffset == -1) { - // fallback to element selection - element = fEndOffset.getElement(); - if (element == null) - element = fStartOffset.getElement(); - if (element != null) - setSelection(element); - return; - } - - if (isValidSelection(revealStartOffset, revealEndOffset - - revealStartOffset) - && isValidSelection(startOffset, endOffset - - startOffset)) - selectAndReveal(startOffset, endOffset - startOffset, - revealStartOffset, revealEndOffset - - revealStartOffset); - } finally { - fStartOffset.clear(); - fEndOffset.clear(); - } - } - - private boolean isValidSelection(int offset, int length) { - IDocumentProvider provider = getDocumentProvider(); - if (provider != null) { - IDocument document = provider.getDocument(getEditorInput()); - if (document != null) { - int end = offset + length; - int documentLength = document.getLength(); - return 0 <= offset && offset <= documentLength && 0 <= end - && end <= documentLength; - } - } - return false; - } - - } - - /** - * Remembers additional data for a given offset to be able restore it later. - * - * @since 3.0 - */ - private class RememberedOffset { - /** Remembered line for the given offset */ - private int fLine; - - /** Remembered column for the given offset */ - private int fColumn; - - /** Remembered Java element for the given offset */ - private IJavaElement fElement; - - /** Remembered Java element line for the given offset */ - private int fElementLine; - - /** - * Store visual properties of the given offset. - * - * @param offset - * Offset in the document - */ - public void setOffset(int offset) { - try { - IDocument document = getSourceViewer().getDocument(); - fLine = document.getLineOfOffset(offset); - fColumn = offset - document.getLineOffset(fLine); - fElement = getElementAt(offset, true); - - fElementLine = -1; - if (fElement instanceof IMember) { - ISourceRange range = ((IMember) fElement).getNameRange(); - if (range != null) - fElementLine = document.getLineOfOffset(range - .getOffset()); - } - if (fElementLine == -1) - fElementLine = document - .getLineOfOffset(getOffset(fElement)); - } catch (BadLocationException e) { - // should not happen - PHPeclipsePlugin.log(e); - clear(); - } catch (JavaModelException e) { - // should not happen - PHPeclipsePlugin.log(e.getStatus()); - clear(); - } - } - - /** - * Return offset recomputed from stored visual properties. - * - * @return Offset in the document - */ - public int getOffset() { - IJavaElement newElement = getElement(); - - int offset = getRememberedOffset(newElement); - - if (offset != -1 && !containsOffset(newElement, offset) - && (offset == 0 || !containsOffset(newElement, offset - 1))) - return -1; - - return offset; - } - - /** - * Return offset recomputed from stored visual properties. - * - * @param newElement - * Enclosing element - * @return Offset in the document - */ - public int getRememberedOffset(IJavaElement newElement) { - try { - if (newElement == null) - return -1; - - IDocument document = getSourceViewer().getDocument(); - int newElementLine = -1; - if (newElement instanceof IMember) { - ISourceRange range = ((IMember) newElement).getNameRange(); - if (range != null) - newElementLine = document.getLineOfOffset(range - .getOffset()); - } - if (newElementLine == -1) - newElementLine = document - .getLineOfOffset(getOffset(newElement)); - if (newElementLine == -1) - return -1; - - int newLine = fLine + newElementLine - fElementLine; - if (newLine < 0 || newLine >= document.getNumberOfLines()) - return -1; - int maxColumn = document.getLineLength(newLine); - String lineDelimiter = document.getLineDelimiter(newLine); - if (lineDelimiter != null) - maxColumn = maxColumn - lineDelimiter.length(); - int offset; - if (fColumn > maxColumn) - offset = document.getLineOffset(newLine) + maxColumn; - else - offset = document.getLineOffset(newLine) + fColumn; - - return offset; - } catch (BadLocationException e) { - // should not happen - PHPeclipsePlugin.log(e); - return -1; - } catch (JavaModelException e) { - // should not happen - PHPeclipsePlugin.log(e.getStatus()); - return -1; - } - } - - /** - * Returns the offset used to reveal the given element based on the - * given selection offset. - * - * @param element - * the element - * @param offset - * the selection offset - * @return the offset to reveal the given element based on the given - * selection offset - */ - public int getRevealOffset(IJavaElement element, int offset) { - if (element == null || offset == -1) - return -1; - - if (containsOffset(element, offset)) { - if (offset > 0) { - IJavaElement alternateElement = getElementAt(offset, false); - if (element.getHandleIdentifier().equals( - alternateElement.getParent().getHandleIdentifier())) - return offset - 1; // Solves test case 2 from - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 - } - return offset; - } else if (offset > 0 && containsOffset(element, offset - 1)) - return offset - 1; // Solves test case 1 from - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 - - return -1; - } - - /** - * Return Java element recomputed from stored visual properties. - * - * @return Java element - */ - public IJavaElement getElement() { - if (fElement == null) - return null; - - return findElement(fElement); - } - - /** - * Clears the stored position - */ - public void clear() { - fLine = -1; - fColumn = -1; - fElement = null; - fElementLine = -1; - } - - /** - * Does the given Java element contain the given offset? - * - * @param element - * Java element - * @param offset - * Offset - * @return true iff the Java element contains the offset - */ - private boolean containsOffset(IJavaElement element, int offset) { - int elementOffset = getOffset(element); - int elementLength = getLength(element); - return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset - + elementLength) - : false; - } - - /** - * Returns the offset of the given Java element. - * - * @param element - * Java element - * @return Offset of the given Java element - */ - private int getOffset(IJavaElement element) { - if (element instanceof ISourceReference) { - ISourceReference sr = (ISourceReference) element; - try { - ISourceRange srcRange = sr.getSourceRange(); - if (srcRange != null) - return srcRange.getOffset(); - } catch (JavaModelException e) { - } - } - return -1; - } - - /** - * Returns the length of the given Java element. - * - * @param element - * Java element - * @return Length of the given Java element - */ - private int getLength(IJavaElement element) { - if (element instanceof ISourceReference) { - ISourceReference sr = (ISourceReference) element; - try { - ISourceRange srcRange = sr.getSourceRange(); - if (srcRange != null) - return srcRange.getLength(); - } catch (JavaModelException e) { - } - } - return -1; - } - - /** - * Returns the updated java element for the old java element. - * - * @param element - * Old Java element - * @return Updated Java element - */ - private IJavaElement findElement(IJavaElement element) { - - if (element == null) - return null; - - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); - - if (unit != null) { - try { - - synchronized (unit) { - // unit.reconcile(ICompilationUnit.NO_AST, false, null, - // null); - unit.reconcile(); - } - IJavaElement[] findings = unit.findElements(element); - if (findings != null && findings.length > 0) - return findings[0]; - - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - } - - return null; - } - - } - - static class TabConverter implements ITextConverter { - private int fTabRatio; - - private ILineTracker fLineTracker; - - public TabConverter() { - } - - public void setNumberOfSpacesPerTab(int ratio) { - fTabRatio = ratio; - } - - public void setLineTracker(ILineTracker lineTracker) { - fLineTracker = lineTracker; - } - - private int insertTabString(StringBuffer buffer, int offsetInLine) { - if (fTabRatio == 0) - return 0; - int remainder = offsetInLine % fTabRatio; - remainder = fTabRatio - remainder; - for (int i = 0; i < remainder; i++) - buffer.append(' '); - return remainder; - } - - public void customizeDocumentCommand(IDocument document, - DocumentCommand command) { - String text = command.text; - if (text == null) - return; - int index = text.indexOf('\t'); - if (index > -1) { - StringBuffer buffer = new StringBuffer(); - fLineTracker.set(command.text); - int lines = fLineTracker.getNumberOfLines(); - try { - for (int i = 0; i < lines; i++) { - int offset = fLineTracker.getLineOffset(i); - int endOffset = offset + fLineTracker.getLineLength(i); - String line = text.substring(offset, endOffset); - int position = 0; - if (i == 0) { - IRegion firstLine = document - .getLineInformationOfOffset(command.offset); - position = command.offset - firstLine.getOffset(); - } - int length = line.length(); - for (int j = 0; j < length; j++) { - char c = line.charAt(j); - if (c == '\t') { - position += insertTabString(buffer, position); - } else { - buffer.append(c); - ++position; - } - } - } - command.text = buffer.toString(); - } catch (BadLocationException x) { - } - } - } - }; - - private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { - final char fExitCharacter; - - public ExitPolicy(char exitCharacter) { - fExitCharacter = exitCharacter; - } - - /* - * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager, - * org.eclipse.swt.events.VerifyEvent, int, int) - */ - public ExitFlags doExit(LinkedPositionManager manager, - VerifyEvent event, int offset, int length) { - if (event.character == fExitCharacter) { - if (manager.anyPositionIncludes(offset, length)) - return new ExitFlags(LinkedPositionUI.COMMIT - | LinkedPositionUI.UPDATE_CARET, false); - else - return new ExitFlags(LinkedPositionUI.COMMIT, true); - } - // Fix for #1380415 (toshihiro) start - switch (event.keyCode) { - case SWT.ARROW_UP: - case SWT.ARROW_DOWN: - return new ExitFlags(LinkedPositionUI.COMMIT, true); - case SWT.ARROW_LEFT: - case SWT.ARROW_RIGHT: - if (!manager.anyPositionIncludes(offset, length)) - return new ExitFlags(LinkedPositionUI.COMMIT, true); - break; - } - // #1380415 end - switch (event.character) { - case '\b': - if (manager.getFirstPosition().length == 0) - return new ExitFlags(0, false); - else - return null; - case '\n': - case '\r': - return new ExitFlags(LinkedPositionUI.COMMIT, true); - default: - return null; - } - } - } - -// private static class BracketLevel { -// int fOffset; -// -// int fLength; -// -// LinkedPositionManager fManager; -// -// LinkedPositionUI fEditor; -// }; - - private class BracketInserter implements VerifyKeyListener, - LinkedPositionUI.ExitListener { - private boolean fCloseBracketsPHP = true; - - private boolean fCloseStringsPHPDQ = true; - - private boolean fCloseStringsPHPSQ = true; - - private int fOffset; - - private int fLength; - - public void setCloseBracketsPHPEnabled(boolean enabled) { - fCloseBracketsPHP = enabled; - } - - public void setCloseStringsPHPDQEnabled(boolean enabled) { - fCloseStringsPHPDQ = enabled; - } - - public void setCloseStringsPHPSQEnabled(boolean enabled) { - fCloseStringsPHPSQ = enabled; - } - - private boolean hasIdentifierToTheRight(IDocument document, int offset) { - try { - int end = offset; - IRegion endLine = document.getLineInformationOfOffset(end); - int maxEnd = endLine.getOffset() + endLine.getLength(); - while (end != maxEnd - && Character.isWhitespace(document.getChar(end))) - ++end; - return end != maxEnd - && Scanner.isPHPIdentifierPart(document.getChar(end)); - } catch (BadLocationException e) { - // be conservative - return true; - } - } - -// private boolean hasIdentifierToTheLeft(IDocument document, int offset) { -// try { -// int start = offset; -// IRegion startLine = document.getLineInformationOfOffset(start); -// int minStart = startLine.getOffset(); -// while (start != minStart -// && Character.isWhitespace(document.getChar(start - 1))) -// --start; -// return start != minStart -// && Scanner.isPHPIdentifierPart(document -// .getChar(start - 1)); -// } catch (BadLocationException e) { -// return true; -// } -// } - - private boolean hasCharacterToTheLeft(IDocument document, int offset, - char character) { - try { - int start = offset; - IRegion startLine = document.getLineInformationOfOffset(start); - int minStart = startLine.getOffset(); - while (start != minStart - && Character.isWhitespace(document.getChar(start - 1))) - --start; - return start != minStart - && document.getChar(start - 1) == character; - } catch (BadLocationException e) { - return false; - } - } - - private boolean hasCharacterToTheRight(IDocument document, int offset, - char character) { - try { - int end = offset; - IRegion endLine = document.getLineInformationOfOffset(end); - int maxEnd = endLine.getOffset() + endLine.getLength(); - while (end != maxEnd - && Character.isWhitespace(document.getChar(end))) - ++end; - return end != maxEnd && document.getChar(end) == character; - } catch (BadLocationException e) { - // be conservative - return true; - } - } - - /* - * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) - */ - public void verifyKey(VerifyEvent event) { - if (!event.doit) - return; - final ISourceViewer sourceViewer = getSourceViewer(); - IDocument document = sourceViewer.getDocument(); - final Point selection = sourceViewer.getSelectedRange(); - final int offset = selection.x; - final int length = selection.y; - try { - ITypedRegion partition = document.getPartition(offset); - String type = partition.getType(); - if (type.equals(IPHPPartitions.PHP_PARTITIONING) - || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) { - // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP - // and HTML area - switch (event.character) { - case '(': - if (hasCharacterToTheRight(document, offset + length, - '(')) - return; - // fall through - case '[': - if (!fCloseBracketsPHP) - return; - if (hasIdentifierToTheRight(document, offset + length)) - return; - // fall through - case '{': - if (!fCloseBracketsPHP) - return; - if (hasIdentifierToTheRight(document, offset + length)) - return; - // fall through - case '"': - if (event.character == '"') { - if (!fCloseStringsPHPDQ) - return; - // changed for statements like echo "" print "" - // if (hasIdentifierToTheLeft(document, offset) - // || - // hasIdentifierToTheRight(document, offset + - // length)) - if (hasIdentifierToTheRight(document, offset - + length)) - return; - } - // ITypedRegion partition= - // document.getPartition(offset); - // if (! - // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) - // && - // (partition.getOffset() != offset)) - // return; - final char characterDQ = event.character; - final char closingCharacterDQ = getPeerCharacter(characterDQ); - final StringBuffer bufferDQ = new StringBuffer(); - bufferDQ.append(characterDQ); - bufferDQ.append(closingCharacterDQ); - document.replace(offset, length, bufferDQ.toString()); - LinkedPositionManager managerDQ = new LinkedPositionManager( - document); - managerDQ.addPosition(offset + 1, 0); - fOffset = offset; - fLength = 2; - LinkedPositionUI editorDQ = new LinkedPositionUI( - sourceViewer, managerDQ); - editorDQ.setCancelListener(this); - editorDQ.setExitPolicy(new ExitPolicy( - closingCharacterDQ)); - editorDQ.setFinalCaretOffset(offset + 2); - editorDQ.enter(); - IRegion newSelectionDQ = editorDQ.getSelectedRegion(); - sourceViewer.setSelectedRange(newSelectionDQ - .getOffset(), newSelectionDQ.getLength()); - event.doit = false; - break; - case '\'': - if (event.character == '\'') { - if (!fCloseStringsPHPSQ) - return; - // changed for statements like echo "" print "" - // if (hasIdentifierToTheLeft(document, offset) - // || - // hasIdentifierToTheRight(document, offset + - // length)) - if (hasIdentifierToTheRight(document, offset - + length)) - return; - } - // ITypedRegion partition= - // document.getPartition(offset); - // if (! - // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) - // && - // (partition.getOffset() != offset)) - // return; - final char characterSQ = event.character; - final char closingCharacterSQ = getPeerCharacter(characterSQ); - final StringBuffer bufferSQ = new StringBuffer(); - bufferSQ.append(characterSQ); - bufferSQ.append(closingCharacterSQ); - document.replace(offset, length, bufferSQ.toString()); - LinkedPositionManager managerSQ = new LinkedPositionManager( - document); - managerSQ.addPosition(offset + 1, 0); - fOffset = offset; - fLength = 2; - LinkedPositionUI editorSQ = new LinkedPositionUI( - sourceViewer, managerSQ); - editorSQ.setCancelListener(this); - editorSQ.setExitPolicy(new ExitPolicy( - closingCharacterSQ)); - editorSQ.setFinalCaretOffset(offset + 2); - editorSQ.enter(); - IRegion newSelectionSQ = editorSQ.getSelectedRegion(); - sourceViewer.setSelectedRange(newSelectionSQ - .getOffset(), newSelectionSQ.getLength()); - event.doit = false; - case '\r': { // insert linebreaks and new closing brace - // after brace and return - if (!fCloseBracketsPHP) { - return; - } - if (hasCharacterToTheLeft(document, offset, '{') - && hasCharacterToTheRight(document, offset, '}')) { - String lineDelimiter = StubUtility - .getLineDelimiterFor(document); - int caretPos = sourceViewer.getTextWidget() - .getCaretOffset(); - final StringBuffer buffer = new StringBuffer( - lineDelimiter); - // get indentation - IRegion line = document - .getLineInformationOfOffset(offset); - String currentLine = document.get(line.getOffset(), - line.getLength()); - int index = 0; - int max = currentLine.length(); - StringBuffer indent = new StringBuffer(); - while (index < max - && Character.isWhitespace(currentLine - .charAt(index))) { - indent.append(currentLine.charAt(index)); - index++; - } - buffer.append(indent); - JavaHeuristicScanner scanner = new JavaHeuristicScanner( - document); - JavaIndenter indenter = new JavaIndenter(document, - scanner); - buffer.append(indenter.createIndent(1)); - int cursorPos = buffer.length(); - buffer.append(lineDelimiter); - buffer.append(indent); - document.replace(offset, length, buffer.toString()); - sourceViewer.getTextWidget().setCaretOffset( - caretPos + cursorPos); - event.doit = false; - } - } - } - } - } catch (BadLocationException e) { - } - } - - /* - * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) - */ - public void exit(boolean accept) { - if (accept) - return; - // remove brackets - try { - final ISourceViewer sourceViewer = getSourceViewer(); - IDocument document = sourceViewer.getDocument(); - document.replace(fOffset, fLength, null); - } catch (BadLocationException e) { - } - } - } - - /** The editor's save policy */ - protected ISavePolicy fSavePolicy; - - /** - * Listener to annotation model changes that updates the error tick in the - * tab image - */ - private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; - - /** The editor's paint manager */ - // private PaintManager fPaintManager; - /** The editor's bracket painter */ - // private BracketPainter fBracketPainter; - /** The editor's bracket matcher */ - //private PHPPairMatcher fBracketMatcher; - - /** The editor's line painter */ - // private LinePainter fLinePainter; - /** The editor's print margin ruler painter */ - // private PrintMarginPainter fPrintMarginPainter; - /** The editor's problem painter */ - // private ProblemPainter fProblemPainter; - /** The editor's tab converter */ - private TabConverter fTabConverter; - - /** History for structure select action */ - // private SelectionHistory fSelectionHistory; - /** The preference property change listener for php core. */ - // private IPropertyChangeListener fPropertyChangeListener = new - // PropertyChangeListener(); - /** The remembered java element */ - //private IJavaElement fRememberedElement; - - /** - * The remembered selection. - * - * @since 3.0 - */ - private RememberedSelection fRememberedSelection = new RememberedSelection(); - - /** The remembered php element offset */ - //private int fRememberedElementOffset; - - /** The bracket inserter. */ - private BracketInserter fBracketInserter = new BracketInserter(); - - /** The standard action groups added to the menu */ - private GenerateActionGroup fGenerateActionGroup; - - private CompositeActionGroup fContextMenuGroup; - - // private class PropertyChangeListener implements IPropertyChangeListener { - // /* - // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - // */ - // public void - // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent - // event) { - // handlePreferencePropertyChanged(event); - // } - // } - /* Preference key for code formatter tab size */ - private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; - - /** Preference key for matching brackets */ - // private final static String MATCHING_BRACKETS = - // PreferenceConstants.EDITOR_MATCHING_BRACKETS; - /** Preference key for matching brackets color */ - // private final static String MATCHING_BRACKETS_COLOR = - // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; - /** Preference key for highlighting current line */ - // private final static String CURRENT_LINE = - // PreferenceConstants.EDITOR_CURRENT_LINE; - /** Preference key for highlight color of current line */ - // private final static String CURRENT_LINE_COLOR = - // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; - /** Preference key for showing print marging ruler */ - // private final static String PRINT_MARGIN = - // PreferenceConstants.EDITOR_PRINT_MARGIN; - /** Preference key for print margin ruler color */ - // private final static String PRINT_MARGIN_COLOR = - // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; - /** Preference key for print margin ruler column */ - // private final static String PRINT_MARGIN_COLUMN = - // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; - /** Preference key for inserting spaces rather than tabs */ - private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; - - /** Preference key for error indication */ - // private final static String ERROR_INDICATION = - // PreferenceConstants.EDITOR_PROBLEM_INDICATION; - /** Preference key for error color */ - // private final static String ERROR_INDICATION_COLOR = - // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; - /** Preference key for warning indication */ - // private final static String WARNING_INDICATION = - // PreferenceConstants.EDITOR_WARNING_INDICATION; - /** Preference key for warning color */ - // private final static String WARNING_INDICATION_COLOR = - // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; - /** Preference key for task indication */ - //private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; - - /** Preference key for task color */ - //private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; - - /** Preference key for bookmark indication */ - //private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; - - /** Preference key for bookmark color */ - //private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; - - /** Preference key for search result indication */ - //private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; - - /** Preference key for search result color */ - //private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; - - /** Preference key for unknown annotation indication */ - //private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; - - /** Preference key for unknown annotation color */ - //private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; - - /** Preference key for linked position color */ - //private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR; - - /** Preference key for shwoing the overview ruler */ - //private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; - - /** Preference key for error indication in overview ruler */ - //private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for warning indication in overview ruler */ - //private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for task indication in overview ruler */ - //private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for bookmark indication in overview ruler */ - //private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for search result indication in overview ruler */ - //private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for unknown annotation indication in overview ruler */ - //private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; - - /** Preference key for automatically closing double quoted strings */ - private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP; - - /** Preference key for automatically closing single quoted strings */ - private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP; - - /** Preference key for automatically wrapping Java strings */ - // private final static String WRAP_STRINGS = - // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ; - /** Preference key for automatically closing brackets and parenthesis */ - private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP; - - /** Preference key for automatically closing phpdocs and comments */ - //private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS; - - /** Preference key for automatically adding phpdoc tags */ - //private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS; - - /** Preference key for automatically formatting phpdocs */ - // private final static String FORMAT_JAVADOCS = - // PreferenceConstants.EDITOR_FORMAT_JAVADOCS; - /** Preference key for automatically closing strings */ - //private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML; - - /** Preference key for automatically closing brackets and parenthesis */ - //private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML; - - /** Preference key for smart paste */ - //private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE; - - // private final static class AnnotationInfo { - // public String fColorPreference; - // public String fOverviewRulerPreference; - // public String fEditorPreference; - // }; - // private final static Map ANNOTATION_MAP; - // static { - // - // AnnotationInfo info; - // ANNOTATION_MAP = new HashMap(); - // - // info = new AnnotationInfo(); - // info.fColorPreference = TASK_INDICATION_COLOR; - // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = TASK_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.TASK, info); - // - // info = new AnnotationInfo(); - // info.fColorPreference = ERROR_INDICATION_COLOR; - // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = ERROR_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.ERROR, info); - // - // info = new AnnotationInfo(); - // info.fColorPreference = WARNING_INDICATION_COLOR; - // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = WARNING_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.WARNING, info); - // - // info = new AnnotationInfo(); - // info.fColorPreference = BOOKMARK_INDICATION_COLOR; - // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = BOOKMARK_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info); - // - // info = new AnnotationInfo(); - // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR; - // info.fOverviewRulerPreference = - // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = SEARCH_RESULT_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.SEARCH, info); - // - // info = new AnnotationInfo(); - // info.fColorPreference = UNKNOWN_INDICATION_COLOR; - // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER; - // info.fEditorPreference = UNKNOWN_INDICATION; - // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info); - // }; - // - // private final static AnnotationType[] ANNOTATION_LAYERS = - // new AnnotationType[] { - // AnnotationType.UNKNOWN, - // AnnotationType.BOOKMARK, - // AnnotationType.TASK, - // AnnotationType.SEARCH, - // AnnotationType.WARNING, - // AnnotationType.ERROR }; - /** - * Creates a new php unit editor. - */ - - /** - * Reconciling listeners. - * - * @since 3.0 - */ - private ListenerList fReconcilingListeners = new ListenerList(); - - /** - * Mutex for the reconciler. See - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of - * the problem. - *

- * TODO remove once the underlying problem is solved. - *

- */ - private final Object fReconcilerLock = new Object(); - - public PHPUnitEditor() { - super(); - setDocumentProvider(WebUI.getDefault() - .getCompilationUnitDocumentProvider()); - setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$ - setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$ - setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$ - // don't set help contextId, we install our own help context - fSavePolicy = null; - fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this); - } - - /* - * @see AbstractTextEditor#createActions() - */ - protected void createActions() { - super.createActions(); - Action action; - // Action action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); - // //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); - // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ - // markAsStateDependentAction("CorrectionAssistProposal", true); - // //$NON-NLS-1$ - // // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.QUICK_FIX_ACTION); - action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(), - "ContentAssistProposal.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.CONTENT_ASSIST_ACTION); - // action = new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "ContentAssistContextInformation.", this, - // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); - // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ - // markAsStateDependentAction("ContentAssistContextInformation", true); - // //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); - // action= new - // TextOperationAction(PHPEditorMessages.getResourceBundle(), - // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); - // //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX); - // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$ - // markAsStateDependentAction("ContentAssistCompletePrefix", true); - // //$NON-NLS-1$ - // // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), - "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT); - setAction("Comment", action); //$NON-NLS-1$ - markAsStateDependentAction("Comment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), - "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT); - setAction("Uncomment", action); //$NON-NLS-1$ - markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); - - action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(), - "ToggleComment.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT); - setAction("ToggleComment", action); //$NON-NLS-1$ - markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION); - configureToggleCommentAction(); - - action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), - "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT); - setAction("Format", action); //$NON-NLS-1$ - markAsStateDependentAction("Format", true); //$NON-NLS-1$ - markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); - - // action = new - // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(), - // "AddBlockComment.", this); //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); - // setAction("AddBlockComment", action); //$NON-NLS-1$ - // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("AddBlockComment", true); - // //$NON-NLS-1$ - // // WorkbenchHelp.setHelp(action, - // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - // action = new RemoveBlockCommentAction( - // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); - // //$NON-NLS-1$ - // action - // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); - // setAction("RemoveBlockComment", action); //$NON-NLS-1$ - // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("RemoveBlockComment", true); - // //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - action = new IndentAction(PHPEditorMessages.getResourceBundle(), - "Indent.", this, false); //$NON-NLS-1$ - action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); - setAction("Indent", action); //$NON-NLS-1$ - markAsStateDependentAction("Indent", true); //$NON-NLS-1$ - markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); - // - // action= new IndentAction(PHPEditorMessages.getResourceBundle(), - // "Indent.", this, true); //$NON-NLS-1$ - // setAction("IndentOnTab", action); //$NON-NLS-1$ - // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ - // - - action = new AddBlockCommentAction(PHPEditorMessages - .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); - setAction("AddBlockComment", action); //$NON-NLS-1$ - markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ - markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); - - action = new RemoveBlockCommentAction(PHPEditorMessages - .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); - setAction("RemoveBlockComment", action); //$NON-NLS-1$ - markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ - // WorkbenchHelp.setHelp(action, - // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); - - // action= new IndentAction(PHPEditorMessages.getResourceBundle(), - // "Indent.", this, false); //$NON-NLS-1$ - // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); - // setAction("Indent", action); //$NON-NLS-1$ - // markAsStateDependentAction("Indent", true); //$NON-NLS-1$ - // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ - // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); - // - action = new IndentAction(PHPEditorMessages.getResourceBundle(), - "Indent.", this, true); //$NON-NLS-1$ - setAction("IndentOnTab", action); //$NON-NLS-1$ - markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ - markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ - - if (getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_SMART_TAB)) { - // don't replace Shift Right - have to make sure their enablement is - // mutually exclusive - // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); - setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ - } - fGenerateActionGroup = new GenerateActionGroup(this, - ITextEditorActionConstants.GROUP_EDIT); - // ActionGroup rg= new RefactorActionGroup(this, - // ITextEditorActionConstants.GROUP_EDIT); - - // fActionGroups.addGroup(rg); - fActionGroups.addGroup(fGenerateActionGroup); - - // We have to keep the context menu group separate to have better - // control over positioning - fContextMenuGroup = new CompositeActionGroup( - new ActionGroup[] { fGenerateActionGroup - // rg, - // new LocalHistoryActionGroup(this, - // ITextEditorActionConstants.GROUP_EDIT) - }); - - } - - /* - * @see JavaEditor#getElementAt(int) - */ - protected IJavaElement getElementAt(int offset) { - return getElementAt(offset, true); - } - - /** - * Returns the most narrow element including the given offset. If - * reconcile is true the editor's input - * element is reconciled in advance. If it is false this - * method only returns a result if the editor's input element does not need - * to be reconciled. - * - * @param offset - * the offset included by the retrieved element - * @param reconcile - * true if working copy should be reconciled - */ - protected IJavaElement getElementAt(int offset, boolean reconcile) { - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); - if (unit != null) { - try { - if (reconcile) { - synchronized (unit) { - unit.reconcile(); - } - return unit.getElementAt(offset); - } else if (unit.isConsistent()) - return unit.getElementAt(offset); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - } - return null; - } - - /* - * @see JavaEditor#getCorrespondingElement(IJavaElement) - */ - protected IJavaElement getCorrespondingElement(IJavaElement element) { - try { - return EditorUtility.getWorkingCopy(element, true); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x.getStatus()); - // nothing found, be tolerant and go on - } - return null; - } - - public void createPartControl(Composite parent) { - super.createPartControl(parent); - // fPaintManager = new PaintManager(getSourceViewer()); - LinePainter linePainter; - linePainter = new LinePainter(getSourceViewer()); - linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235, - 224)); - // fPaintManager.addPainter(linePainter); - // if (isBracketHighlightingEnabled()) - // startBracketHighlighting(); - // if (isLineHighlightingEnabled()) - // startLineHighlighting(); - // if (isPrintMarginVisible()) - // showPrintMargin(); - // Iterator e = ANNOTATION_MAP.keySet().iterator(); - // while (e.hasNext()) { - // AnnotationType type = (AnnotationType) e.next(); - // if (isAnnotationIndicationEnabled(type)) - // startAnnotationIndication(type); - // } - if (isTabConversionEnabled()) - startTabConversion(); - // if (isOverviewRulerVisible()) - // showOverviewRuler(); - // - // Preferences preferences = - // PHPeclipsePlugin.getDefault().getPluginPreferences(); - // preferences.addPropertyChangeListener(fPropertyChangeListener); - IPreferenceStore preferenceStore = getPreferenceStore(); - boolean closeBracketsPHP = preferenceStore - .getBoolean(CLOSE_BRACKETS_PHP); - boolean closeStringsPHPDQ = preferenceStore - .getBoolean(CLOSE_STRINGS_DQ_PHP); - boolean closeStringsPHPSQ = preferenceStore - .getBoolean(CLOSE_STRINGS_SQ_PHP); - fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP); - fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ); - fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ); - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension) - ((ITextViewerExtension) sourceViewer) - .prependVerifyKeyListener(fBracketInserter); - } - - private static char getPeerCharacter(char character) { - switch (character) { - case '(': - return ')'; - case ')': - return '('; - case '[': - return ']'; - case ']': - return '['; - case '"': - return character; - case '\'': - return character; - case '{': - return '}'; - default: - throw new IllegalArgumentException(); - } - } - - // private void startBracketHighlighting() { - // if (fBracketPainter == null) { - // ISourceViewer sourceViewer = getSourceViewer(); - // fBracketPainter = new BracketPainter(sourceViewer); - // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); - // // fPaintManager.addPainter(fBracketPainter); - // } - // } - // - // private void stopBracketHighlighting() { - // if (fBracketPainter != null) { - // // fPaintManager.removePainter(fBracketPainter); - // fBracketPainter.deactivate(true); - // fBracketPainter.dispose(); - // fBracketPainter = null; - // } - // } - - // private boolean isBracketHighlightingEnabled() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(MATCHING_BRACKETS); - // } - - // private void startLineHighlighting() { - // if (fLinePainter == null) { - // ISourceViewer sourceViewer = getSourceViewer(); - // fLinePainter = new LinePainter(sourceViewer); - // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); - // // fPaintManager.addPainter(fLinePainter); - // } - // } - - // private void stopLineHighlighting() { - // if (fLinePainter != null) { - // // fPaintManager.removePainter(fLinePainter); - // fLinePainter.deactivate(true); - // fLinePainter.dispose(); - // fLinePainter = null; - // } - // } - - // private boolean isLineHighlightingEnabled() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(CURRENT_LINE); - // } - - // private void showPrintMargin() { - // if (fPrintMarginPainter == null) { - // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer()); - // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); - // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); - // // fPaintManager.addPainter(fPrintMarginPainter); - // } - // } - - // private void hidePrintMargin() { - // if (fPrintMarginPainter != null) { - // // fPaintManager.removePainter(fPrintMarginPainter); - // fPrintMarginPainter.deactivate(true); - // fPrintMarginPainter.dispose(); - // fPrintMarginPainter = null; - // } - // } - - // private boolean isPrintMarginVisible() { - // IPreferenceStore store = getPreferenceStore(); - // return store.getBoolean(PRINT_MARGIN); - // } - - private int getTabSize() { - Preferences preferences = PHPeclipsePlugin.getDefault() - .getPluginPreferences(); - return preferences.getInt(CODE_FORMATTER_TAB_SIZE); - } - - private boolean isTabConversionEnabled() { - IPreferenceStore store = getPreferenceStore(); - return store.getBoolean(SPACES_FOR_TABS); - } - -// private Color getColor(String key) { -// RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key); -// return getColor(rgb); -// } - -// private Color getColor(RGB rgb) { -// JavaTextTools textTools = WebUI.getDefault() -// .getJavaTextTools(); -// return textTools.getColorManager().getColor(rgb); -// } - - // private Color getColor(AnnotationType annotationType) { - // AnnotationInfo info = (AnnotationInfo) - // ANNOTATION_MAP.get(annotationType); - // if (info != null) - // return getColor(info.fColorPreference); - // return null; - // } - public void dispose() { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension) - ((ITextViewerExtension) sourceViewer) - .removeVerifyKeyListener(fBracketInserter); - // if (fPropertyChangeListener != null) { - // Preferences preferences = - // PHPeclipsePlugin.getDefault().getPluginPreferences(); - // preferences.removePropertyChangeListener(fPropertyChangeListener); - // fPropertyChangeListener = null; - // } - if (fJavaEditorErrorTickUpdater != null) { - fJavaEditorErrorTickUpdater.dispose(); - fJavaEditorErrorTickUpdater = null; - } - // if (fSelectionHistory != null) - // fSelectionHistory.dispose(); - // if (fPaintManager != null) { - // fPaintManager.dispose(); - // fPaintManager = null; - // } - if (fActionGroups != null) { - fActionGroups.dispose(); - fActionGroups = null; - } - super.dispose(); - } - - // protected AnnotationType getAnnotationType(String preferenceKey) { - // Iterator e = ANNOTATION_MAP.keySet().iterator(); - // while (e.hasNext()) { - // AnnotationType type = (AnnotationType) e.next(); - // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type); - // if (info != null) { - // if (preferenceKey.equals(info.fColorPreference) - // || preferenceKey.equals(info.fEditorPreference) - // || preferenceKey.equals(info.fOverviewRulerPreference)) - // return type; - // } - // } - // return null; - // } - /* - * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) - */ - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - try { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - if (asv != null) { - String p = event.getProperty(); - if (CLOSE_BRACKETS_PHP.equals(p)) { - fBracketInserter - .setCloseBracketsPHPEnabled(getPreferenceStore() - .getBoolean(p)); - return; - } - if (CLOSE_STRINGS_DQ_PHP.equals(p)) { - fBracketInserter - .setCloseStringsPHPDQEnabled(getPreferenceStore() - .getBoolean(p)); - return; - } - if (CLOSE_STRINGS_SQ_PHP.equals(p)) { - fBracketInserter - .setCloseStringsPHPSQEnabled(getPreferenceStore() - .getBoolean(p)); - return; - } - if (SPACES_FOR_TABS.equals(p)) { - if (isTabConversionEnabled()) - startTabConversion(); - else - stopTabConversion(); - return; - } - // if (MATCHING_BRACKETS.equals(p)) { - // if (isBracketHighlightingEnabled()) - // startBracketHighlighting(); - // else - // stopBracketHighlighting(); - // return; - // } - // if (MATCHING_BRACKETS_COLOR.equals(p)) { - // if (fBracketPainter != null) - // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); - // return; - // } - // if (CURRENT_LINE.equals(p)) { - // if (isLineHighlightingEnabled()) - // startLineHighlighting(); - // else - // stopLineHighlighting(); - // return; - // } - // if (CURRENT_LINE_COLOR.equals(p)) { - // if (fLinePainter != null) { - // stopLineHighlighting(); - // startLineHighlighting(); - // } - // return; - // } - // if (PRINT_MARGIN.equals(p)) { - // if (isPrintMarginVisible()) - // showPrintMargin(); - // else - // hidePrintMargin(); - // return; - // } - // if (PRINT_MARGIN_COLOR.equals(p)) { - // if (fPrintMarginPainter != null) - // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); - // return; - // } - // if (PRINT_MARGIN_COLUMN.equals(p)) { - // if (fPrintMarginPainter != null) - // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); - // return; - // } - // if (OVERVIEW_RULER.equals(p)) { - // if (isOverviewRulerVisible()) - // showOverviewRuler(); - // else - // hideOverviewRuler(); - // return; - // } - // AnnotationType type = getAnnotationType(p); - // if (type != null) { - // - // AnnotationInfo info = (AnnotationInfo) - // ANNOTATION_MAP.get(type); - // if (info.fColorPreference.equals(p)) { - // Color color = getColor(type); - // if (fProblemPainter != null) { - // fProblemPainter.setColor(type, color); - // fProblemPainter.paint(IPainter.CONFIGURATION); - // } - // setColorInOverviewRuler(type, color); - // return; - // } - // - // if (info.fEditorPreference.equals(p)) { - // if (isAnnotationIndicationEnabled(type)) - // startAnnotationIndication(type); - // else - // stopAnnotationIndication(type); - // return; - // } - // - // if (info.fOverviewRulerPreference.equals(p)) { - // if (isAnnotationIndicationInOverviewRulerEnabled(type)) - // showAnnotationIndicationInOverviewRuler(type, true); - // else - // showAnnotationIndicationInOverviewRuler(type, false); - // return; - // } - // } - IContentAssistant c = asv.getContentAssistant(); - if (c instanceof ContentAssistant) - ContentAssistPreference.changeConfiguration( - (ContentAssistant) c, getPreferenceStore(), event); - } - } finally { - super.handlePreferenceStoreChanged(event); - } - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) - */ - protected void handlePreferencePropertyChanged( - org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - if (asv != null) { - String p = event.getProperty(); - if (CODE_FORMATTER_TAB_SIZE.equals(p)) { - asv.updateIndentationPrefixes(); - if (fTabConverter != null) - fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - } - } - super.handlePreferencePropertyChanged(event); - } - - /** - * Handles a property change event describing a change of the php core's - * preferences and updates the preference related editor properties. - * - * @param event - * the property change event - */ - // protected void - // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent - // event) { - // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - // if (asv != null) { - // String p = event.getProperty(); - // if (CODE_FORMATTER_TAB_SIZE.equals(p)) { - // asv.updateIndentationPrefixes(); - // if (fTabConverter != null) - // fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - // } - // } - // } - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, - * org.eclipse.jface.text.source.IVerticalRuler, - * org.eclipse.jface.text.source.IOverviewRuler, boolean, int) - */ - protected ISourceViewer createJavaSourceViewer(Composite parent, - IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, - boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { - return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, - isOverviewRulerVisible, styles, store); - } - - // protected ISourceViewer createJavaSourceViewer(Composite parent, - // IVerticalRuler ruler, int styles) { - // return new AdaptedSourceViewer(parent, ruler, styles); - // } -// private boolean isValidSelection(int offset, int length) { -// IDocumentProvider provider = getDocumentProvider(); -// if (provider != null) { -// IDocument document = provider.getDocument(getEditorInput()); -// if (document != null) { -// int end = offset + length; -// int documentLength = document.getLength(); -// return 0 <= offset && offset <= documentLength && 0 <= end -// && end <= documentLength; -// } -// } -// return false; -// } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement() - */ - protected IJavaElement getInputJavaElement() { - return WebUI.getDefault().getWorkingCopyManager() - .getWorkingCopy(getEditorInput()); - } - - /* - * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) - */ - public void editorContextMenuAboutToShow(IMenuManager menu) { - super.editorContextMenuAboutToShow(menu); - ActionContext context = new ActionContext(getSelectionProvider() - .getSelection()); - fContextMenuGroup.setContext(context); - fContextMenuGroup.fillContextMenu(menu); - fContextMenuGroup.setContext(null); - } - - /* - * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) - */ - protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { - if (page != null) { - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - page.setInput(manager.getWorkingCopy(input)); - } - } - - /* - * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, - * IProgressMonitor) - */ - // protected void performSaveOperation(WorkspaceModifyOperation operation, - // IProgressMonitor progressMonitor) { - // IDocumentProvider p = getDocumentProvider(); - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(fSavePolicy); - // } - // - // try { - // super.performSaveOperation(operation, progressMonitor); - // } finally { - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(null); - // } - // } - // } - /* - * @see AbstractTextEditor#doSave(IProgressMonitor) - */ - public void doSave(IProgressMonitor progressMonitor) { - - IDocumentProvider p = getDocumentProvider(); - if (p == null) { - // editor has been closed - return; - } - - if (p.isDeleted(getEditorInput())) { - - if (isSaveAsAllowed()) { - - /* - * 1GEUSSR: ITPUI:ALL - User should never loose changes made in - * the editors. Changed Behavior to make sure that if called - * inside a regular save (because of deletion of input element) - * there is a way to report back to the caller. - */ - performSaveAs(progressMonitor); - - } else { - - /* - * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still - * there Missing resources. - */ - Shell shell = getSite().getShell(); - MessageDialog - .openError( - shell, - PHPEditorMessages - .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ - } - - } else { - if (getPreferenceStore().getBoolean( - PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) { - RTrimAction trimAction = new RTrimAction(); - trimAction.setActiveEditor(null, getSite().getPage() - .getActiveEditor()); - trimAction.run(null); - } - - setStatusLineErrorMessage(null); - - updateState(getEditorInput()); - validateState(getEditorInput()); - - IWorkingCopyManager manager = WebUI.getDefault() - .getWorkingCopyManager(); - ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); - - if (unit != null) { - synchronized (unit) { - performSave(false, progressMonitor); - } - } else - performSave(false, progressMonitor); - } - } - - public boolean isSaveAsAllowed() { - return true; - } - - /** - * The compilation unit editor implementation of this - * AbstractTextEditor method asks the user for the workspace - * path of a file resource and saves the document there. See - * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 - * - * @param progressMonitor - * the progress monitor - */ - protected void performSaveAs(IProgressMonitor progressMonitor) { - - Shell shell = getSite().getShell(); - IEditorInput input = getEditorInput(); - - SaveAsDialog dialog = new SaveAsDialog(shell); - - IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input) - .getFile() - : null; - if (original != null) - dialog.setOriginalFile(original); - - dialog.create(); - - IDocumentProvider provider = getDocumentProvider(); - if (provider == null) { - // editor has been programmatically closed while the dialog was open - return; - } - - if (provider.isDeleted(input) && original != null) { - String message = PHPEditorMessages - .getFormattedString( - "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ - dialog.setErrorMessage(null); - dialog.setMessage(message, IMessageProvider.WARNING); - } - - if (dialog.open() == Window.CANCEL) { - if (progressMonitor != null) - progressMonitor.setCanceled(true); - return; - } - - IPath filePath = dialog.getResult(); - if (filePath == null) { - if (progressMonitor != null) - progressMonitor.setCanceled(true); - return; - } - - IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - IFile file = workspaceRoot.getFile(filePath); - final IEditorInput newInput = new FileEditorInput(file); - - boolean success = false; - try { - - provider.aboutToChange(newInput); - getDocumentProvider().saveDocument(progressMonitor, newInput, - getDocumentProvider().getDocument(getEditorInput()), true); - success = true; - - } catch (CoreException x) { - IStatus status = x.getStatus(); - if (status == null || status.getSeverity() != IStatus.CANCEL) - ErrorDialog - .openError( - shell, - PHPEditorMessages - .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ - } finally { - provider.changed(newInput); - if (success) - setInput(newInput); - } - - if (progressMonitor != null) - progressMonitor.setCanceled(!success); - } - - /* - * @see AbstractTextEditor#doSetInput(IEditorInput) - */ - protected void doSetInput(IEditorInput input) throws CoreException { - super.doSetInput(input); - configureTabConverter(); - configureToggleCommentAction(); - } - - // /* - // * @see - // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean) - // * @since 3.0 - // */ - // protected void installOverrideIndicator(boolean waitForReconcilation) { - // IAnnotationModel model= - // getDocumentProvider().getAnnotationModel(getEditorInput()); - // if (!waitForReconcilation) - // super.installOverrideIndicator(false); - // else { - // uninstallOverrideIndicator(); - // IJavaElement inputElement= getInputJavaElement(); - // if (model == null || inputElement == null) - // return; - // - // fOverrideIndicatorManager= new OverrideIndicatorManager(model, - // inputElement, null); - // addReconcileListener(fOverrideIndicatorManager); - // } - // } - // - // /* - // * @see - // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator() - // * @since 3.0 - // */ - // protected void uninstallOverrideIndicator() { - // if (fOverrideIndicatorManager != null) - // removeReconcileListener(fOverrideIndicatorManager); - // super.uninstallOverrideIndicator(); - // } - - /** - * Configures the toggle comment action - * - * @since 3.0 - */ - private void configureToggleCommentAction() { - IAction action = getAction("ToggleComment"); //$NON-NLS-1$ - if (action instanceof ToggleCommentAction) { - ISourceViewer sourceViewer = getSourceViewer(); - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - ((ToggleCommentAction) action).configure(sourceViewer, - configuration); - } - } - - // private void configureTabConverter() { - // if (fTabConverter != null) { - // IDocumentProvider provider = getDocumentProvider(); - // if (provider instanceof PHPDocumentProvider) { - // PHPDocumentProvider cup = (PHPDocumentProvider) provider; - // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); - // } - // } - // } - private void configureTabConverter() { - if (fTabConverter != null) { - IDocumentProvider provider = getDocumentProvider(); - if (provider instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider; - fTabConverter.setLineTracker(cup - .createLineTracker(getEditorInput())); - } - } - } - - private void startTabConversion() { - if (fTabConverter == null) { - fTabConverter = new TabConverter(); - configureTabConverter(); - fTabConverter.setNumberOfSpacesPerTab(getTabSize()); - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - asv.addTextConverter(fTabConverter); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - asv.updateIndentationPrefixes(); - } - } - - private void stopTabConversion() { - if (fTabConverter != null) { - AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); - asv.removeTextConverter(fTabConverter); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 - asv.updateIndentationPrefixes(); - fTabConverter = null; - } - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, - * org.eclipse.core.runtime.IProgressMonitor) - */ - protected void performSave(boolean overwrite, - IProgressMonitor progressMonitor) { - // IDocumentProvider p = getDocumentProvider(); - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(fSavePolicy); - // } - // try { - // super.performSave(overwrite, progressMonitor); - // } finally { - // if (p instanceof PHPDocumentProvider) { - // PHPDocumentProvider cp = (PHPDocumentProvider) p; - // cp.setSavePolicy(null); - // } - // } - - IDocumentProvider p = getDocumentProvider(); - if (p instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; - cp.setSavePolicy(fSavePolicy); - } - try { - super.performSave(overwrite, progressMonitor); - } finally { - if (p instanceof ICompilationUnitDocumentProvider) { - ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; - cp.setSavePolicy(null); - } - } - } - - /* - * @see AbstractTextEditor#doSaveAs - */ - public void doSaveAs() { - if (askIfNonWorkbenchEncodingIsOk()) { - super.doSaveAs(); - } - } - - /** - * Asks the user if it is ok to store in non-workbench encoding. - * - * @return if the user wants to continue - */ - private boolean askIfNonWorkbenchEncodingIsOk() { - IDocumentProvider provider = getDocumentProvider(); - if (provider instanceof IStorageDocumentProvider) { - IEditorInput input = getEditorInput(); - IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider; - String encoding = storageProvider.getEncoding(input); - String defaultEncoding = storageProvider.getDefaultEncoding(); - if (encoding != null && !encoding.equals(defaultEncoding)) { - Shell shell = getSite().getShell(); - String title = PHPEditorMessages - .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ - String msg; - if (input != null) - msg = MessageFormat - .format( - PHPEditorMessages - .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"), - new String[] { input.getName(), encoding }); //$NON-NLS-1$ - else - msg = MessageFormat - .format( - PHPEditorMessages - .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"), - new String[] { encoding }); //$NON-NLS-1$ - return MessageDialog.openQuestion(shell, title, msg); - } - } - return true; - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled() - * @since 3.0 - */ - public void aboutToBeReconciled() { - - // Notify AST provider - // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement()); - - // Notify listeners - Object[] listeners = fReconcilingListeners.getListeners(); - for (int i = 0, length = listeners.length; i < length; ++i) - ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled(); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, - * boolean, IProgressMonitor) - * @since 3.0 - */ - public void reconciled(CompilationUnit ast, boolean forced, - IProgressMonitor progressMonitor) { - - // Always notify AST provider - // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, - // getInputJavaElement()); - - // Notify listeners - // Object[] listeners = fReconcilingListeners.getListeners(); - // for (int i = 0, length= listeners.length; i < length; ++i) - // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, - // progressMonitor); - - // Update Java Outline page selection - if (!forced && !progressMonitor.isCanceled()) { - Shell shell = getSite().getShell(); - if (shell != null && !shell.isDisposed()) { - shell.getDisplay().asyncExec(new Runnable() { - public void run() { - selectionChanged(); - } - }); - } - } - } - - /** - * Returns the updated java element for the old java element. - */ -// private IJavaElement findElement(IJavaElement element) { -// if (element == null) -// return null; -// IWorkingCopyManager manager = WebUI.getDefault() -// .getWorkingCopyManager(); -// ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); -// if (unit != null) { -// try { -// synchronized (unit) { -// unit.reconcile(); -// } -// IJavaElement[] findings = unit.findElements(element); -// if (findings != null && findings.length > 0) -// return findings[0]; -// } catch (JavaModelException x) { -// PHPeclipsePlugin.log(x.getStatus()); -// // nothing found, be tolerant and go on -// } -// } -// return null; -// } - - /** - * Returns the offset of the given Java element. - */ -// private int getOffset(IJavaElement element) { -// if (element instanceof ISourceReference) { -// ISourceReference sr = (ISourceReference) element; -// try { -// ISourceRange srcRange = sr.getSourceRange(); -// if (srcRange != null) -// return srcRange.getOffset(); -// } catch (JavaModelException e) { -// } -// } -// return -1; -// } - - /* - * @see AbstractTextEditor#restoreSelection() - */ - // protected void restoreSelection() { - // try { - // if (getSourceViewer() == null || fRememberedSelection == null) - // return; - // IJavaElement newElement = findElement(fRememberedElement); - // int newOffset = getOffset(newElement); - // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - // - fRememberedElementOffset : 0; - // if (isValidSelection(delta + fRememberedSelection.getOffset(), - // fRememberedSelection.getLength())) - // selectAndReveal(delta + fRememberedSelection.getOffset(), - // fRememberedSelection.getLength()); - // } finally { - // fRememberedSelection = null; - // fRememberedElement = null; - // fRememberedElementOffset = -1; - // } - // } - /** - * Tells whether this is the active editor in the active page. - * - * @return true if this is the active editor in the active - * page - * @see IWorkbenchPage#getActiveEditor(); - */ - protected final boolean isActiveEditor() { - IWorkbenchWindow window = getSite().getWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - if (page == null) - return false; - IEditorPart activeEditor = page.getActiveEditor(); - return activeEditor != null && activeEditor.equals(this); - } - - /** - * Adds the given listener. Has no effect if an identical listener was not - * already registered. - * - * @param listener - * The reconcile listener to be added - * @since 3.0 - */ - final void addReconcileListener(IJavaReconcilingListener listener) { - synchronized (fReconcilingListeners) { - fReconcilingListeners.add(listener); - } - } - - /** - * Removes the given listener. Has no effect if an identical listener was - * not already registered. - * - * @param listener - * the reconcile listener to be removed - * @since 3.0 - */ - final void removeReconcileListener(IJavaReconcilingListener listener) { - synchronized (fReconcilingListeners) { - fReconcilingListeners.remove(listener); - } - } - - protected void updateStateDependentActions() { - super.updateStateDependentActions(); - fGenerateActionGroup.editorStateChanged(); - } - - /* - * @see AbstractTextEditor#rememberSelection() - */ - protected void rememberSelection() { - fRememberedSelection.remember(); - } - - /* - * @see AbstractTextEditor#restoreSelection() - */ - protected void restoreSelection() { - fRememberedSelection.restore(); - } - - /* - * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) - */ - protected boolean canHandleMove(IEditorInput originalElement, - IEditorInput movedElement) { - - String oldExtension = ""; //$NON-NLS-1$ - if (originalElement instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) originalElement).getFile(); - if (file != null) { - String ext = file.getFileExtension(); - if (ext != null) - oldExtension = ext; - } - } - - String newExtension = ""; //$NON-NLS-1$ - if (movedElement instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) movedElement).getFile(); - if (file != null) - newExtension = file.getFileExtension(); - } - - return oldExtension.equals(newExtension); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn() - */ - protected boolean isPrefQuickDiffAlwaysOn() { - // reestablishes the behaviour from AbstractDecoratedTextEditor which - // was hacked by JavaEditor - // to disable the change bar for the class file (attached source) java - // editor. - IPreferenceStore store = getPreferenceStore(); - return store - .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); - } - - /* - * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class required) { - if (SmartBackspaceManager.class.equals(required)) { - if (getSourceViewer() instanceof JavaSourceViewer) { - return ((JavaSourceViewer) getSourceViewer()) - .getBackspaceManager(); - } - } - - return super.getAdapter(required); - } - - /** - * Returns the mutex for the reconciler. See - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of - * the problem. - *

- * TODO remove once the underlying problem is solved. - *

- * - * @return the lock reconcilers may use to synchronize on - */ - public Object getReconcilerLock() { - return fReconcilerLock; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() - */ - protected void editorSaved() { - super.editorSaved(); - ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); - if (a != null) { - //a.refresh(ShowExternalPreviewAction.PHP_TYPE); - a.doRun(ShowExternalPreviewAction.PHP_TYPE); - } - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java deleted file mode 100644 index 9cca5c7..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java +++ /dev/null @@ -1,406 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ - -package net.sourceforge.phpeclipse.phpeditor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelListener; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Highlights the temporary problems. - */ -public class ProblemPainter implements IPainter, PaintListener, - IAnnotationModelListener { - - private static class ProblemPosition { - Position fPosition; - - Color fColor; - - boolean fMultiLine; - }; - - private boolean fIsActive = false; - - private boolean fIsPainting = false; - - private boolean fIsSettingModel = false; - - private ITextEditor fTextEditor; - - private ISourceViewer fSourceViewer; - - private StyledText fTextWidget; - - private IAnnotationModel fModel; - - private List fProblemPositions = new ArrayList(); - - private Map fColorTable = new HashMap(); - - private Set fAnnotationSet = new HashSet(); - - public ProblemPainter(ITextEditor textEditor, ISourceViewer sourceViewer) { - fTextEditor = textEditor; - fSourceViewer = sourceViewer; - fTextWidget = sourceViewer.getTextWidget(); - } - - private boolean hasProblems() { - return !fProblemPositions.isEmpty(); - } - - private void enablePainting() { - if (!fIsPainting && hasProblems()) { - fIsPainting = true; - fTextWidget.addPaintListener(this); - handleDrawRequest(null); - } - } - - private void disablePainting(boolean redraw) { - if (fIsPainting) { - fIsPainting = false; - fTextWidget.removePaintListener(this); - if (redraw && hasProblems()) - handleDrawRequest(null); - } - } - - private void setModel(IAnnotationModel model) { - if (fModel != model) { - if (fModel != null) - fModel.removeAnnotationModelListener(this); - fModel = model; - if (fModel != null) { - try { - fIsSettingModel = true; - fModel.addAnnotationModelListener(this); - } finally { - fIsSettingModel = false; - } - } - } - } - - private void catchupWithModel() { - if (fProblemPositions != null) { - fProblemPositions.clear(); - if (fModel != null) { - - Iterator e = new ProblemAnnotationIterator(fModel, true); - while (e.hasNext()) { - IProblemAnnotation pa = (IProblemAnnotation) e.next(); - Annotation a = (Annotation) pa; - - Color color = null; - AnnotationType type = pa.getAnnotationType(); - if (fAnnotationSet.contains(type)) - color = (Color) fColorTable.get(type); - - if (color != null) { - ProblemPosition pp = new ProblemPosition(); - pp.fPosition = fModel.getPosition(a); - pp.fColor = color; - pp.fMultiLine = true; - fProblemPositions.add(pp); - } - } - } - } - } - - private void updatePainting() { - disablePainting(true); - catchupWithModel(); - enablePainting(); - } - - /* - * @see IAnnotationModelListener#modelChanged(IAnnotationModel) - */ - public void modelChanged(final IAnnotationModel model) { - if (fTextWidget != null && !fTextWidget.isDisposed()) { - if (fIsSettingModel) { - // inside the ui thread -> no need for posting - updatePainting(); - } else { - Display d = fTextWidget.getDisplay(); - if (d != null) { - d.asyncExec(new Runnable() { - public void run() { - if (fTextWidget != null - && !fTextWidget.isDisposed()) - updatePainting(); - } - }); - } - } - } - } - - public void setColor(AnnotationType annotationType, Color color) { - if (color != null) - fColorTable.put(annotationType, color); - else - fColorTable.remove(annotationType); - } - - public void paintAnnotations(AnnotationType annotationType, boolean paint) { - if (paint) - fAnnotationSet.add(annotationType); - else - fAnnotationSet.remove(annotationType); - } - - public boolean isPaintingAnnotations() { - return !fAnnotationSet.isEmpty(); - } - - /* - * @see IPainter#dispose() - */ - public void dispose() { - - if (fColorTable != null) - fColorTable.clear(); - fColorTable = null; - - if (fAnnotationSet != null) - fAnnotationSet.clear(); - fAnnotationSet = null; - - fTextWidget = null; - fModel = null; - fProblemPositions = null; - } - - /* - * Returns the document offset of the upper left corner of the widgets - * viewport, possibly including partially visible lines. - */ - private int getInclusiveTopIndexStartOffset() { - - if (fTextWidget != null && !fTextWidget.isDisposed()) { - int top = fSourceViewer.getTopIndex(); - if ((fTextWidget.getTopPixel() % fTextWidget.getLineHeight()) != 0) - top--; - try { - IDocument document = fSourceViewer.getDocument(); - return document.getLineOffset(top); - } catch (BadLocationException ex) { - } - } - - return -1; - } - - /* - * @see PaintListener#paintControl(PaintEvent) - */ - public void paintControl(PaintEvent event) { - if (fTextWidget != null) - handleDrawRequest(event.gc); - } - - private void handleDrawRequest(GC gc) { - - int vOffset = getInclusiveTopIndexStartOffset(); - // http://bugs.eclipse.org/bugs/show_bug.cgi?id=17147 - int vLength = fSourceViewer.getBottomIndexEndOffset() + 1; - - for (Iterator e = fProblemPositions.iterator(); e.hasNext();) { - ProblemPosition pp = (ProblemPosition) e.next(); - Position p = pp.fPosition; - if (p.overlapsWith(vOffset, vLength)) { - - if (!pp.fMultiLine) { - - IRegion widgetRange = getWidgetRange(p); - if (widgetRange != null) - draw(gc, widgetRange.getOffset(), widgetRange - .getLength(), pp.fColor); - - } else { - - IDocument document = fSourceViewer.getDocument(); - try { - - int startLine = document.getLineOfOffset(p.getOffset()); - int lastInclusive = Math.max(p.getOffset(), p - .getOffset() - + p.getLength() - 1); - int endLine = document.getLineOfOffset(lastInclusive); - - for (int i = startLine; i <= endLine; i++) { - IRegion line = document.getLineInformation(i); - int paintStart = Math.max(line.getOffset(), p - .getOffset()); - int paintEnd = Math.min(line.getOffset() - + line.getLength(), p.getOffset() - + p.getLength()); - if (paintEnd > paintStart) { - // otherwise inside a line delimiter - IRegion widgetRange = getWidgetRange(new Position( - paintStart, paintEnd - paintStart)); - if (widgetRange != null) - draw(gc, widgetRange.getOffset(), - widgetRange.getLength(), pp.fColor); - } - } - - } catch (BadLocationException x) { - } - } - } - } - } - - private IRegion getWidgetRange(Position p) { - if (fSourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) fSourceViewer; - return extension.modelRange2WidgetRange(new Region(p.getOffset(), p - .getLength())); - - } else { - - IRegion region = fSourceViewer.getVisibleRegion(); - int offset = region.getOffset(); - int length = region.getLength(); - - if (p.overlapsWith(offset, length)) { - int p1 = Math.max(offset, p.getOffset()); - int p2 = Math.min(offset + length, p.getOffset() - + p.getLength()); - return new Region(p1 - offset, p2 - p1); - } - } - - return null; - } - - private int[] computePolyline(Point left, Point right, int height) { - - final int WIDTH = 4; // must be even - final int HEIGHT = 2; // can be any number - // final int MINPEEKS= 2; // minimal number of peeks - - int peeks = (right.x - left.x) / WIDTH; - // if (peeks < MINPEEKS) { - // int missing= (MINPEEKS - peeks) * WIDTH; - // left.x= Math.max(0, left.x - missing/2); - // peeks= MINPEEKS; - // } - - int leftX = left.x; - - // compute (number of point) * 2 - int length = ((2 * peeks) + 1) * 2; - if (length < 0) - return new int[0]; - - int[] coordinates = new int[length]; - - // cache peeks' y-coordinates - int bottom = left.y + height - 1; - int top = bottom - HEIGHT; - - // populate array with peek coordinates - for (int i = 0; i < peeks; i++) { - int index = 4 * i; - coordinates[index] = leftX + (WIDTH * i); - coordinates[index + 1] = bottom; - coordinates[index + 2] = coordinates[index] + WIDTH / 2; - coordinates[index + 3] = top; - } - - // the last down flank is missing - coordinates[length - 2] = left.x + (WIDTH * peeks); - coordinates[length - 1] = bottom; - - return coordinates; - } - - private void draw(GC gc, int offset, int length, Color color) { - if (gc != null) { - - Point left = fTextWidget.getLocationAtOffset(offset); - Point right = fTextWidget.getLocationAtOffset(offset + length); - - gc.setForeground(color); - int[] polyline = computePolyline(left, right, gc.getFontMetrics() - .getHeight()); - gc.drawPolyline(polyline); - - } else { - fTextWidget.redrawRange(offset, length, true); - } - } - - /* - * @see IPainter#deactivate(boolean) - */ - public void deactivate(boolean redraw) { - if (fIsActive) { - fIsActive = false; - disablePainting(redraw); - setModel(null); - catchupWithModel(); - } - } - - /* - * @see IPainter#paint(int) - */ - public void paint(int reason) { - if (!fIsActive) { - fIsActive = true; - IDocumentProvider provider = WebUI.getDefault() - .getCompilationUnitDocumentProvider(); - setModel(provider.getAnnotationModel(fTextEditor.getEditorInput())); - } else if (CONFIGURATION == reason || INTERNAL == reason) - updatePainting(); - } - - /* - * @see IPainter#setPositionManager(IPositionManager) - */ - public void setPositionManager(IPositionManager manager) { - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java deleted file mode 100644 index 8f0a6b3..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java +++ /dev/null @@ -1,39 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2003 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.filebuffers.IDocumentSetupParticipant; -import org.eclipse.jface.text.IDocument; - -/** - * The document setup participant for PHPDT. - */ -public class SmartyDocumentSetupParticipant implements - IDocumentSetupParticipant { - - public SmartyDocumentSetupParticipant() { - } - - /* - * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) - */ - public void setup(IDocument document) { - JavaTextTools tools = WebUI.getDefault().getJavaTextTools(); - tools.setupSmartyDocumentPartitioner(document, - IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, - // null); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java deleted file mode 100644 index 4792294..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.phpeditor; - -import net.sourceforge.phpdt.internal.ui.PHPUiImages; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; - -/** - * A toolbar action which toggles the presentation model of the connected text - * editor. The editor shows either the highlight range only or always the whole - * document. - */ -public class TogglePresentationAction extends TextEditorAction implements - IPropertyChangeListener { - - private IPreferenceStore fStore; - - /** - * Constructs and updates the action. - */ - public TogglePresentationAction() { - super(PHPEditorMessages.getResourceBundle(), - "TogglePresentation.", null); //$NON-NLS-1$ - PHPUiImages.setToolImageDescriptors(this, "segment_edit.gif"); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages - .getString("TogglePresentation.tooltip")); //$NON-NLS-1$ - setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_PRESENTATION); - // WorkbenchHelp.setHelp(this, - // IJavaHelpContextIds.TOGGLE_PRESENTATION_ACTION); - update(); - } - - /* - * @see IAction#actionPerformed - */ - public void run() { - - ITextEditor editor = getTextEditor(); - if (editor == null) - return; - - IRegion remembered = editor.getHighlightRange(); - editor.resetHighlightRange(); - - boolean showAll = !editor.showsHighlightRangeOnly(); - setChecked(showAll); - - editor.showHighlightRangeOnly(showAll); - if (remembered != null) - editor.setHighlightRange(remembered.getOffset(), remembered - .getLength(), true); - - fStore.removePropertyChangeListener(this); - fStore.setValue(PreferenceConstants.EDITOR_SHOW_SEGMENTS, showAll); - fStore.addPropertyChangeListener(this); - } - - /* - * @see TextEditorAction#update - */ - public void update() { - ITextEditor editor = getTextEditor(); - boolean checked = (editor != null && editor.showsHighlightRangeOnly()); - setChecked(checked); - setEnabled(editor != null); - } - - /* - * @see TextEditorAction#setEditor(ITextEditor) - */ - public void setEditor(ITextEditor editor) { - - super.setEditor(editor); - - if (editor != null) { - - if (fStore == null) { - fStore = WebUI.getDefault().getPreferenceStore(); - fStore.addPropertyChangeListener(this); - } - synchronizeWithPreference(editor); - - } else if (fStore != null) { - fStore.removePropertyChangeListener(this); - fStore = null; - } - - update(); - } - - /** - * Synchronizes the appearance of the editor with what the preference store - * tells him. - */ - private void synchronizeWithPreference(ITextEditor editor) { - - if (editor == null) - return; - - boolean showSegments = fStore - .getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS); - setChecked(showSegments); - - if (editor.showsHighlightRangeOnly() != showSegments) { - IRegion remembered = editor.getHighlightRange(); - editor.resetHighlightRange(); - editor.showHighlightRangeOnly(showSegments); - if (remembered != null) - editor.setHighlightRange(remembered.getOffset(), remembered - .getLength(), true); - } - } - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty() - .equals(PreferenceConstants.EDITOR_SHOW_SEGMENTS)) - synchronizeWithPreference(getTextEditor()); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java deleted file mode 100644 index 1d406b0..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java +++ /dev/null @@ -1,309 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor.php; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; -import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -//import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationExtension; -import org.eclipse.jface.text.contentassist.IContextInformationPresenter; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.IEditorPart; - -/** - * HTML completion processor. - */ -public class HTMLCompletionProcessor implements IContentAssistProcessor { - - /** - * Simple content assist tip closer. The tip is valid in a range of 5 - * characters around its popup location. - */ - protected static class Validator implements IContextInformationValidator, - IContextInformationPresenter { - - protected int fInstallOffset; - - /* - * @see IContextInformationValidator#isContextInformationValid(int) - */ - public boolean isContextInformationValid(int offset) { - return Math.abs(fInstallOffset - offset) < 5; - } - - /* - * @see IContextInformationValidator#install(IContextInformation, - * ITextViewer, int) - */ - public void install(IContextInformation info, ITextViewer viewer, - int offset) { - fInstallOffset = offset; - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, - * TextPresentation) - */ - public boolean updatePresentation(int documentPosition, - TextPresentation presentation) { - return false; - } - }; - - private static class ContextInformationWrapper implements - IContextInformation, IContextInformationExtension { - - private final IContextInformation fContextInformation; - - private int fPosition; - - public ContextInformationWrapper(IContextInformation contextInformation) { - fContextInformation = contextInformation; - } - - /* - * @see IContextInformation#getContextDisplayString() - */ - public String getContextDisplayString() { - return fContextInformation.getContextDisplayString(); - } - - /* - * @see IContextInformation#getImage() - */ - public Image getImage() { - return fContextInformation.getImage(); - } - - /* - * @see IContextInformation#getInformationDisplayString() - */ - public String getInformationDisplayString() { - return fContextInformation.getInformationDisplayString(); - } - - /* - * @see IContextInformationExtension#getContextInformationPosition() - */ - public int getContextInformationPosition() { - return fPosition; - } - - public void setContextInformationPosition(int position) { - fPosition = position; - } - }; - - protected IContextInformationValidator fValidator = new Validator(); - - private TemplateEngine fTemplateEngine; - - private char[] fProposalAutoActivationSet; - - private PHPCompletionProposalComparator fComparator; - - private int fNumberOfComputedResults = 0; - - private IEditorPart fEditor; - - protected IWorkingCopyManager fManager; - - public HTMLCompletionProcessor(IEditorPart editor) { - fEditor = editor; - fManager = WebUI.getDefault().getWorkingCopyManager(); - - TemplateContextType contextType = WebUI.getDefault() - .getTemplateContextRegistry().getContextType("html"); //$NON-NLS-1$ - if (contextType != null) - fTemplateEngine = new TemplateEngine(contextType); - - fComparator = new PHPCompletionProposalComparator(); - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, - int documentOffset) { - int contextInformationPosition = guessContextInformationPosition( - viewer, documentOffset); - return internalComputeCompletionProposals(viewer, documentOffset, - contextInformationPosition); - } - - private ICompletionProposal[] internalComputeCompletionProposals( - ITextViewer viewer, int offset, int contextOffset) { - //IDocument document = viewer.getDocument(); - ICompilationUnit unit = fManager.getWorkingCopy(fEditor - .getEditorInput()); - - if (fTemplateEngine != null) { - ICompletionProposal[] results; - // try { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, offset, unit); - // } catch (JavaModelException x) { - // Shell shell= viewer.getTextWidget().getShell(); - // ErrorDialog.openError(shell, - // JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), - // JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), - // x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ - // } - - IPHPCompletionProposal[] templateResults = fTemplateEngine - .getResults(); - - // concatenate arrays - IPHPCompletionProposal[] total; - total = new IPHPCompletionProposal[templateResults.length]; - System.arraycopy(templateResults, 0, total, 0, - templateResults.length); - results = total; - - fNumberOfComputedResults = (results == null ? 0 : results.length); - /* - * Order here and not in result collector to make sure that the - * order applies to all proposals and not just those of the - * compilation unit. - */ - return order(results); - } - return new IPHPCompletionProposal[0]; - } - - private int guessContextInformationPosition(ITextViewer viewer, int offset) { - int contextPosition = offset; - //IDocument document = viewer.getDocument(); - return contextPosition; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - // public IContextInformation[] computeContextInformation(ITextViewer - // viewer, int documentOffset) { - // IContextInformation[] result = new IContextInformation[5]; - // for (int i = 0; i < result.length; i++) - // result[i] = new - // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), - // new Object[] { new Integer(i), new Integer(documentOffset)}), - // //$NON-NLS-1$ - // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), - // new Object[] { new Integer(i), new Integer(documentOffset - 5), new - // Integer(documentOffset + 5)})); //$NON-NLS-1$ - // return result; - // } - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, - int offset) { - int contextInformationPosition = guessContextInformationPosition( - viewer, offset); - List result = addContextInformations(viewer, contextInformationPosition); - return (IContextInformation[]) result - .toArray(new IContextInformation[result.size()]); - } - - private List addContextInformations(ITextViewer viewer, int offset) { - ICompletionProposal[] proposals = internalComputeCompletionProposals( - viewer, offset, -1); - - List result = new ArrayList(); - for (int i = 0; i < proposals.length; i++) { - IContextInformation contextInformation = proposals[i] - .getContextInformation(); - if (contextInformation != null) { - ContextInformationWrapper wrapper = new ContextInformationWrapper( - contextInformation); - wrapper.setContextInformationPosition(offset); - result.add(wrapper); - } - } - return result; - } - - /** - * Order the given proposals. - */ - private ICompletionProposal[] order(ICompletionProposal[] proposals) { - Arrays.sort(proposals, fComparator); - return proposals; - } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order - * true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet - * the activation set - */ - public void setCompletionProposalAutoActivationCharacters( - char[] activationSet) { - fProposalAutoActivationSet = activationSet; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public char[] getContextInformationAutoActivationCharacters() { - return new char[] {}; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public IContextInformationValidator getContextInformationValidator() { - return fValidator; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public String getErrorMessage() { - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java deleted file mode 100644 index 3ea10f5..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java +++ /dev/null @@ -1,1068 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor.php; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedMap; - -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.IMethod; -import net.sourceforge.phpdt.core.IType; -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.ToolFactory; -import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; -import net.sourceforge.phpdt.core.compiler.InvalidInputException; -import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies; -import net.sourceforge.phpdt.internal.compiler.ast.CompilationUnitDeclaration; -import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions; -import net.sourceforge.phpdt.internal.compiler.parser.Scanner; -import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; -import net.sourceforge.phpdt.internal.compiler.parser.UnitParser; -import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo; -import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory; -import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; -import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader; -import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; -import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator; -import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; -import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine; -import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine; -import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal; -import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; -import net.sourceforge.phpeclipse.phpeditor.PHPEditor; -import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationExtension; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; - -/** - * Example PHP completion processor. - */ -public class PHPCompletionProcessor implements IContentAssistProcessor { - /** - * Simple content assist tip closer. The tip is valid in a range of 5 - * characters around its popup location. - */ - // protected static class Validator implements IContextInformationValidator, - // IContextInformationPresenter { - // protected int fInstallOffset; - // - // /* - // * @see IContextInformationValidator#isContextInformationValid(int) - // */ - // public boolean isContextInformationValid(int offset) { - // return Math.abs(fInstallOffset - offset) < 5; - // } - // - // /* - // * @see IContextInformationValidator#install(IContextInformation, - // ITextViewer, int) - // */ - // public void install(IContextInformation info, ITextViewer viewer, int - // offset) { - // fInstallOffset = offset; - // } - // - // /* - // * @see - // org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, - // TextPresentation) - // */ - // public boolean updatePresentation(int documentPosition, TextPresentation - // presentation) { - // return false; - // } - // }; - private static class ContextInformationWrapper implements - IContextInformation, IContextInformationExtension { - private final IContextInformation fContextInformation; - - private int fPosition; - - public ContextInformationWrapper(IContextInformation contextInformation) { - fContextInformation = contextInformation; - } - - /* - * @see IContextInformation#getContextDisplayString() - */ - public String getContextDisplayString() { - return fContextInformation.getContextDisplayString(); - } - - /* - * @see IContextInformation#getImage() - */ - public Image getImage() { - return fContextInformation.getImage(); - } - - /* - * @see IContextInformation#getInformationDisplayString() - */ - public String getInformationDisplayString() { - return fContextInformation.getInformationDisplayString(); - } - - /* - * @see IContextInformationExtension#getContextInformationPosition() - */ - public int getContextInformationPosition() { - return fPosition; - } - - public void setContextInformationPosition(int position) { - fPosition = position; - } - }; - - // private class TableName { - // String fTableName; - // - // TableName() { - // fTableName = null; - // } - // - // /** - // * @return Returns the tableName. - // */ - // public String getTableName() { - // if (fTableName == null) { - // return ""; - // } - // return fTableName; - // } - // - // /** - // * @param tableName - // * The tableName to set. - // */ - // public void setTableName(String tableName) { - // fTableName = tableName; - // } - // } - - private char[] fProposalAutoActivationSet; - - protected IContextInformationValidator fValidator = null; - - private TemplateEngine fTemplateEngine; - - private PHPCompletionProposalComparator fComparator; - - private IEditorPart fEditor; - - protected IWorkingCopyManager fManager; - - public PHPCompletionProcessor(IEditorPart editor) { - fEditor = editor; - fManager = WebUI.getDefault().getWorkingCopyManager(); - TemplateContextType contextType = WebUI.getDefault() - .getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$ - if (contextType != null) - fTemplateEngine = new TemplateEngine(contextType); - fComparator = new PHPCompletionProposalComparator(); - } - - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order - * true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet - * the activation set - */ - public void setCompletionProposalAutoActivationCharacters( - char[] activationSet) { - fProposalAutoActivationSet = activationSet; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, - int documentOffset) { - int contextInformationPosition = guessContextInformationPosition( - viewer, documentOffset); - return internalComputeCompletionProposals(viewer, documentOffset, - contextInformationPosition); - } - - private int getLastToken(List list, ITextViewer viewer, - int completionPosition, JavaContext context) { - // TableName tableName) { - IDocument document = viewer.getDocument(); - int start = context.getStart(); - // int end = context.getEnd(); - String startText; - int lastSignificantToken = ITerminalSymbols.TokenNameEOF; - try { - // begin search 2 lines behind of this - int j = start; - if (j != 0) { - char ch; - while (j > 0) { - ch = document.getChar(--j); - if (ch == '\n') { - break; - } - } - while (j > 0) { - ch = document.getChar(--j); - if (ch == '\n') { - break; - } - } - } - if (j != start) { - // scan the line for the dereferencing operator '->' - startText = document.get(j, start - j); - if (Scanner.DEBUG) { - System.out.println(startText); - } - int token = ITerminalSymbols.TokenNameEOF; - // token = getLastSQLToken(startText); - // tableName.setTableName(getLastSQLTableName(startText)); - Scanner scanner = ToolFactory - .createScanner(false, false, false); - scanner.setSource(startText.toCharArray()); - scanner.setPHPMode(true); - int beforeLastToken = ITerminalSymbols.TokenNameEOF; - int lastToken = ITerminalSymbols.TokenNameEOF; - char[] ident = null; - try { - token = scanner.getNextToken(); - lastToken = token; - while (token != ITerminalSymbols.TokenNameERROR - && token != ITerminalSymbols.TokenNameEOF) { - beforeLastToken = lastToken; - if (token == ITerminalSymbols.TokenNameVariable) { - ident = scanner.getCurrentTokenSource(); - if (ident.length == 5 && ident[0] == '$' - && ident[1] == 't' && ident[2] == 'h' - && ident[3] == 'i' && ident[4] == 's') { - token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION; - } - } - lastToken = token; - // System.out.println(scanner.toStringAction(lastToken)); - token = scanner.getNextToken(); - } - } catch (InvalidInputException e1) { - } catch (SyntaxError e) { - } - switch (lastToken) { - case ITerminalSymbols.TokenNameMINUS_GREATER: - // dereferencing operator '->' found - lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER; - if (beforeLastToken == ITerminalSymbols.TokenNameVariable) { - lastSignificantToken = ITerminalSymbols.TokenNameVariable; - list.set(0, ident); - } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) { - lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION; - list.set(0, ident); - } - break; - case ITerminalSymbols.TokenNamenew: - lastSignificantToken = ITerminalSymbols.TokenNamenew; - break; - } - } - } catch (BadLocationException e) { - } - return lastSignificantToken; - } - - String getSQLTableName(String sqlText, int start) { - int tableNameStart = -1; - int currentCharacterPosition = start + 1; - char ch; - try { - while (true) { - ch = sqlText.charAt(currentCharacterPosition++); - if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) { - tableNameStart = currentCharacterPosition - 1; - } else { - if (!Scanner.isPHPIdentifierPart(ch)) { - return sqlText.substring(tableNameStart, - currentCharacterPosition - 1); - } - } - } - } catch (IndexOutOfBoundsException e) { - if (tableNameStart >= 0) { - return sqlText.substring(tableNameStart, - currentCharacterPosition - 1); - } - } - return ""; - } - - // private String getLastSQLTableName(String startText) { - // // scan for sql identifiers - // char ch = ' '; - // int currentSQLPosition = startText.length(); - // int identEnd = -1; - // String ident = null; - // try { - // while (true) { - // ch = startText.charAt(--currentSQLPosition); - // if (Scanner.isSQLIdentifierPart(ch)) { - // // if (ch >= 'A' && ch <= 'Z') { - // if (identEnd < 0) { - // identEnd = currentSQLPosition + 1; - // } - // // } else if (ch >= 'a' && ch <= 'z') { - // // if (identEnd < 0) { - // // identEnd = currentSQLPosition + 1; - // // } - // } else if (identEnd >= 0) { - // ident = startText.substring(currentSQLPosition + 1, identEnd); - // // select -- from -- where -- - // // update -- set -- where -- - // // insert into -- ( -- ) values ( -- ) - // if (ident.length() >= 4 && ident.length() <= 6) { - // ident = ident.toLowerCase(); - // switch (ident.length()) { - // // case 3 : - // // if (ident.equals("set")) { - // // // System.out.println("set"); - // // token = ITerminalSymbols.TokenNameSQLset; - // // return token; - // // } - // // break; - // case 4: - // if (ident.equals("from")) { - // // System.out.println("from"); - // return getSQLTableName(startText, identEnd); - // } else if (ident.equals("into")) { - // // System.out.println("into"); - // return getSQLTableName(startText, identEnd); - // } - // break; - // case 6: - // if (ident.equals("update")) { - // // System.out.println("update"); - // return getSQLTableName(startText, identEnd); - // } - // break; - // } - // } - // identEnd = -1; - // } else if (Character.isWhitespace(ch)) { - // } - // } - // } catch (IndexOutOfBoundsException e) { - // } - // return ""; - // } - - /** - * Detect the last significant SQL token in the text before the completion - * - * @param startText - */ - // private int getLastSQLToken(String startText) { - // int token; - // // scan for sql identifiers - // char ch = ' '; - // int currentSQLPosition = startText.length(); - // int identEnd = -1; - // String ident = null; - // try { - // while (true) { - // ch = startText.charAt(--currentSQLPosition); - // if (ch >= 'A' && ch <= 'Z') { - // if (identEnd < 0) { - // identEnd = currentSQLPosition + 1; - // } - // } else if (ch >= 'a' && ch <= 'z') { - // if (identEnd < 0) { - // identEnd = currentSQLPosition + 1; - // } - // } else if (identEnd >= 0) { - // ident = startText.substring(currentSQLPosition + 1, identEnd); - // // select -- from -- where -- - // // update -- set -- where -- - // // insert into -- ( -- ) values ( -- ) - // if (ident.length() >= 3 && ident.length() <= 6) { - // ident = ident.toLowerCase(); - // switch (ident.length()) { - // case 3: - // if (ident.equals("set")) { - // // System.out.println("set"); - // token = ITerminalSymbols.TokenNameSQLset; - // return token; - // } - // break; - // case 4: - // if (ident.equals("from")) { - // // System.out.println("from"); - // token = ITerminalSymbols.TokenNameSQLfrom; - // // getSQLTableName(); - // return token; - // } else if (ident.equals("into")) { - // // System.out.println("into"); - // token = ITerminalSymbols.TokenNameSQLinto; - // return token; - // } - // break; - // case 5: - // if (ident.equals("where")) { - // // System.out.println("where"); - // token = ITerminalSymbols.TokenNameSQLwhere; - // return token; - // } - // break; - // case 6: - // if (ident.equals("select")) { - // // System.out.println("select"); - // token = ITerminalSymbols.TokenNameSQLselect; - // return token; - // } else if (ident.equals("insert")) { - // // System.out.println("insert"); - // token = ITerminalSymbols.TokenNameSQLinsert; - // return token; - // } else if (ident.equals("update")) { - // // System.out.println("update"); - // token = ITerminalSymbols.TokenNameSQLupdate; - // return token; - // } else if (ident.equals("values")) { - // // System.out.println("values"); - // token = ITerminalSymbols.TokenNameSQLvalues; - // return token; - // } - // break; - // } - // } - // identEnd = -1; - // } - // } - // } catch (IndexOutOfBoundsException e) { - // } - // return ITerminalSymbols.TokenNameEOF; - // } - private ICompletionProposal[] internalComputeCompletionProposals( - ITextViewer viewer, int offset, int contextOffset) { - ICompilationUnit unit = fManager.getWorkingCopy(fEditor - .getEditorInput()); - IDocument document = viewer.getDocument(); - IFile file = null; - IProject project = null; - if (offset > 0) { - PHPEditor editor = null; - if (fEditor != null && (fEditor instanceof PHPEditor)) { - editor = (PHPEditor) fEditor; - IEditorInput editorInput = editor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - file = ((IFileEditorInput) editorInput).getFile(); - project = file.getProject(); - } else { - return new ICompletionProposal[0]; - } - } - } - - Point selection = viewer.getSelectedRange(); - // remember selected text - String selectedText = null; - if (selection.y != 0) { - try { - selectedText = document.get(selection.x, selection.y); - } catch (BadLocationException e) { - } - } - - if (offset > 2 && fProposalAutoActivationSet != null) { - // restrict auto activation for '>' character to '->' token - - try { - char ch = document.getChar(offset - 1); - if (ch == '>') { - for (int i = 0; i < fProposalAutoActivationSet.length; i++) { - ch = fProposalAutoActivationSet[i]; - if (ch == '>') { // auto activation enabled - ch = document.getChar(offset - 2); - if (ch != '-') { - return new IPHPCompletionProposal[0]; - } - break; - } - } - } - } catch (BadLocationException e) { - e.printStackTrace(); - } - } - - JavaContextType phpContextType = (JavaContextType) WebUI - .getDefault().getTemplateContextRegistry() - .getContextType("php"); //$NON-NLS-1$ - JavaContext context = (JavaContext) phpContextType.createContext( - document, offset, selection.y, unit); - context.setVariable("selection", selectedText); //$NON-NLS-1$ - String prefix = context.getKey(); - - HashMap methodVariables = null; - // HashMap typeVariables = null; - HashMap unitVariables = null; - ICompilationUnit compilationUnit = (ICompilationUnit) context - .findEnclosingElement(IJavaElement.COMPILATION_UNIT); - // if (compilationUnit != null) { - // unitVariables = ((CompilationUnit) compilationUnit).variables; - // } - IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE); - if (type != null) { - // typeVariables = ((SourceType) type).variables; - } - IMethod method = (IMethod) context - .findEnclosingElement(IJavaElement.METHOD); - // if (method != null) { - // methodVariables = ((SourceMethod) method).variables; - // } - - boolean emptyPrefix = prefix == null || prefix.equals(""); - IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0]; - - if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { - // php Variable ? - String lowerCasePrefix = prefix.toLowerCase(); - HashSet localVariables = new HashSet(); - if (compilationUnit != null) { - unitVariables = getUnitVariables(unitVariables, compilationUnit); - getVariableProposals(localVariables, viewer, project, context, - unitVariables, lowerCasePrefix, 94); - } - if (method != null) { - methodVariables = getMethodVariables(methodVariables, method); - getVariableProposals(localVariables, viewer, project, context, - methodVariables, lowerCasePrefix, 99); - } - if (!localVariables.isEmpty()) { - localVariableResults = (IPHPCompletionProposal[]) localVariables - .toArray(new IPHPCompletionProposal[localVariables - .size()]); - } - } - - // TableName sqlTable = new TableName(); - ArrayList list = new ArrayList(); - list.add(null); - int lastSignificantToken = getLastToken(list, viewer, offset, context); // , - // sqlTable); - boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER) - || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) - || (lastSignificantToken == ITerminalSymbols.TokenNamenew) - || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION); - - if (fTemplateEngine != null) { - IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0]; - ICompletionProposal[] results; - if (!emptyPrefix) { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, offset, unit); - templateResults = fTemplateEngine.getResults(); - } - // TODO delete this - IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0]; - - // declarations stored in file project.index on project level - IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0]; - if (project != null) { - DeclarationEngine declarationEngine; - JavaContextType contextType = (JavaContextType) WebUI - .getDefault().getTemplateContextRegistry() - .getContextType("php"); //$NON-NLS-1$ - if (contextType != null) { - IdentifierIndexManager indexManager = WebUI - .getDefault().getIndexManager(project); - SortedMap sortedMap; - declarationEngine = new DeclarationEngine(project, - contextType, lastSignificantToken, file); - if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) { - // complete '$this->' - sortedMap = indexManager.getIdentifiers(file); - declarationEngine.completeObject(viewer, offset, - sortedMap, unit); - } else { - String typeRef = null; - char[] varName = (char[]) list.get(0); - if (varName != null) { - if (method != null) { - methodVariables = getMethodVariables( - methodVariables, method); - VariableInfo info = (VariableInfo) methodVariables - .get(new String(varName)); - if (info != null && info.typeIdentifier != null) { - typeRef = new String(info.typeIdentifier); - } - } - } - if (typeRef != null) { - // complete '$variable->' with type information - sortedMap = indexManager.getIdentifiers(typeRef); - declarationEngine.completeObject(viewer, offset, - sortedMap, unit); - } else { - // complete '$variable->' without type information - sortedMap = indexManager.getIdentifierMap(); - declarationEngine.complete(viewer, offset, - sortedMap, unit); - } - } - declarationResults = declarationEngine.getResults(); - } - } - // built in function names from phpsyntax.xml - ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData(); - IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0]; - if ((!useClassMembers) && syntaxbuffer != null) { - BuiltInEngine builtinEngine; - JavaContextType contextType = (JavaContextType) WebUI - .getDefault().getTemplateContextRegistry() - .getContextType("php"); //$NON-NLS-1$ - if (contextType != null) { - builtinEngine = new BuiltInEngine(contextType); - builtinEngine.complete(viewer, offset, syntaxbuffer, unit); - builtinResults = builtinEngine.getResults(); - } - } - // ICompletionProposal[] sqlResults = new ICompletionProposal[0]; - // if (project != null) { - // sqlResults = getSQLProposals(viewer, project, context, prefix, - // sqlTable); - // } - // concatenate the result arrays - IPHPCompletionProposal[] total; - total = new IPHPCompletionProposal[localVariableResults.length - + templateResults.length + identifierResults.length - + builtinResults.length + declarationResults.length];// + - // sqlResults.length]; - System.arraycopy(templateResults, 0, total, 0, - templateResults.length); - System.arraycopy(identifierResults, 0, total, - templateResults.length, identifierResults.length); - System.arraycopy(builtinResults, 0, total, templateResults.length - + identifierResults.length, builtinResults.length); - System.arraycopy(declarationResults, 0, total, - templateResults.length + identifierResults.length - + builtinResults.length, declarationResults.length); - // System.arraycopy(sqlResults, 0, total, templateResults.length + - // identifierResults.length + builtinResults.length - // + declarationResults.length, sqlResults.length); - // System.arraycopy(localVariableResults, 0, total, - // templateResults.length - // + identifierResults.length + builtinResults.length - // + declarationResults.length + sqlResults.length, - // localVariableResults.length); - System - .arraycopy(localVariableResults, 0, total, - templateResults.length + identifierResults.length - + builtinResults.length - + declarationResults.length, - localVariableResults.length); - results = total; - // fNumberOfComputedResults = (results == null ? 0 : - // results.length); - /* - * Order here and not in result collector to make sure that the - * order applies to all proposals and not just those of the - * compilation unit. - */ - return order(results); - } - return new IPHPCompletionProposal[0]; - } - - /** - * @param unitVariables - * @param unit - */ - private HashMap getUnitVariables(HashMap unitVariables, - ICompilationUnit unit) { - if (unitVariables == null) { - try { - String unitText = unit.getSource(); - unitVariables = new HashMap(); - - ProblemReporter problemReporter = new ProblemReporter( - DefaultErrorHandlingPolicies.exitAfterAllProblems(), - new CompilerOptions(JavaCore.getOptions()), - new DefaultProblemFactory()); - UnitParser parser = new UnitParser(problemReporter); - parser.compilationUnit = new CompilationUnitDeclaration( - problemReporter, null, unitText.length()); - parser.parse(unitText, unitVariables); - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - WebUI.log(e); - } - } - return unitVariables; - } - - /** - * @param methodVariables - * @param method - */ - private HashMap getMethodVariables(HashMap methodVariables, IMethod method) { - if (methodVariables == null) { - try { - String methodText = method.getSource(); - methodVariables = new HashMap(); - ProblemReporter problemReporter = new ProblemReporter( - DefaultErrorHandlingPolicies.exitAfterAllProblems(), - new CompilerOptions(JavaCore.getOptions()), - new DefaultProblemFactory()); - UnitParser parser = new UnitParser(problemReporter); - parser.compilationUnit = new CompilationUnitDeclaration( - problemReporter, null, methodText.length()); - parser.parseFunction(methodText, methodVariables); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - WebUI.log(e); - } - } - return methodVariables; - } - - /** - * @param viewer - * @param project - * @param context - * @param prefix - * @return - */ - private void getVariableProposals(HashSet localVariables, - ITextViewer viewer, IProject project, JavaContext context, - HashMap variables, String prefix, int relevance) { - // try { - int start = context.getStart(); - int end = context.getEnd(); - IRegion region = new Region(start, end - start); - // IMethod method = (IMethod) - // context.findEnclosingElement(IJavaElement.METHOD); - // if (method != null && (method instanceof SourceMethod) && - // ((SourceMethod) - // method).variables != null) { - // HashMap map = ((SourceMethod) method).variables; - Set set = variables.keySet(); - Iterator iter = set.iterator(); - String varName; - boolean matchesVarName; - while (iter.hasNext()) { - varName = (String) iter.next(); - if (varName.length() >= prefix.length()) { - matchesVarName = true; - for (int i = 0; i < prefix.length(); i++) { - if (prefix.charAt(i) != Character.toLowerCase(varName - .charAt(i))) { - matchesVarName = false; - break; - } - } - if (matchesVarName) { - LocalVariableProposal prop; - // if (varName.length == prefix.length()) { - // prop = new LocalVariableProposal(new String(varName), - // region, - // viewer, relevance-10); - // } else { - prop = new LocalVariableProposal(new String(varName), - region, viewer, relevance); - // } - localVariables.add(prop); - } - } - } - // } - - // char[] varName; - // boolean matchesVarName; - // if (method != null) { - // ISourceRange range = method.getSourceRange(); - // char[] source = method.getSource().toCharArray(); - // Scanner scanner = new Scanner(); - // scanner.setSource(source); - // scanner.phpMode = true; - // int token = Scanner.TokenNameWHITESPACE; - // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) { - // if (token == Scanner.TokenNameVariable) { - // varName = scanner.getCurrentTokenSource(); - // if (varName.length >= prefix.length()) { - // matchesVarName = true; - // for (int i = 0; i < prefix.length(); i++) { - // if (prefix.charAt(i) != varName[i]) { - // matchesVarName = false; - // break; - // } - // } - // if (matchesVarName) { - // LocalVariableProposal prop = new LocalVariableProposal(new - // String(varName), region, viewer); - // if (varName.length == prefix.length()) { - // prop.setRelevance(98); - // } - // localVariables.add(prop); - // } - // } - // } - // } - // } - // } catch (Throwable e) { - // // ignore - Syntax exceptions could occur, if there are syntax errors - // ! - // } - } - - /** - * @param viewer - * @param project - * @param context - * @param prefix - * @param sqlTable - * @param sqlResults - * @return - */ - // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, - // IProject - // project, DocumentTemplateContext context, - // String prefix, TableName sqlTable) { - // ICompletionProposal[] sqlResults = new ICompletionProposal[0]; - // // Get The Database bookmark from the Quantum SQL plugin: - // // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance(); - // // if (sqlBookMarks != null) { - // String bookmarkString = - // ProjectPrefUtil.getMiscProjectsPreferenceValue(project, - // IPreferenceConstants.PHP_BOOKMARK_DEFAULT); - // if (bookmarkString != null && !bookmarkString.equals("")) { - // String[] bookmarks = ExternalInterface.getBookmarkNames(); - // boolean foundBookmark = false; - // for (int i = 0; i < bookmarks.length; i++) { - // if (bookmarks[i].equals(bookmarkString)) { - // foundBookmark = true; - // } - // } - // if (!foundBookmark) { - // return sqlResults; - // } - // // Bookmark bookmark = sqlBookMarks.find(bookmarkString); - // ArrayList sqlList = new ArrayList(); - // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) { - // ExternalInterface.connectBookmark(bookmarkString, null); - // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) { - // return sqlResults; - // } - // } - // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) { - // try { - // int start = context.getStart(); - // int end = context.getEnd(); - // String foundSQLTableName = sqlTable.getTableName(); - // String tableName; - // String columnName; - // String prefixWithoutDollar = prefix; - // boolean isDollarPrefix = false; - // if (prefix.length() > 0 && prefix.charAt(0) == '$') { - // prefixWithoutDollar = prefix.substring(1); - // isDollarPrefix = true; - // } - // IRegion region = new Region(start, end - start); - // ResultSet set; - // if (!isDollarPrefix) { - // String[] tableNames = ExternalInterface.getMatchingTableNames(null, - // bookmarkString, prefixWithoutDollar, null, false); - // for (int i = 0; i < tableNames.length; i++) { - // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer, - // PHPUiImages.get(PHPUiImages.IMG_TABLE))); - // } - // } - // - // String[] columnNames = ExternalInterface.getMatchingColumnNames(null, - // bookmarkString, prefixWithoutDollar, null, false); - // for (int i = 0; i < columnNames.length; i++) { - // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer, - // PHPUiImages.get(PHPUiImages.IMG_TABLE))); - // } - // - // sqlResults = new IPHPCompletionProposal[sqlList.size()]; - // for (int i = 0; i < sqlList.size(); i++) { - // sqlResults[i] = (SQLProposal) sqlList.get(i); - // } - // } catch (Exception /* NotConnectedException */ e) { - // - // } - // // } - // } - // // } - // return sqlResults; - // } - private boolean looksLikeMethod(PHPCodeReader reader) throws IOException { - int curr = reader.read(); - while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr)) - curr = reader.read(); - - if (curr == PHPCodeReader.EOF) - return false; - - return Scanner.isPHPIdentifierPart((char) curr); - } - - private int guessContextInformationPosition(ITextViewer viewer, int offset) { - int contextPosition = offset; - IDocument document = viewer.getDocument(); - try { - - PHPCodeReader reader = new PHPCodeReader(); - reader.configureBackwardReader(document, offset, true, true); - - int nestingLevel = 0; - - int curr = reader.read(); - while (curr != PHPCodeReader.EOF) { - - if (')' == (char) curr) - ++nestingLevel; - - else if ('(' == (char) curr) { - --nestingLevel; - - if (nestingLevel < 0) { - int start = reader.getOffset(); - if (looksLikeMethod(reader)) - return start + 1; - } - } - - curr = reader.read(); - } - } catch (IOException e) { - } - return contextPosition; - } - - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, - int offset) { - int contextInformationPosition = guessContextInformationPosition( - viewer, offset); - List result = addContextInformations(viewer, contextInformationPosition); - return (IContextInformation[]) result - .toArray(new IContextInformation[result.size()]); - } - - private List addContextInformations(ITextViewer viewer, int offset) { - ICompletionProposal[] proposals = internalComputeCompletionProposals( - viewer, offset, -1); - List result = new ArrayList(); - for (int i = 0; i < proposals.length; i++) { - IContextInformation contextInformation = proposals[i] - .getContextInformation(); - if (contextInformation != null) { - ContextInformationWrapper wrapper = new ContextInformationWrapper( - contextInformation); - wrapper.setContextInformationPosition(offset); - result.add(wrapper); - } - } - return result; - } - - /** - * Order the given proposals. - */ - private ICompletionProposal[] order(ICompletionProposal[] proposals) { - Arrays.sort(proposals, fComparator); - // int len = proposals.length; - // if (len > 10) { - // len = 10; - // } - // for (int i = 0; i < len; i++) { - // System.out.println(proposals[i].getDisplayString()); - // } - return proposals; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - // return null; // new char[] { '$' }; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public IContextInformationValidator getContextInformationValidator() { - if (fValidator == null) - fValidator = new JavaParameterListValidator(); - return fValidator; - } - - /* - * (non-Javadoc) Method declared on IContentAssistProcessor - */ - public String getErrorMessage() { - return null; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java deleted file mode 100644 index c8a5072..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java +++ /dev/null @@ -1,97 +0,0 @@ -/********************************************************************** - Copyright (c) 2002 Widespace, OU and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://solareclipse.sourceforge.net/legal/cpl-v10.html - - Contributors: - Igor Malinin - initial contribution - - $Id: PHPDocumentPartitioner.java,v 1.6 2006-10-21 23:18:33 pombredanne Exp $ - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor.php; - -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.text.rules.FlatNode; -import net.sourceforge.phpeclipse.ui.text.rules.MultiViewPartitioner; -import net.sourceforge.phpeclipse.ui.text.rules.ViewNode; - -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.rules.IPartitionTokenScanner; - -/** - * - * - * @author Igor Malinin - */ -public class PHPDocumentPartitioner extends MultiViewPartitioner { - public static final String PHP_TEMPLATE_DATA = "__php_template_data"; - - public static final String PHP_SCRIPT_CODE = "__php_script_code"; - - public static final String[] LEGAL_TYPES = { PHP_TEMPLATE_DATA, - PHP_SCRIPT_CODE }; - - public PHPDocumentPartitioner(IPartitionTokenScanner scanner) { - super(scanner); - } - - protected FlatNode createNode(String type, int offset, int length) { - if (type.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { - if (DEBUG) { - Assert.isTrue(offset >= 0); - } - ViewNode node = new ViewNode(type); - node.offset = offset; - node.length = length; - return node; - } - - return super.createNode(type, offset, length); - } - - /* - * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#createPartitioner(String) - */ - protected IDocumentPartitioner createPartitioner(String contentType) { - if (contentType == null) { - // return JavaTextTools.createHTMLPartitioner(); - return WebUI.getDefault().getJavaTextTools() - .getXMLTextTools().createPHPXMLPartitioner(); - } - - if (contentType.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { - return WebUI.getDefault().getJavaTextTools() - .createPHPPartitioner(); - } - return null; - } - - /* - * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#getContentType(String, - * String) - */ - protected String getContentType(String parent, String view) { - if (parent == null) { - if (view == IDocument.DEFAULT_CONTENT_TYPE) { - return PHP_TEMPLATE_DATA; - } - } else { - if (view == IDocument.DEFAULT_CONTENT_TYPE) { - return PHP_SCRIPT_CODE; - } - } - - return super.getContentType(parent, view); - } - - public String[] getLegalContentTypes() { - return LEGAL_TYPES; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml deleted file mode 100644 index 6eef0eb..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml +++ /dev/null @@ -1,6633 +0,0 @@ - - -Returns the sum of two arbitrary precision numbers -Compares two arbitrary precision numbers -Returns the quotient of two arbitrary precision numbers (division) -Returns the modulus of the two arbitrary precision operands -Returns the multiplication of two arbitrary precision numbers -Returns the value of an arbitrary precision number raised to the power of another -Returns the value of an arbitrary precision number raised to the power of another reduced by a modulous -Sets default scale parameter for all bc math functions -Returns the square root of an arbitray precision number -Returns the difference between two arbitrary precision numbers -Compresses a string into BZip2 encoded data -Decompresses BZip2 compressed data -Returns the error number -Returns the error number and error string in an associative array -Returns the error string -Opens a new BZip2 stream -Reads up to length bytes from a BZip2 stream, or 1024 bytes if length is not specified -Convert Julian Day to UNIX timestamp -Convert UNIX timestamp to Julian Day -Returns the number of days in a month for a given year and calendar -Converts from Julian Day Count to a supported calendar and return extended information -Returns information about a particular calendar -Converts from a supported calendar to Julian Day Count -Converts a french republic calendar date to julian day count -Converts a gregorian calendar date to julian day count -Returns name or number of day of week from julian day count -Returns name of month for julian day count -Converts a julian day count to a french republic calendar date -Converts a julian day count to a gregorian calendar date -Converts a julian day count to a jewish calendar date -Convert a julian day count to a julian calendar date -Converts a jewish calendar date to a julian day count -Converts a julian calendar date to julian day count -Return the timestamp of midnight on Easter of a given year (defaults to current year) -Return the number of days after March 21 that Easter falls on for a given year (defaults to current year) -Generate a globally unique identifier (GUID) -Connect events from a COM object to a PHP object -Returns a handle to an already running instance of a COM object -Loads a Typelibrary and registers its constants -Process COM messages, sleeping for up to timeoutms milliseconds -Print out a PHP class definition for a dispatchable interface -Determines the filename into which an object will be saved, or false if none is set, via IPersistFile::GetCurFile -Gets maximum stream size required to store the object data, via IPersistStream::GetSizeMax (or IPersistStreamInit::GetSizeMax) -Initializes the object to a default state, via IPersistStreamInit::InitNew -Load object data from file, via IPersistFile::Load -Initializes an object from the stream where it was previously saved, via IPersistStream::Load or OleLoadFromStream -Persist object data to file, via IPersistFile::Save -Saves the object to a stream, via IPersistStream::Save -Creates a persistence helper object, usually associated with a com_object -Returns the absolute value of a variant -"Adds" two variant values together and returns the result -performs a bitwise AND operation between two variants and returns the result -Convert a variant into a new variant object of another type -concatenates two variant values together and returns the result -Compares two variants -Returns a variant date representation of a unix timestamp -Converts a variant date/time value to unix timestamp -Returns the result from dividing two variants -Performs a bitwise equivalence on two variants -Returns the integer part ? of a variant -Returns the VT_XXX type code for a variant -Converts variants to integers and then returns the result from dividing them -Performs a bitwise implication on two variants -Returns the integer portion of a variant -Divides two variants and returns only the remainder -multiplies the values of the two variants and returns the result -Performs logical negation on a variant -Performs bitwise not negation on a variant -Performs a logical disjunction on two variants -Returns the result of performing the power function with two variants -Rounds a variant to the specified number of decimal places -Assigns a new value for a variant object -Convert a variant into another type. Variant is modified "in-place" -subtracts the value of the right variant from the left variant value and returns the result -Performs a logical exclusion on two variants -Checks for alphanumeric character(s) -Checks for alphabetic character(s) -Checks for control character(s) -Checks for numeric character(s) -Checks for any printable character(s) except space -Checks for lowercase character(s) -Checks for printable character(s) -Checks for any printable character which is not whitespace or an alphanumeric character -Checks for whitespace character(s) -Checks for uppercase character(s) -Checks for character(s) representing a hexadecimal digit -Close a cURL session -Copy a cURL handle along with all of it's preferences -Return an integer containing the last error number -Return a string contain the last error for the current session -Perform a cURL session -Get information regarding a specific transfer -Initialize a cURL session -Set an option for a cURL transfer -Set an array of option for a cURL transfer -Return cURL version information. -Add a normal cURL handle to a cURL multi handle -Close a set of cURL handles -Run the sub-connections of the current cURL handle -Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set -Get information about the current transfers -Returns a new cURL multi handle -Remove a multi handle from a set of cURL handles -Get all the sockets associated with the cURL extension, which can then be "selected" -Returns true(1) if it is a valid date in gregorian calendar -Format a local date/time -Returns new DateTime object -Sets the date. -Gets the default timezone used by all date/time functions in a script -Sets the default timezone used by all date/time functions in a script -Returns date formatted according to given format - -Sets the ISO date. -Alters the timestamp. -Returns the DST offset. -Returns associative array with detailed info about given date -Returns an array with information about sun set/rise and twilight begin/end -Returns time of sunrise for a given day and location -Returns time of sunset for a given day and location -Sets the time. -Return new DateTimeZone object relative to give DateTime -Sets the timezone for the DateTime object. -Get date/time information -Format a GMT date/time -Get UNIX timestamp for a GMT date -Format a GMT/UCT time/date according to locale settings -Format a local time/date as integer -Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array -Get UNIX timestamp for a date -Format a local time/date according to locale settings -Convert string representation of date and time to a timestamp -Return current UNIX timestamp -Creates new DateTime object -Creates new DateTimeZone object. -Returns associative array containing dst, offset and the timezone name -Returns numerically index array with all timezone identifiers. -Returns the timezone name from abbrevation -Returns the name of the timezone. -Returns the timezone offset. -Returns new DateTimeZone object -Returns numeracilly indexed array containing associative array for all transitions for the timezone. -Closes database -Deletes the entry associated with key If inifile: remove all other key lines -Checks, if the specified key exists -Fetches the data associated with key -Resets the internal key pointer and returns the first key -List configured database handlers -If not inifile: Insert value as key, return false, if key exists already If inifile: Add vakue as key (next instance of key) -List opened databases -Returns the next key -Opens path using the specified handler in mode -Optimizes (e.g. clean up, vacuum) database -Opens path using the specified handler in mode persistently -Inserts value as key, replaces key, if key exists already If inifile: remove all other key lines -Synchronizes database -Adds a record to the database -Closes an open dBase-format database file -Creates a new dBase-format database file -Marks a record to be deleted - -Returns an array representing a record from the database -Returns an associative array representing a record from the database -Returns the number of fields (columns) in the database -Returns the number of records in the database -Opens a dBase-format database file -Packs the database (deletes records marked for deletion) -Replaces a record to the database -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Attr-isId Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-32791A2F Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-7C603781 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3EDB695F Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-E5CBA7FB Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6531BCCF Since: -Register extended class used to create base node type -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 -URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 -Since: DOM extended -Since: DOM extended -URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 -Convenience method to save to file -Convenience method to output as html -Convenience method to save to file as html -URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 -Since: DOM extended -Substitutues xincludes in a DomDocument -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-canSetParameter Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-getParameter Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocument Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocType Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementation3-getFeature Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-5CED94D7 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList-item Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpl Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpls Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMStringList-item Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-666EE0F9 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-217A91B8 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAtNodeNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAttrNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1938918D Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C90942 Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttr Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttrNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6D6AC0F9 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D589198 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElRemAtNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-F68F082 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-887236154 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAtNodeNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAttrNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttr Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNode Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNS Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1074577549 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getNamedItemNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-349467F9 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D58B193 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-removeNamedItemNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1025163788 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-setNamedItemNS Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getName Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getNamespaceURI Since: -Canonicalize nodes to a string -Canonicalize nodes to a file -Gets an xpath for a node -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-184E7107 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3A0ED0A4 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-compareDocumentPosition Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getFeature Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getUserData Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-NodeHasAttrs Since: DOM Level 2 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-810594187 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-952280727 Since: -URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isEqualNode Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isSameNode Since: DOM Level 3 -URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-lookupNamespacePrefix Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-normalize Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1734834066 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-785887307 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-setUserData Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-844377136 Since: -Get a simplexml_element object from dom to allow for processing -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset16 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset32 Since: -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-isWhitespaceInElementContent Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-replaceWholeText Since: DOM Level 3 -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-38853C1D Since: -Get the type of an image -Reads header data from the JPEG/TIFF image filename and optionally reads the internal thumbnails -Get headername for index or false if not defined -Reads the embedded thumbnail -Get the number of rows affected by the last statement -Turns on auto-commit -Get the size of a BLOB identified by blob_handle -Change the user for a session -Get the size of a CLOB identified by clob_handle -Close a connection to a database server -Commit the transaction -Create a connection to a database server -Create a BLOB in the database for use with an insert or update statement -Create a CLOB in the database for use with an insert or update statement -Create a new database on the server -Move the internal row counter to the specified row_number -Get or set the database name used with a connection -Get or set the databsae password used with a connection -Send one or more SQL statements to a specified database on the server -Gets the status (Stopped, Starting, Running, Stopping) for a given database -Drop a database on the server -Returns the last error code -Returns the last error string -Fetches a result row as an array (associative, numeric or both) -Detch a row of data. Returns an assoc array -Get the field properties for a specified field_index -Returns an array of the lengths of each column in the result set -Fetch a row of data. Returns an object -Fetch a row of data. Returns an indexed array -??? -Get the column length for a specified field_index -Get the column name for a specified field_index -??? -Get the table name for a specified field_index -Get the field type for a specified field_index -free the memory used to store a result -??? -Get or set the host name used with a connection -Get the internal index for the last insert statement -Retreive a list of all databases on the server -Retrieve a list of all fields for the specified database.table -Retreive a list of all tables from the specifoied database -Switch to the next result if multiple results are available -Get number of fields in the result set -Get number of rows -Get or set the user password used with a connection -Create a persistant connection to a database server -Send one or more SQL statements to the server and execute them -Read the BLOB data identified by blob_handle -Read the CLOB data identified by clob_handle -??? -Rollback all statments since last commit -Get the number of rows affected by the last statement -Select the database to open -Change input/output character set -Sets the mode for how LOB data re retreived (actual data or a handle) -Change the password for a given user -Sets the transaction locking and isolation -Start a database on the server -Stop a database on the server -Retreive the table name for index after a call to fbsql_list_tables() -Get or set the host user used with a connection -Enable or disable FrontBase warnings -Add javascript code to the fdf file -Adds a template into the FDF document -Closes the FDF document -Creates a new FDF document -Call a user defined function for each document value -Gets error code for last operation -Gets error description for error code -Gets the appearance of a field and creates a PDF document out of it. -Get attached uploaded file -Gets FDF file encoding scheme -Gets the value of /F key -Gets the flags of a field -Gets a value from the opt array of a field -Gets the value of /Status key -Gets the value of a field as string -Gets version number for FDF api or file -Set FDF specific HTTP headers -Gets the name of the next field name or the first field name -Opens a new FDF document -Opens a new FDF document from string -Sets target frame for form -Writes out the FDF file -Returns the FDF file as a string -Sets the appearence of a field -Sets FDF encoding (either "Shift-JIS" or "Unicode") -Sets the value of /F key -Sets flags for a field in the FDF document -Sets the javascript action for a field -Adds javascript code to be executed when Acrobat opens the FDF -Sets a value in the opt array for a field -Sets the value of /Status key -Sets the submit form action for a field -Sets target frame for form -Sets the value of a field -Sets FDF version for a file -* Returns true if the variable with the name 'name' exists in source. -* Returns the filtered variable 'name'* from source `type`. -* Returns an array with all arguments defined in 'definition'. -* Returns the filtered version of the vriable. -* Returns an array with all arguments defined in 'definition'. -* Returns the filter ID belonging to a named filter -Attempt to allocate space on the remote FTP server -Changes to the parent directory -Changes directories -Sets permissions on a file -Closes the FTP stream -Opens a FTP stream -Deletes a file -Requests execution of a program on the FTP server -Retrieves a file from the FTP server and writes it to an open file -Stores a file from an open file to the FTP server -Retrieves a file from the FTP server and writes it to a local file -Gets an FTP option -Logs into the FTP server -Returns the last modification time of the file, or -1 on error -Creates a directory and returns the absolute path for the new directory or false on error -Continues retrieving/sending a file nbronously -Retrieves a file from the FTP server asynchronly and writes it to an open file -Stores a file from an open file to the FTP server nbronly -Retrieves a file from the FTP server nbhronly and writes it to a local file -Stores a file on the FTP server -Returns an array of filenames in the given directory -Turns passive mode on or off -Stores a file on the FTP server -Returns the present working directory -Sends a literal command to the FTP server -Returns a detailed listing of a directory as an array of output lines -Renames the given file to a new path -Removes a directory -Sets an FTP option -Sends a SITE command to the server -Returns the size of the file, or -1 on error -Opens a FTP-SSL stream -Returns the system type identifier - -Output WBMP image to browser or file -Turn alpha blending mode on or off for the given image -Should antialiased functions used or not -Draw a partial ellipse -Draw a character -Draw a character rotated 90 degrees counter-clockwise -Allocate a color for an image -Allocate a color with an alpha level. Works for true color and palette based images -Get the index of the color of a pixel -Get the index of the closest color to the specified color -Find the closest matching colour with alpha transparency -Get the index of the color which has the hue, white and blackness nearest to the given color -De-allocate a color for an image -Get the index of the specified color -Find exact match for colour with transparency -Makes the colors of the palette version of an image more closely match the true color version -Get the index of the specified color or its closest possible alternative -Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images -Set the color for the specified palette index -Get the colors for an index -Find out the number of colors in an image's palette -Define a color as transparent -Apply a 3x3 convolution matrix, using coefficient div and offset -Copy part of an image -Merge one part of an image with another -Merge one part of an image with another -Copy and resize part of an image using resampling to help ensure clarity -Copy and resize part of an image -Create a new image -Create a new image from GD file or URL -Create a new image from GD2 file or URL -Create a new image from a given part of GD2 file or URL -Create a new image from GIF file or URL -Create a new image from JPEG file or URL -Create a new image from PNG file or URL -Create a new image from the image stream in the string -Create a new image from WBMP file or URL -Create a new image from XBM file or URL -Create a new image from XPM file or URL -Create a new true color image -Draw a dashed line -Destroy an image -Draw an ellipse -Flood fill -Draw a filled partial ellipse -Draw an ellipse -Draw a filled polygon -Draw a filled rectangle -Flood fill to specific color -Applies Filter an image using a custom angle -Get font height -Get font width -Give the bounding box of a text using fonts via freetype2 -Write text to the image using fonts via freetype2 -Apply a gamma correction to a GD image -Output GD image to browser or file -Output GD2 image to browser or file -Output GIF image to browser or file -Grab a screenshot -Grab a window or its client area using a windows handle (HWND property in COM instance) -Enable or disable interlace -return true if the image uses truecolor -Output JPEG image to browser or file -Set the alpha blending flag to use the bundled libgd layering effects -Draw a line -Load a new font -Copy the palette from the src image onto the dst image -Output PNG image to browser or file -Draw a polygon -Return the bounding box needed by a string if rasterized -Make a copy of a font for purposes like extending or reenconding -To change a fonts character encoding vector -Extend or or condense (if extend < 1) a font -Free memory used by a font -Load a new font from specified file -Slant a font -Rasterize a string over an image -Draw a rectangle -Rotate an image using a custom angle -Include alpha channel to a saved image -Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color -Set a single pixel -Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. -Set line thickness for drawing lines, ellipses, rectangles, polygons etc. -Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color -Draw a string horizontally -Draw a string vertically - rotated 90 degrees counter-clockwise -Get image width -Get image height -Convert a true colour image to a palette based image with a number of colours, optionally using dithering. -Give the bounding box of a text using TrueType fonts -Write text to the image using a TrueType font -Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM -Output WBMP image to browser or file -Output XBM image to browser or file -Bind to the text domain domain_name, looking for translations in dir. Returns the current domain -Return the translation of msgid for domain_name and category, or msgid unaltered if a translation does not exist -Return the translation of msgid for domain_name, or msgid unaltered if a translation does not exist -Return the translation of msgid for the current domain, or msgid unaltered if a translation does not exist -Plural version of gettext() -Set the textdomain to "domain". Returns the current domain -Calculates absolute value -Add a and b -Calculates logical AND of a and b -Clears bit in a -Compares two numbers -Calculates one's complement of a -Divide a by b, returns quotient only -Divide a by b, returns quotient and reminder -Divide a by b, returns reminder only -Divide a by b using exact division algorithm -Calculates factorial function -Computes greatest common denominator (gcd) of a and b -Computes G, S, and T, such that AS + BT = G = `gcd' (A, B) -Calculates hamming distance between a and b -Initializes GMP number -Gets signed long value of GMP number -Computes the inverse of a modulo b -Computes Jacobi symbol -Computes Legendre symbol -Computes a modulo b -Multiply a and b -Negates a number -Finds next prime of a -Calculates logical OR of a and b -Checks if a is an exact square -Calculates the population count of a -Raise base to power exp -Raise base to power exp and take result modulo mod -Checks if a is "probably prime" -Gets random number -Finds first zero bit -Finds first non-zero bit -Sets or clear bit in a -Gets the sign of the number -Takes integer part of square root of a -Square root with remainder -Gets string representation of GMP number -Subtract b from a -Tests if bit is set in a -Calculates logical exclusive OR of a and b -Generate a hash of a given input string Returns lowercase hexits by default -Return a list of registered hashing algorithms -Generate a hash of a given file Returns lowercase hexits by default -Output resulting digest -Generate a hash of a given input string with a key using HMAC Returns lowercase hexits by default -Generate a hash of a given file with a key using HMAC Returns lowercase hexits by default -Initialize a hashing context -Pump data into the hashing algorithm -Pump data into the hashing algorithm from a file -Pump data into the hashing algorithm from an open stream -Returns str converted to the out_charset character set -Get internal encoding and output encoding for ob_iconv_handler() -Decodes a mime header field -Decodes multiple mime header fields -Composes a mime header field with field_name and field_value in a specified scheme -Sets internal encoding and output encoding for ob_iconv_handler() -Returns the character count of str -Finds position of first occurrence of needle within part of haystack beginning with offset -Finds position of last occurrence of needle within part of haystack beginning with offset -Returns specified part of a string -Convert an 8-bit string to a quoted-printable string -Returns an array of all IMAP alerts that have been generated since the last page load or since the last imap_alerts() call, whichever came last. The alert stack is cleared after imap_alerts() is called. -Append a new message to a specified mailbox -Decode BASE64 encoded text -Convert an 8bit string to a base64 string -Read the message body -Read the structure of a specified body section of a specific message -Get mailbox properties -Clears flags on messages -Close an IMAP stream -Create a new mailbox -Mark a message for deletion -Delete a mailbox -Returns an array of all IMAP errors generated since the last page load, or since the last imap_errors() call, whichever came last. The error stack is cleared after imap_errors() is called. -Permanently delete all messages marked for deletion -Read an overview of the information in the headers of the given message sequence -Get a specific body section -Get the full unfiltered header for a message -Read the full structure of a message -Returns the quota set to the mailbox account qroot -Returns the quota set to the mailbox account mbox -Gets the ACL for a given mailbox -Reads the list of mailboxes and returns a full array of objects containing name, attributes, and delimiter -Return a list of subscribed mailboxes, in the same format as imap_getmailboxes() -Read the headers of the message -Returns headers for all messages in a mailbox -Returns the last error that was generated by an IMAP function. The error stack is NOT cleared after this call. -Read the list of mailboxes -Return a list of subscribed mailboxes -Send an email message -Create a MIME message based on given envelope and body sections -Copy specified message to a mailbox -Move specified message to a mailbox -Returns info about the current mailbox -Decode mime header element in accordance with RFC 2047 and return array of objects containing 'charset' encoding and decoded 'text' -Get the sequence number associated with a UID -Gives the number of messages in the current mailbox -Gives the number of recent messages in current mailbox -Open an IMAP stream to a mailbox -Check if the IMAP stream is still active -Convert a quoted-printable string to an 8-bit string -Rename a mailbox -Reopen an IMAP stream to a new mailbox -Parses an address string -Parse a set of mail headers contained in a string, and return an object similar to imap_headerinfo() -Returns a properly formatted email address given the mailbox, host, and personal info -Save a specific body section to a file -Read list of mailboxes containing a certain string -Return a list of messages matching the given criteria -Will set the quota for qroot mailbox -Sets the ACL for a given mailbox -Sets flags on messages -Sort an array of message headers, optionally including only messages that meet specified criteria. -Get status info from a mailbox -Subscribe to a mailbox -Return threaded by REFERENCES tree -Set or fetch imap timeout -Get the unique message id associated with a standard sequential message number -Remove the delete flag from a message -Unsubscribe from a mailbox -Decode a modified UTF-7 string -Encode a string in modified UTF-7 -Convert a mime-encoded text to UTF-8 -Add data into created blob -Cancel creating blob -Close blob -Create blob for adding data -Output blob contents to browser -Get len bytes data from open blob -Create blob, copy file in it, and close it -Return blob length and other useful info -Open blob for retrieving data parts -Frees the event handler set by ibase_set_event_handler() -Register the callback for handling each of the named events -Waits for any one of the passed Interbase events to be posted by the database, and returns its name -Returns the number of rows affected by the previous INSERT, UPDATE or DELETE statement -Execute a previously prepared query -Fetch a row from the results of a query -Fetch a object from the results of a query -Fetch a row from the results of a query -Get information about a field -Free memory used by a query -Free the memory used by a result -Assign a name to a result for use with ... WHERE CURRENT OF <name> statements -Get the number of fields in result -Get the number of params in a prepared query -Return the number of rows that are available in a result -Get information about a parameter -Prepare a query for later execution -Execute a query -Add a user to security database -Initiates a backup task in the service manager and returns immediately -Request statistics about a database -Delete a user from security database -Execute a maintenance command on the database server -Modify a user in security database -Initiates a restore task in the service manager and returns immediately -Request information about a database server -Connect to the service manager -Disconnect from the service manager -Close an InterBase connection -Commit transaction -Commit transaction and retain the transaction context -Open a connection to an InterBase database -Drop an InterBase database -Return error code -Return error message -Increments the named generator and returns its new value -Open a persistent connection to an InterBase database -Rollback transaction -Rollback transaction and retain the transaction context -Start a transaction over one or several databases -Decodes the JSON representation into a PHP value -Returns the JSON representation of a value -Translate 8859 characters to t61 characters -Add entries to LDAP directory -Bind to LDAP directory -Determine if an entry has a specific value for one of its attributes -Connect to an LDAP server -Count the number of entries in a search result -Delete an entry from a directory -Convert DN to User Friendly Naming format -Convert error number to error string -Get the current ldap error number -Get the current ldap error string -Splits DN into its component parts -Return first attribute -Return first result id -Return first reference -Free result memory -Get attributes from a search result entry -Get the DN of a result entry -Get all result entries -Get the current value of various session-wide parameters -Get all values with lengths from a result entry -Single-level search -Add attribute values to current -Delete attribute values -Replace attribute values with new ones -Get the next attribute in result -Get next result entry -Get next reference -Extract information from reference entry -Extract information from result -Read an entry -Bind to LDAP directory using SASL -Search LDAP tree under base_dn -Set the value of various session-wide parameters -Set a callback function to do re-binds on referral chasing. -Sort LDAP result entries -Start TLS -Translate t61 characters to 8859 characters -Unbind from LDAP directory -Clear last error from libxml -Retrieve array of errors -Retrieve last error from libxml -Set the streams context for the next libxml document load or write -Disable libxml errors and allow user to fetch error information as needed -Check if the string is valid for the specified encoding -Returns a case-folded version of sourcestring -Returns converted string in desired encoding -Conversion between full-width character and half-width character (Japanese) -Converts the string resource in variables to desired encoding -Decodes the MIME "encoded-word" in the string -Converts HTML numeric entities to character code -Encodings of the given string is returned (as a string) -Converts the string to MIME "encoded-word" in the format of =?charset?(B|Q)?encoded_string?= -Converts specified characters to HTML numeric entities -Returns the current settings of mbstring -Returns the input encoding -Sets the current output_encoding or returns the current output_encoding as a string -Sets the current internal encoding or Returns the current internal encoding as a string -Sets the current language or Returns the current language as a string -Returns an array of all supported entity encodings or Returns the entity encoding as a string -Returns an array of all supported alias encodings -Returns an array or string of all supported mime names -Returns string in output buffer converted to the http_output encoding -Parses GET/POST/COOKIE data and sets global variables -Return the preferred MIME name (charset) as a string -* Sends an email message with MIME scheme -Returns part of a string -Trim the string in terminal width -Finds position of first occurrence of a string within another, case insensitive -Finds first occurrence of a string within another, case insensitive -Get character numbers of a string -Find position of first occurrence of a string within another -Finds the last occurrence of a character in a string within another -Finds the last occurrence of a character in a string within another, case insensitive -Finds position of last occurrence of a string within another, case insensitive -Find position of last occurrence of a string within another -Finds first occurrence of a string within another -* Returns a lowercased version of sourcestring -* Returns a uppercased version of sourcestring -Gets terminal width of a string -Sets the current substitute_character or returns the current substitute_character -Returns part of a string -Count the number of substring occurrences -Regular expression match for multibyte string -Regular expression match for multibyte string -Replace regular expression for multibyte string -Regular expression search for multibyte string -Get search start position -Get matched substring of the last time -Initialize string and regular expression for search. -Regular expression search for multibyte string -Regular expression search for multibyte string -Set search start position -Case-insensitive regular expression match for multibyte string -Case insensitive replace regular expression for multibyte string -Returns the current encoding for regex as a string. -Set or get the default options for mbregex functions -split multibyte string into array by regular expression -CBC crypt/decrypt data using key key with cipher cipher starting with iv -CFB crypt/decrypt data using key key with cipher cipher starting with iv -Create an initialization vector (IV) -OFB crypt/decrypt data using key key with cipher cipher starting with iv -ECB crypt/decrypt data using key key with cipher cipher starting with iv -Returns the name of the algorithm specified by the descriptor td -Returns the block size of the cipher specified by the descriptor td -Returns the size of the IV in bytes of the algorithm specified by the descriptor td -Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td -Returns the name of the mode specified by the descriptor td -This function decrypts the crypttext -Returns TRUE if the alrogithm is a block algorithms -Returns TRUE if the mode is for use with block algorithms -Returns TRUE if the mode outputs blocks -This function runs the self test on the algorithm specified by the descriptor td -OFB crypt/decrypt data using key key with cipher cipher starting with iv -This function encrypts the plaintext -This function terminates encrypt specified by the descriptor td -This function initializes all buffers for the specific module -Get the key size of cipher -Get the name of cipher -Get the IV size of cipher (Usually the same as the blocksize) -Get the key size of cipher -List all algorithms in "module_dir" -List all modes "module_dir" -Free the descriptor td -Returns the block size of the algorithm -Returns the maximum supported key size of the algorithm -This function decrypts the crypttext -Returns TRUE if the algorithm is a block algorithm -Returns TRUE if the mode is for use with block algorithms -Returns TRUE if the mode outputs blocks of bytes -Opens the module of the algorithm and the mode to be used -Does a self test of the module "module" -OFB crypt/decrypt data using key key with cipher cipher starting with iv -This function decrypts the plaintext -Hash data with hash -Gets the number of available hashes -Gets the block size of hash -Gets the name of hash -Get the name of the keygen algorithm -Get the required size of the salt for the keygen algorithm -Generate a key -Get the number of available keygen algorithms -Generates a key using hash functions -Whether the keygen algorithm uses the bytes_count parameter -Whether the keygen algorithm uses a hash algorithm -Whether the keygen algorithm requires a salt -Return content-type for file -Returns the action flag for keyPress(char) -Set scale (?) -Use constant pool (?) -Use SWF version (?) -Creates a new SWFAction object, compiling the given script -Creates a new SWFBitmap object from jpg (with optional mask) or dbl file -Returns the height of this bitmap -Returns the width of this bitmap -Creates a new SWFButton object -associates a sound with a button transition NOTE: the transitions are all wrong _UP, _OVER, _DOWN _HIT -Sets the action to perform when conditions described in flags is met -Sets the character to display for the condition described in flags -Sets the action to perform when button is pressed -Sets the character for this button's down state -Sets the character for this button's hit test state -enable track as menu button behaviour -Sets the character for this button's over state -Sets the character for this button's up state -Adds this SWFAction to the given SWFSprite instance -Sets the add color part of this SWFDisplayItem's CXform to (r, g, b [, a]), a defaults to 0 -another way of defining a MASK layer -Displaces this SWFDisplayItem by (dx, dy) in movie coordinates -Moves this SWFDisplayItem to movie coordinates (x, y) -Sets the multiply color part of this SWFDisplayItem's CXform to (r, g, b [, a]), a defaults to 1.0 -Rotates this SWFDisplayItem the given (clockwise) degrees from its current orientation -Rotates this SWFDisplayItem the given (clockwise) degrees from its original orientation -Multiplies this SWFDisplayItem's current x scale by xScale, its y scale by yScale -Scales this SWFDisplayItem by xScale in the x direction, yScale in the y, or both to xScale if only one arg -Sets this SWFDisplayItem's z-depth to depth. Items with higher depth values are drawn on top of those with lower values -defines a MASK layer at level -Sets the item's transform matrix -Sets this SWFDisplayItem's name to name -Sets this SWFDisplayItem's ratio to ratio. Obviously only does anything if displayitem was created from an SWFMorph -Adds xSkew to this SWFDisplayItem's x skew value -Sets this SWFDisplayItem's x skew value to xSkew -Adds ySkew to this SWFDisplayItem's y skew value -Sets this SWFDisplayItem's y skew value to ySkew -Creates a new SWFFill object -Moves this SWFFill to shape coordinates (x,y) -Rotates this SWFFill the given (clockwise) degrees from its original orientation -Scales this SWFFill by xScale in the x direction, yScale in the y, or both to xScale if only one arg -Sets this SWFFill's x skew value to xSkew -Sets this SWFFill's y skew value to ySkew -Creates a new SWFFont object from given file -adds characters to a font required within textfields -Returns the ascent of the font, or 0 if not available -Returns the descent of the font, or 0 if not available -Returns the leading of the font, or 0 if not available -Returns the glyph shape of a char as a text string -Calculates the width of the given string in this font at full height -Calculates the width of the given string in this font at full height -Calculates the width of the given string in this font at full height -adds characters to a font for exporting font -adds characters to a font for exporting font -Creates a new SWFGradient object -Adds given entry to the gradient -Creates a new SWFMorph object -Return's this SWFMorph's start shape object -Return's this SWFMorph's start shape object -Creates swfmovie object according to the passed version - -Labels frame - - - - - -Saves the movie. 'where' can be stream and the movie will be saved there otherwise it is treated as string and written in file with that name - -Sets background color (r,g,b) -Sets movie dimension -Sets number of frames -Sets movie rate -Sets sound stream of the SWF movie. The parameter can be stream or string. Retuens the number of frames. -Returns a SWFPrebuiltClip object -Creates a new SWFShape object -Returns a fill object, for use with swfshape_setleftfill and swfshape_setrightfill. If 1 or 2 parameter(s) is (are) passed first should be object (from gradient class) and the second int (flags). Gradient fill is performed. If 3 or 4 parameters are passed : r, g, b [, a]. Solid fill is performed. -Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock -Draws a circle of radius r centered at the current location, in a counter-clockwise fashion -Draws a cubic bezier curve using the current position and the three given points as control points -Draws a cubic bezier curve using the current position and the three given points as control points -Draws a curve from the current pen position (x, y) to the point (x+bdx, y+bdy) in the current line style, using point (x+adx, y+ady) as a control point or draws a cubic bezier to point (x+cdx, x+cdy) with control points (x+adx, y+ady) and (x+bdx, y+bdy) -Draws a curve from the current pen position (x,y) to the point (bx, by) in the current line style, using point (ax, ay) as a control point. Or draws a cubic bezier to point (dx, dy) with control points (ax, ay) and (bx, by) -Draws the first character in the given string into the shape using the glyph definition from the given font -Draws a line from the current pen position (x, y) to the point (x+dx, y+dy) in the current line style -Draws a line from the current pen position to shape coordinates (x, y) in the current line style -Moves the pen from its current location by vector (x, y) -Moves the pen to shape coordinates (x, y) -Sets the left side fill style to fill in case only one parameter is passed. When 3 or 4 parameters are passed they are treated as : int r, int g, int b, int a . Solid fill is performed in this case before setting left side fill type. -Sets the right side fill style to fill in case only one parameter is passed. When 3 or 4 parameters are passed they are treated as : int r, int g, int b, int a . Solid fill is performed in this case before setting right side fill type. -Sets the current line style for this SWFShape -Creates a new SWFSound object from given file -Creates a new SWFSprite object -Adds the character to the sprite, returns a displayitem object -Labels frame -Moves the sprite to the next frame -Remove the named character from the sprite's display list -Sets the number of frames in this SWFSprite -Creates new SWFText object -Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color -Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color -Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color -Returns the ascent of the current font at its current size, or 0 if not available -Returns the descent of the current font at its current size, or 0 if not available -Returns the leading of the current font at its current size, or 0 if not available -calculates the width of the given string in this text objects current font and size -calculates the width of the given string in this text objects current font and size -Calculates the width of the given string in this text objects current font and size -Moves this SWFText object's current pen position to (x, y) in text coordinates -Sets this SWFText object's current color to the given color -Sets this SWFText object's current font to given font -Sets this SWFText object's current height to given height -Sets this SWFText object's current letterspacing to given spacing -Creates a new SWFTextField object -adds characters to a font that will be available within a textfield -Adds the given string to this textfield -Sets the alignment of this textfield -Sets the width and height of this textfield -Sets the color of this textfield -Sets the font for this textfield -Sets the font height of this textfield -Sets the indentation of the first line of this textfield -Sets the left margin of this textfield -Sets the line spacing of this textfield -Sets both margins of this textfield -Sets the variable name of this textfield -Sets the padding of this textfield -Sets the right margin of this textfield -Returns a SWVideoStream object -Return number of affected rows -Close an mSQL connection -Open a connection to an mSQL Server -Create an mSQL database -Move internal result pointer -Send an SQL query to mSQL -Drop (delete) an mSQL database -Returns the text of the error message from previous mSQL operation -Fetch a result row as an associative array -Get column information from a result and return as an object -Fetch a result row as an object -Get a result row as an enumerated array -Get the flags associated with the specified field in a result -Returns the length of the specified field -Get the name of the specified field in a result -Set result pointer to a specific field offset -Get name of the table the specified field is in -Get the type of the specified field in a result -Free result memory -List databases available on an mSQL server -List mSQL result fields -List tables in an mSQL database -Get number of fields in a result -Get number of rows in a result -Open a persistent connection to an mSQL Server -Send an SQL query to mSQL -Get result data -Select an mSQL database -Adds a parameter to a stored procedure or a remote stored procedure -Closes a connection to a MS-SQL server -Establishes a connection to a MS-SQL server -Moves the internal row pointer of the MS-SQL result associated with the specified result identifier to pointer to the specified row number -Executes a stored procedure on a MS-SQL server database -Returns an associative array of the current row in the result set specified by result_id -Returns an associative array of the current row in the result set specified by result_id -Returns the next batch of records -Gets information about certain fields in a query result -Returns a psuedo-object of the current row in the result set specified by result_id -Returns an array of the current row in the result set specified by result_id -Get the length of a MS-SQL field -Returns the name of the field given by offset in the result set given by result_id -Seeks to the specified field offset -Returns the type of a field -Free a MS-SQL result index -Free a MS-SQL statement index -Gets the last message from the MS-SQL server -Converts a 16 byte binary GUID to a string -Initializes a stored procedure or a remote stored procedure -Sets the lower error severity -Sets the lower message severity -Move the internal result pointer to the next result -Returns the number of fields fetched in from the result id specified -Returns the number of rows fetched in from the result id specified -Establishes a persistent connection to a MS-SQL server -Perform an SQL query on a MS-SQL server database -Returns the contents of one cell from a MS-SQL result set -Returns the number of records affected by the query -Select a MS-SQL database -Gets number of affected rows in previous MySQL operation -Returns the default character set for the current connection -Close a MySQL connection -Opens a connection to a MySQL Server -Create a MySQL database -Move internal result pointer -Sends an SQL query to MySQL -Drops (delete) a MySQL database -Returns the number of the error message from previous MySQL operation -Returns the text of the error message from previous MySQL operation -Escape string for mysql query -Fetch a result row as an array (associative, numeric or both) -Fetch a result row as an associative array -Gets column information from a result and return as an object -Gets max data size of each column in a result -Fetch a result row as an object -Gets a result row as an enumerated array -Gets the flags associated with the specified field in a result -Returns the length of the specified field -Gets the name of the specified field in a result -Sets result pointer to a specific field offset -Gets name of the table the specified field is in -Gets the type of the specified field in a result -Free result memory -Returns a string that represents the client library version -Returns a string describing the type of connection in use, including the server host name -Returns the protocol version used by current connection -Returns a string that represents the server version number -Returns a string containing information about the most recent query -Gets the ID generated from the previous INSERT operation -List databases available on a MySQL server -List MySQL result fields -Returns a result set describing the current server threads -List tables in a MySQL database -Gets number of fields in a result -Gets number of rows in a result -Opens a persistent connection to a MySQL Server -Ping a server connection. If no connection then reconnect. -Sends an SQL query to MySQL -Escape special characters in a string for use in a SQL statement, taking into account the current charset of the connection -Gets result data -Selects a MySQL database -sets client character set -Returns a string containing status information -Returns the thread id of current connection -Sends an SQL query to MySQL, without fetching and buffering the result rows -Get number of affected rows in previous MySQL operation -Turn auto commit on or of -Change logged-in user of the active connection -Returns the name of the character set used for this connection -Close connection -Commit outstanding actions and close transaction -Move internal result pointer - - -Returns the numerical value of the error message from previous MySQL operation -Returns the text of the error message from previous MySQL operation -Fetch the number of fields returned by the last query for the given link -Set result pointer to a specified field offset -Get current field offset of result pointer -Free query result memory for the given result handle -Get MySQL client info -Get MySQL client info -Get MySQL protocol information -Get MySQL server info -Return the MySQL version for the server referenced by the given link -Get information about the most recent query -Initialize mysqli and return a resource for use with mysql_real_connect -Get the ID generated from the previous INSERT operation -Kill a mysql process on the server -check if there any more query results from a multi query -read next result from multi_query -Get number of fields in result -Get number of rows in result -Set options -Ping a server connection or reconnect if there is no connection -Prepare a SQL statement for execution -Open a connection to a mysql server -Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection -Binary-safe version of mysql_query() -Undo actions from current transaction -Select a MySQL database -unsets user defined handler for load local infile command -Set callback functions for LOAD DATA LOCAL INFILE -Returns the SQLSTATE error from previous MySQL operation - -Get current system status -Return the number of rows affected in the last query for the given link - - -Bind variables to a prepared statement as parameters -Bind variables to a prepared statement for result storage -Close statement -Move internal result pointer - - -Execute a prepared statement -Fetch results from a prepared statement into the bound variables -Return the number of result columns for the given statement -Free stored result memory for the given statement handle -Initialize statement object -Get the ID generated from the previous INSERT operation -Return the number of rows in statements result set -Return the number of parameter for the given statement -prepare server side statement with query -reset a prepared statement -return result set from statement - - - -Buffer result set on client -Return the current thread ID -Return whether thread safety is given or not -Directly retrieve query results - do not buffer results on client side - -initialize and start embedded server -Open a connection to a mysql server -Returns the numerical value of the error message from last connect command -Returns the text of the error message from previous MySQL operation -returns a character set object -allows to execute multiple queries -sets client character set - - - - -Enforce execution of a query on the master in a master/slave setup - - - - -Enforce execution of a query on a slave in a master/slave setup -sets report level -Bind a PHP array to an Oracle PL/SQL type by name -Bind a PHP variable to an Oracle placeholder by name -Cancel reading from a cursor -Disconnect from database -Append an object to the collection -Assign a collection from another existing collection -Assign element val to collection at index ndx -Retrieve the value at collection index ndx -Return the max value of a collection. For a varray this is the maximum length of the array -Return the size of a collection -Trim num elements from the end of a collection -Commit the current context -Connect to an Oracle database and log on. Returns a new session. -Define a PHP variable to an Oracle column by name -Return the last error of stmt|connection|global. If no error happened returns false. -Execute a parsed statement -Prepare a new row of data for reading -Fetch all rows of result data into an array -Fetch a result row as an array -Fetch a result row as an associative array -Fetch a result row as an object -Fetch a result row as an enumerated array -Tell whether a column is NULL -Tell the name of a column -Tell the precision of a column -Tell the scale of a column -Tell the maximum data size of a column -Tell the data type of a column -Tell the raw oracle data type of a column -Deletes collection object -Deletes large object description -Free all resources associated with a statement -Toggle internal debugging output for the OCI extension -Appends data from a LOB to another LOB -Closes lob descriptor -Copies data from a LOB to another LOB -Checks if EOF is reached -Erases a specified portion of the internal LOB, starting at a specified offset -Writes a large object into a file -Flushes the LOB buffer -Loads file into a LOB -Tests to see if two LOB/FILE locators are equal -Loads a large object -Reads particular part of a large object -Rewind pointer of a LOB -Saves a large object -Moves the pointer of a LOB -Returns size of a large object -Tells LOB pointer position -Truncates a LOB -Writes data to current position of a LOB -Writes temporary blob -Initialize a new collection -Connect to an Oracle database and log on. Returns a new session. -Return a new cursor (Statement-Handle) - use this to bind ref-cursors! -Initialize a new empty descriptor LOB/FILE (LOB is default) -Return the number of result columns in a statement -Return the row count of an OCI statement -Parse a query and return a statement -Changes the password of an account -Connect to an Oracle database using a persistent connection and log on. Returns a new session. -Return a single column of result data -Rollback the current context -Return a string containing server version information -Sets the number of rows to be prefetched on execute to prefetch_rows for stmt -Return the query type of an OCI statement -Fetch a row of result data into an array -Returns current state of buffering for a LOB -Enables/disables buffering for a LOB - - - - - - - - - - - - -Toggle autocommit mode or get status -Handle binary column data -Close an ODBC connection -Close all ODBC connections -Returns a result identifier that can be used to fetch a list of columns and associated privileges for the specified table -Returns a result identifier that can be used to fetch a list of column names in specified tables -Commit an ODBC transaction -Connect to a datasource -Get cursor name -Return information about the currently connected data source -Get the last error code -Get the last error message -Prepare and execute an SQL statement -Execute a prepared statement -Fetch a result row as an associative array -Fetch one result row into an array -Fetch a result row as an object -Fetch a row -Get the length (precision) of a column -Get a column name -Return column number -Get the scale of a column -Get the datatype of a column -Returns a result identifier to either a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table -Free resources associated with a result -Returns a result identifier containing information about data types supported by the data source -Handle LONG columns -Checks if multiple results are avaiable -Get number of columns in a result -Get number of rows in a result -Establish a persistent connection to a datasource -Prepares a statement for execution -Returns a result identifier listing the column names that comprise the primary key for a table -Returns a result identifier containing the list of input and output parameters, as well as the columns that make up the result set for the specified procedures -Returns a result identifier containg the list of procedure names in a datasource -Get result data -Print result as HTML table -Rollback a transaction -Sets connection or statement options -Returns a result identifier containing either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction -Returns a result identifier that contains statistics about a single table and the indexes associated with the table -Returns a result identifier containing a list of tables and the privileges associated with each table -Call the SQLTables function - -Exports a CSR to file or a var -Exports a CSR to file -Returns the subject of a CERT or FALSE on error -Returns the subject of a CERT or FALSE on error -Generates a privkey and CSR -Signs a cert with another CERT -Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages -Opens data -Creates and exports a PKCS12 to a var -Creates and exports a PKCS to file -Parses a PKCS12 to an array -Decrypts the S/MIME message in the file name infilename and output the results to the file name outfilename. recipcert is a CERT for one of the recipients. recipkey specifies the private key matching recipcert, if recipcert does not include the key -Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile -Signs the MIME message in the file named infile with signcert/signkey and output the result to file name outfile. headers lists plain text headers to exclude from the signed portion of the message, and should include to, from and subject as a minimum -Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers -Gets an exportable representation of a key into a string or file -Gets an exportable representation of a key into a file -Frees a key -returns an array with the key details (bits, pkey, type) -Gets private keys -Gets public key from X.509 certificate -Generates a new private key -Decrypts data with private key -Encrypts data with private key -Decrypts data with public key -Encrypts data with public key -Seals data -Signs data -Verifys data -Checks if a private key corresponds to a CERT -Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs -Exports a CERT to file or a var -Exports a CERT to file or a var -Frees X.509 certificates -Returns an array of the fields/values of the CERT -Reads X.509 certificates -Set an alarm clock for delivery of a signal -Executes specified program in current process space as defined by exec(2) -Forks the currently running process following the same behavior as the UNIX fork() system call -Get the priority of any process -Change the priority of any process -Assigns a system signal handler to a PHP function -Waits on or returns the status of a forked child as defined by the waitpid() system call -Waits on or returns the status of a forked child as defined by the waitpid() system call -Returns the status code of a child's exit -Returns true if the child status code represents a successful exit -Returns true if the child status code represents a process that was terminated due to a signal -Returns true if the child status code represents a stopped process (WUNTRACED must have been used with waitpid) -Returns the number of the signal that caused the process to stop who's status code is passed -Returns the number of the signal that terminated the process who's status code is passed -Searches array and returns entries which match regex -Returns the error code of the last regexp execution. -Perform a Perl-style regular expression match -Perform a Perl-style global regular expression match -Quote regular expression characters plus an optional character -Perform Perl-style regular expression replacement. -Perform Perl-style regular expression replacement using replacement callback. -Split string into an array using a perl-style regular expression as a delimiter -Return array of available PDO drivers - -Prevents serialization of a PDO instance -Prevents use of a PDO instance that has been unserialized -Initiates a transaction -Commit a transaction -Fetch the error code associated with the last operation on the database handle -Fetch extended error information associated with the last operation on the database handle -Execute a query that does not return a row set, returning the number of affected rows -Get an attribute -Returns the id of the last row that we affected on this connection. Some databases require a sequence or table name to be passed in. Not always meaningful. -Prepares a statement for execution and returns a statement object -Prepare and execute $sql; returns the statement object for iteration -quotes string for use in a query. The optional paramtype acts as a hint for drivers that have alternate quoting styles. The default value is PDO_PARAM_STR -roll back a transaction -Set an attribute -Return array of available PDO drivers -Prevents serialization of a PDOStatement instance -Prevents use of a PDOStatement instance that has been unserialized -bind a column to a PHP variable. On each row fetch $param will contain the value of the corresponding column. $column is the 1-based offset of the column, or the column name. For portability, don't call this before execute(). -bind a parameter to a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). This isn't supported by all drivers. It should be called prior to execute(). -bind an input parameter to the value of a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). It should be called prior to execute(). -Closes the cursor, leaving the statement ready for re-execution. -Returns the number of columns in the result set -A utility for internals hackers to debug parameter internals -Fetch the error code associated with the last operation on the statement handle -Fetch extended error information associated with the last operation on the statement handle -Execute a prepared statement, optionally binding parameters -Fetches the next row and returns it, or false if there are no more rows -Returns an array of all of the results. -Returns a data of the specified column in the result set. -Fetches the next row and returns it as an object. -Get an attribute -Returns meta data for a numbered column -Advances to the next rowset in a multi-rowset statement handle. Returns true if it succeded, false otherwise -Returns the number of rows in a result set, or the number of rows affected by the last execute(). It is not always meaningful. -Set an attribute -Changes the default fetch mode for subsequent fetches (params have different meaning for different fetch modes) -Returns the number of affected tuples -Cancel request -Get the current client encoding -Close a PostgreSQL connection -Open a PostgreSQL connection -Get connection is busy or not -Reset connection (reconnect) -Get connection status -Check and convert values for PostgreSQL SQL statement -Copy table from array -Copy table to array -Get the database name -Delete records has ids (id=>value) -Sync with backend. Completes the Copy command -Escape binary for bytea type -Escape string for text/char type -Execute a prepared query -Fetch all rows into array -Fetch all rows into array -Fetch a row as an array -Fetch a row as an assoc array -Fetch a row as an object -Returns values from a result identifier -Get a row as an enumerated array -Test if a field is NULL -Returns the name of the field -Returns the field number of the named field -Returns the printed length -Returns the internal size of the field -Returns the name of the table field belongs to, or table's oid if oid_only is true -Returns the type name for the given field -Returns the type oid for the given field -Free result memory -Get asynchronous notification -Get backend(server) pid -Get asynchronous query result -Returns the host name associated with the connection -Insert values (filed=>value) to table -Get the error message string -Returns the last notice set by the backend -Returns the last object identifier -Close a large object -Create a large object -Export large object direct to filesystem -Import large object direct from filesystem -Open a large object and return fd -Read a large object -Read a large object and send straight to browser -Seeks position of large object -Returns current position of large object -Delete a large object -Write a large object -Get meta_data -Return the number of fields in the result -Return the number of rows in the result -Get the options associated with the connection -Open a persistent PostgreSQL connection -Ping database. If connection is bad, try to reconnect. -Return the port number associated with the connection -Prepare a query for future execution -Send null-terminated string to backend server -Execute a query -Execute a query -Get error message associated with result -Get error message field associated with result -Set internal row offset -Get status of query result -Select records that has ids (id=>value) -Executes prevriously prepared stmtname asynchronously -Asynchronously prepare a query for future execution -Send asynchronous query -Send asynchronous parameterized query -Set client encoding -Set error verbosity -Enable tracing a PostgreSQL connection -Get transaction status -Return the tty name associated with the connection -Unescape binary for bytea type -Disable tracing of a PostgreSQL connection -Update table using values (field=>value) and ids (id=>value) -Returns an array with client, protocol and server version (when available) -Determine accessibility of a file (POSIX.1 5.6.3) -Generate terminal path name (POSIX.1, 4.7.1) -Retrieve the error number set by the last posix function which failed. -Get working directory pathname (POSIX.1, 5.2.2) -Get the current effective group id (POSIX.1, 4.2.1) -Get the current effective user id (POSIX.1, 4.2.1) -Get the current group id (POSIX.1, 4.2.1) -Group database access (POSIX.1, 9.2.1) -Group database access (POSIX.1, 9.2.1) -Get supplementary group id's (POSIX.1, 4.2.3) -Get user name (POSIX.1, 4.2.4) -Get the process group id of the specified process (This is not a POSIX function, but a SVR4ism, so we compile conditionally) -Get current process group id (POSIX.1, 4.3.1) -Get the current process id (POSIX.1, 4.1.1) -Get the parent process id (POSIX.1, 4.1.1) -User database access (POSIX.1, 9.2.2) -User database access (POSIX.1, 9.2.2) -Get system resource consumption limits (This is not a POSIX function, but a BSDism and a SVR4ism. We compile conditionally) -Get process group id of session leader (This is not a POSIX function, but a SVR4ism, so be compile conditionally) -Get the current user id (POSIX.1, 4.2.1) -Calculate the group access list for the user specified in name. -Determine if filedesc is a tty (POSIX.1, 4.7.1) -Send a signal to a process (POSIX.1, 3.3.2) -Make a FIFO special file (POSIX.1, 5.4.2) -Make a special or ordinary file (POSIX.1) -Set effective group id -Set effective user id -Set group id (POSIX.1, 4.2.2) -Set process group id for job control (POSIX.1, 4.3.3) -Create session and set process group id (POSIX.1, 4.3.2) -Set user id (POSIX.1, 4.2.2) -Retrieve the system error message associated with the given errno. -Get process times (POSIX.1, 4.5.2) -Determine terminal device name (POSIX.1, 4.7.2) -Get system name (POSIX.1, 4.4.1) -Adds a word to a personal list -Adds a word to the current session -Returns true if word is valid -Clears the current session -Create a new config to be used later to create a manager -location of language data files -location of the main word list -Ignore words <= n chars -Select mode for config (PSPELL_FAST, PSPELL_NORMAL or PSPELL_BAD_SPELLERS) -Use a personal dictionary for this config -Use a personal dictionary with replacement pairs for this config -Consider run-together words as valid components -Save replacement pairs when personal list is saved for this config -Load a dictionary -Load a dictionary based on the given config -Load a dictionary with a personal wordlist -Saves the current (personal) wordlist -Notify the dictionary of a user-selected replacement -Returns array of suggestions -Reads a line -Adds a line to the history -Initializes the readline callback interface and terminal, prints the prompt and returns immediately -Removes a previously installed callback handler and restores terminal settings -Informs the readline callback interface that a character is ready for input -Clears the history -Readline completion function? -Gets/sets various internal readline variables. -Lists the history -Inform readline that the cursor has moved to a new line -Reads the history -Ask readline to redraw the display -Writes the history -Recode file input into file output according to request -Recode string str according to request string -Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire -Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter -Deserializes data and reinitializes the variables -Destroy the current session and all data associated with it -Serializes the current setup and returns the serialized representation -Return the session cookie parameters -Return the current session id. If newid is given, the session id is replaced with newid -Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname -Return the current session name. If newname is given, the session name is replaced with newname -Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. -Return the current save path passed to module_name. If newname is given, the save path is replaced with newname -Set session cookie parameters -Sets user-level functions -Begin session - reinitializes freezed variables, registers browsers etc -Unset all registered variables -Write session data and end session -Add Attribute with optional namespace information -Add Element with optional namespace information -Return a well-formed XML string based on SimpleXML element -Identifies an element's attributes -Finds children of given node -Return all namespaces registered with document -Finds children of given node -Return all namespaces in use -Creates a prefix/ns context for the next XPath query -Runs XPath query on the XML data -SimpleXMLElement constructor -Return a string to confirm that the module is compiled in -* * Generic SNMPv3 object fetcher * From here is passed on the the common internal object fetcher. * * st=SNMP_CMD_GET snmp3_get() - query an agent and return a single value. * st=SNMP_CMD_GETNEXT snmp3_getnext() - query an agent and return the next single value. * st=SNMP_CMD_WALK snmp3_walk() - walk the mib and return a single dimensional array * containing the values. * st=SNMP_CMD_REALWALK snmp3_real_walk() - walk the mib and return an * array of oid,value pairs. * st=SNMP_CMD_SET snmp3_set() - query an agent and set a single value * -Fetch a SNMP object -Fetch a SNMP object -Return all objects including their respective object id withing the specified one -Set the value of a SNMP object -Return all objects under the specified object id -Fetch the value of a SNMP object -Fetch the value of a SNMP object -Fetch the value of a SNMP object -Fetch the value of a SNMP object -Fetch the value of a SNMP object -Return the current status of quick_print -Return the method how the SNMP values will be returned -Reads and parses a MIB file into the active MIB tree. -Return all values that are enums with their enum value instead of the raw integer -Set the OID output format. -Return all objects including their respective object id withing the specified one -Specify the method how the SNMP values will be returned -Fetch a SNMP object -Fetch a SNMP object -Return all objects including their respective object id withing the specified one -Set the value of a SNMP object -Return all objects under the specified object id -SoapClient::__doRequest() -Returns array of cookies. -Returns last SOAP request headers -Returns last SOAP response headers -Sets cookie thet will sent with SOAP request. The call to this function will effect all folowing calls of SOAP methods. If value is not specified cookie is removed. -Sets the location option (the endpoint URL that will be touched by the following SOAP requests). If new_location is not specified or null then SoapClient will use endpoint from WSDL file. The function returns old value of location options. -Sets SOAP headers for subsequent calls (replaces any previous values). If no value is specified, all of the headers are removed. -Adds one or several functions those will handle SOAP requests -Returns list of defined functions -Sets class which will handle SOAP requests -Sets object which will handle SOAP requests -Accepts a connection on the listening socket fd -Binds an open socket to a listening port, port is only specified in AF_INET family. -Clears the error on the socket or the last error code. -Closes a file descriptor -Opens a connection to addr:port on the socket specified by socket -Creates an endpoint for communication in the domain specified by domain, of type specified by type -Opens a socket on port to accept connections -Creates a pair of indistinguishable sockets and stores them in fds. -Gets socket options for the socket -Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type. -Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type. -Returns the last socket error (either the last used or the provided socket resource) -Sets the maximum number of connections allowed to be waited for on the socket specified by fd -Reads a maximum of length bytes from socket -Receives data from a connected socket -Receives data from a socket, connected or not -Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usec -Sends data to a connected socket -Sends a message to a socket, whether it is connected or not -Sets blocking mode on a socket resource -Sets nonblocking mode on a socket resource -Sets socket options for the socket -Shuts down a socket for receiving, sending, or both. -Returns a string describing an error -Writes the buffer to the socket resource, length is optional -Return all classes and interfaces implemented by SPL -Return an array containing the names of all parent classes -Default implementation for __autoload() -Try all registerd autoload function to load the requested class -Register and return default file extensions for spl_autoload -Register given function as __autoload() implementation -Unregister given function as __autoload() implementation -Return an array containing the names of all clsses and interfaces defined in SPL -Return hash id for given object -Move to next entry -Rewind array back to the start -Seek to position. -Check whether array contains more entries -proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) U Cronstructs a new array iterator from a path. -proto void ArrayIterator::append(mixed $newval) U Appends the value (cannot be called for objects). -proto int ArrayIterator::asort() U Sort the entries by values. -proto int ArrayIterator::count() U Return the number of elements in the Iterator. -Get flags -Create a new iterator from a ArrayObject instance -Get the class used in getIterator. -proto int ArrayIterator::ksort() U Sort the entries by key. -proto int ArrayIterator::natcasesort() U Sort the entries by key using case insensitive "natural order" algorithm. -proto int ArrayIterator::natsort() U Sort the entries by values using "natural order" algorithm. -proto bool ArrayIterator::offsetExists(mixed $index) U Returns whether the requested $index exists. -proto mixed ArrayIterator::offsetGet(mixed $index) U Returns the value at the specified $index. -proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) U Sets the value at the specified $index to $newval. -proto void ArrayIterator::offsetUnset(mixed $index) U Unsets the value at the specified $index. -Set flags -Set the class used in getIterator. -proto int ArrayIterator::uasort(callback cmp_function) U Sort the entries by values user defined function. -proto int ArrayIterator::uksort(callback cmp_function) U Sort the entries by key using user defined function. -Create a sub iterator for the current element (same class as $this) -Check whether current element has children (e.g. is an array) -Cronstructs a new dir iterator from a path. -Return number of entries in directory, works only when USE_GLOB is in effect -Return this (needed for Iterator interface) -Returns filename component of current dir entry -Returns an iterator for the current entry if it is a directory -Return filename of current dir entry -Returns true if current entry is '.' or '..' -Return current dir entry -Move to next entry -Rewind dir back to the start -Check whether dir contains more entries -Cronstructs a new dir iterator from a path. -Return getFilename(), getFileInfo() or $this depending on flags -Get sub path -Get sub path and file name -Returns whether current entry is a directory and not '.' or '..' -Return getPathname() or getFilename() depending on flags -Move to next entry -Rewind dir back to the start -Cronstructs a new SplFileInfo from a path. -Get last access time of file -Returns filename component of path -Get inode modification time of file -Get/copy file info -Return filename only -Get file group -Get file inode -Return the target of a symbolic link -Get last modification time of file -Get file owner -Return the path -Get/copy file info -Return path and filename -Get file permissions -Return the resolved path -Get file size -Get file type -Returns true if file is directory -Returns true if file is executable -Returns true if file is a regular file -Returns true if file is symbolic link -Returns true if file can be read -Returns true if file can be written -Open the current file -Class to use in openFile() -Class to use in getFileInfo(), getPathInfo() -Construct a new file object -Return current line from file -Return whether end of file is reached -Flush the file -Get a character form the file -Return current line as csv -Rturn next line from file -Get a line from file pointer and strip HTML tags -Portable file locking -Output all remaining data from a file pointer -Implements a mostly ANSI compatible fscanf() -Return current file position -Stat() on a filehandle -Return current file position -Truncate file to 'size' length -Binary-safe file write -Read NULL -Get the delimiter and enclosure character used in fgetcsv -Get file handling flags -Get maximum line length -Return false -Return line number -Read next line -Rewind the file and read the first line -Seek to specified line -Set the delimiter and enclosure character used in fgetcsv -Set file handling flags -Set maximum line length -Return !eof() -Construct a new temp file object -Create an AppendIterator -Append an iterator -Get access to inner ArrayIterator -Get index of iterator -Forward to next element -Rewind to the first iterator and rewind the first iterator, too -Check if the current state is valid -Construct a CachingIterator from an Iterator -Return the string representation of the current element -Number of cached elements -Return the cache -Return the internal flags -Check whether the inner iterator has a valid next element -Move the iterator forward -Return whether the requested index exists -Return the internal cache if used -Set given index in cache -Unset given index in cache -Rewind the iterator -Set the internal flags -Check whether the current element is valid -Throws exception BadMethodCallException -Throws exception BadMethodCallException -Does nothing -Does nothing -Return false -Create an Iterator from another iterator -proto mixed CachingIterator::current() U proto mixed LimitIterator::current() U proto mixed ParentIterator::current() U proto mixed IteratorIterator::current() U proto mixed NoRewindIterator::current() U proto mixed AppendIterator::current() U Get the current element value -proto Iterator CachingIterator::getInnerIterator() U proto Iterator LimitIterator::getInnerIterator() U proto Iterator ParentIterator::getInnerIterator() U Get the inner iterator -proto mixed CachingIterator::key() U proto mixed LimitIterator::key() U proto mixed ParentIterator::key() U proto mixed IteratorIterator::key() U proto mixed NoRewindIterator::key() U proto mixed AppendIterator::key() U Get the current key -Move the iterator forward -Rewind the iterator -proto bool ParentIterator::valid() U proto bool IteratorIterator::valid() U proto bool NoRewindIterator::valid() U Check whether the current element is valid -Create an iterator from another iterator -Prevent a call to inner iterators rewind() (internally the current data will be fetched if valid()) -Create an iterator from anything that is traversable -Return the current position -Move the iterator forward -Rewind the iterator to the specified starting offset -Seek to the given position -Check whether the current element is valid -Create an iterator from another iterator -Return inner iterators current() -Return inner iterators key() -Return inner iterators next() -Prevent a call to inner iterators rewind() -Return inner iterators valid() -Create a ParentIterator from a RecursiveIterator -proto void IteratorIterator::next() U proto void NoRewindIterator::next() U Move the iterator forward -proto void IteratorIterator::rewind() Rewind the iterator -Create an iterator from a RecursiveIterator -Return the inner iterator's children as a RecursiveCachingIterator -Check whether the current element of the inner iterator has children -Create a RecursiveFilterIterator from a RecursiveIterator -Return the inner iterator's children contained in a RecursiveFilterIterator -Check whether the inner iterator's current element has children -Called when recursing one level down -Called when iteration begins (after first rewind() call) -Return children of current element -Called for each element to test whether it has children -Access the current element value -Called when end recursing one level -Called when iteration ends (when valid() first returns false -Get the current depth of the recursive iteration -The current active sub iterator -The current active sub iterator or the iterator at specified level -Access the current key -Move forward to the next element -Called when the next element is available -Rewind the iterator to the first element of the top level inner iterator. -Set the maximum allowed depth (or any depth if pmax_depth = -1] -Check whether the current position is valid -Create an RecursiveRegexIterator from another recursive iterator and a regular expression -Return the inner iterator's children contained in a RecursiveRegexIterator -Create an RegexIterator from another iterator and a regular expression -Match (string)current() against regular expression -Returns current PREG flags (if in use or NULL) -Returns current operation flags -Returns current operation mode -Set operation flags -Set new operation mode -Set PREG flags -Construct a LimitIterator from an Iterator with a given starting offset and optionally a maximum count -Calls a function for every element in an iterator -Count the elements in an iterator -Copy the iterator into an array -Attaches an object to the storage if not yet contained -Determine whethe an object is contained in the storage -Determine number of objects in storage - -Detaches an object from the storage - - - - - - -Get number of child elements -Get current element -Get child element iterator -Check whether element has children (elements) -Get name of current child element -Move to next element -Rewind to first element -Check whether iteration is valid -Executes a query against a given database and returns an array of arrays. -Set busy timeout duration. If ms <= 0, all busy handlers are disabled. -Returns the number of rows that were changed by the most recent SQL statement. -Closes an open sqlite database. -Fetches a column from the current row of a result set. -Registers an aggregate function for queries. -Registers a "regular" function for queries. -Fetches the current row from a result set as an array. -Returns the textual description of an error code. -Escapes a string for use as a query parameter. -Executes a result-less query against a given database -Opens a SQLite database and creates an object for it. Will create the database if it does not exist. -Fetches all rows from a result set as an array of arrays. -Fetches the next row from a result set as an array. -Return an array of column types from a particular table. -Fetches the next row from a result set as an object. -Fetches the first column of a result set as a string. -Returns the name of a particular field of a result set. -* Returns whether a previous row is available. -Return the current row index of a buffered result. -Returns the error code of the last error for a database. -Returns the rowid of the most recently inserted row. -Returns the encoding (iso8859 or UTF-8) of the linked SQLite library. -Returns the version of the linked SQLite library. -Seek to the next row number of a result set. -Returns the number of fields in a result set. -Returns the number of rows in a buffered result set. -Opens a SQLite database. Will create the database if it does not exist. -Opens a persistent handle to a SQLite database. Will create the database if it does not exist. -* Seek to the previous row number of a result set. -Executes a query against a given database and returns a result handle. -Seek to the first row number of a buffered result set. -Seek to a particular row number of a buffered result set. -Executes a query and returns either an array for one single column or the value of the first row. -Decode binary encoding on a string parameter passed to an UDF. -Apply binary encoding (if required) to a string to return from an UDF. -Executes a query that does not prefetch and buffer all data. -Returns whether more rows are available. -Retuns an array with all string keys lowercased [or uppercased] -Split array into chunks -Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values -Return the value as key and the frequency of that value in input as value -Returns the entries of arr1 that have values which are not present in any of the others arguments. -Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal -Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. -Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. -Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. -Create an array containing num elements starting with index start_key each initialized to val -Create an array using the elements of the first parameter as keys each initialized to val -Filters elements from the array via the callback. -Return array with key <-> value flipped -Returns the entries of arr1 that have values which are present in all the other arguments -Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check -Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. -Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. -Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. -Checks if the given key or index exists in the array -Return just the keys from the input array, optionally only for the specified search_value -Applies the callback to the elements in given arrays. -Merges elements from passed arrays into one array -Recursively merges elements from passed arrays into one array -Sort multiple arrays at once similar to how ORDER BY clause works in SQL -Returns a copy of input array padded with pad_value to size pad_size -Pops an element off the end of the array -Returns the product of the array entries -Pushes elements onto the end of the array -Return key/keys for random entry/entries in the array -Iteratively reduce the array to a single value via the callback. -Return input as a new array with the order of the entries reversed -Searches the array for a given value and returns the corresponding key if successful -Pops an element off the beginning of the array -Returns elements specified by offset and length -Removes the elements designated by offset and length and replace them with supplied array -Returns the sum of the array entries -Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. -Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Entries are compared by user supplied function. -Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. -Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. -Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. -Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. -Removes duplicate values from array -Pushes elements onto the beginning of the array -Return just the values from the input array -Apply a user function to every member of an array -Apply a user function recursively to every member of an array -Sort an array in reverse order and maintain index association -Sort an array and maintain index association -Creates a hash containing variables and their values -Count the number of elements in a variable (usually an array) -Return the element currently pointed to by the internal array pointer -Advances array argument's internal pointer to the last element and return it -Imports variables into symbol table from an array -Checks if the given value exists in the array -Return the key of the element currently pointed to by the internal array pointer -Sort an array by key value in reverse order -Sort an array by key -Return the highest value in an array or a series of arguments -Return the lowest value in an array or a series of arguments -Sort an array using case-insensitive natural sort -Sort an array using natural sort -Move array argument's internal pointer to the next element and return it -Move array argument's internal pointer to the previous element and return it -Create an array containing the range of integers or characters from low to high (inclusive) -Set array argument's internal pointer to the first element and return it -Sort an array in reverse order -Randomly shuffle the contents of an array -Sort an array -Sort an array with a user-defined comparison function and maintain index association -Sort an array by keys using a user-defined comparison function -Sort an array by values using a user-defined comparison function -Checks if assertion is false -Set/get the various assert flags -Decodes string using MIME base64 algorithm -Encodes string using MIME base64 algorithm -Call a user function which is the first parameter -Call a user function which is the first parameter with the arguments contained in array -Call a user method on a specific object or class -Call a user method on a specific object or class using a parameter array -Returns true if client disconnected -Returns the connection status bitfield -Given the name of a constant this function will return the constant's associated value -Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet. -Send an error message somewhere -Flush the output buffer -Get the value of a PHP configuration option -Get the name of the owner of the current PHP script -Get the current include_path configuration option -Get the value of an environment variable -Get options from the command line argument list -Returns protocol number associated with name as per /etc/protocols -Returns protocol name associated with protocol number proto -Returns port associated with service. Protocol must be "tcp" or "udp" -Returns service name associated with port. Protocol must be "tcp" or "udp" -Syntax highlight a source file -Syntax highlight a string or optionally return it -Set whether we want to ignore a user abort event or not -Import GET/POST/Cookie variables into the global scope -Converts a packed inet address to a human readable IP address string -Converts a human readable IP address to a packed binary string -Get a configuration option -Get all configuration options -Restore the value of a configuration option specified by varname -Set a configuration option, returns false on error and the old value of the configuration option on success -Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address -Check if file was created by rfc1867 upload -Converts an (IPv4) Internet network address into a string in Internet standard dotted format -Move a file if and only if it was created by an upload -Parse configuration file -Return source with stripped comments and whitespace -Prints out or returns information about the specified variable -Set the value of an environment variable -Register a user-level function to be called on request termination -Registers a tick callback function -Restore the value of the include_path configuration option -Sets the include_path configuration option -Delay for a given number of seconds - -Delay for a number of seconds and nano seconds -Make the script sleep until the specified time -Unregisters a tick callback function -Delay for a given number of micro seconds -Get information about the capabilities of a browser. If browser_name is omitted or null, HTTP_USER_AGENT is used. Returns an object by default; if return_array is true, returns an array. -Calculate the crc32 polynomial of a string -Hash a string -Convert from one Cyrillic character set to another -Parse a time/date generated with strftime() -Change the current directory -Change root directory -Close directory connection identified by the dir_handle -Directory class with properties, handle and class and methods read, rewind and close -Gets the current directory -Find pathnames matching a pattern -Open a directory and return a dir_handle -Read directory entry from dir_handle -Rewind dir_handle back to the start -List files & directories inside the specified path -Load a PHP extension at runtime -Check DNS records corresponding to a given Internet host name or IP address -Get MX records corresponding to a given Internet host name -Get the Internet host name corresponding to a given IP address -Get the IP address corresponding to a given Internet host name -Return a list of IP addresses that a given hostname resolves to. -Quote and escape an argument for use in a shell command -Escape shell metacharacters -Execute an external program -Execute an external program and display raw output -Change the priority of the current process -Execute command via shell and return complete output as string -Execute an external program and display output -Copy a file -Close an open file pointer -Test for end-of-file on a file pointer -Flushes output -Get a character from file pointer -Get line from file pointer and parse for CSV fields -Get a line from file pointer -Get a line from file pointer and strip HTML tags -Read entire file into an array -Read the entire file into a string -Write/Create a file with contents data and return the number of bytes written -Portable file locking -Match filename against pattern -Open a file or a URL and return a file pointer -Output all remaining data from a file pointer -Format line as CSV and write to file pointer -Binary-safe file read -Implements a mostly ANSI compatible fscanf() -Seek on a file pointer -Stat() on a filehandle -Get file pointer's read/write position -Truncate file to 'size' length -Binary-safe file write -Extracts all meta tag content attributes from a file and returns an array -Create a directory -Close a file pointer opened by popen() -Execute a command and open either a read or a write pipe to it -Output a file or a URL -Return the resolved path -Rename a file -Rewind the position of a file pointer -Remove a directory -Returns directory path used for temporary files -Create a unique filename in a directory -Create a temporary file that will be deleted automatically after use -Return or change the umask -Delete a file -Change file group -Change file mode -Clear file stat cache -Get free disk space for filesystem that path is on -Get total disk space for filesystem that path is on -Returns true if filename exists -Get last access time of file -Get inode modification time of file -Get file group -Get file inode -Get last modification time of file -Get file owner -Get file permissions -Get file size -Get file type -Returns true if file is directory -Returns true if file is executable -Returns true if file is a regular file -Returns true if file is symbolic link -Returns true if file can be read -Returns true if file can be written -Change symlink group -Give information about a file or symbolic link -Give information about a file -Set modification time of file -Output a formatted string into a stream -Output a formatted string -Return a formatted string -Output a formatted string into a stream -Output a formatted string -Return a formatted string -Open Internet or Unix domain socket connection -Open persistent Internet or Unix domain socket connection -Convert a pathname and a project identifier to a System V IPC key -Sends a raw HTTP header -Return list of headers to be sent / already sent -Returns true if headers have already been sent, false otherwise -Send a cookie -Send a cookie with no url encoding of the value -Returns the internal translation table used by htmlspecialchars and htmlentities -Convert all HTML entities to their applicable characters -Convert all applicable characters to HTML entities -Convert special characters to HTML entities -Convert special HTML entities back to characters -Generates a form-encoded query string from an associative array or object. -Get the size of an image as 4-element array -Get file extension for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype -Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype -Return the special ID used to request the PHP logo in phpinfo screens -Return the actual loaded ini filename -Return comma-separated string of .ini files parsed from the additional ini dir -Return the special ID used to request the PHP logo in phpinfo screens -Return the special ID used to request the PHP logo in phpinfo screens -Return the current SAPI module name -Return information about the system PHP was built on -Prints the list of people who've contributed to the PHP project -Output a page of useful information about PHP and the current request -Return the current PHP version -Return the special ID used to request the Zend logo in phpinfo screens -Embed binary IPTC data into a JPEG image. -Parse binary IPTC-data into associative array -Returns a value from the combined linear congruential generator -Calculate Levenshtein distance between two strings -Create a hard link -Returns the st_dev field of the UNIX C stat structure describing the link -Return the target of a symbolic link -Create a symbolic link -Calculate EZMLM list hash value. -Send an email message -Return the absolute value of the number -Return the arc cosine of the number in radians -Returns the inverse hyperbolic cosine of the number, i.e. the value whose hyperbolic cosine is number -Returns the arc sine of the number in radians -Returns the inverse hyperbolic sine of the number, i.e. the value whose hyperbolic sine is number -Returns the arc tangent of the number in radians -Returns the arc tangent of y/x, with the resulting quadrant determined by the signs of y and x -Returns the inverse hyperbolic tangent of the number, i.e. the value whose hyperbolic tangent is number -Converts a number in a string from any base <= 36 to any base <= 36 -Returns the decimal equivalent of the binary number -Returns the next highest integer value of the number -Returns the cosine of the number in radians -Returns the hyperbolic cosine of the number, defined as (exp(number) + exp(-number))/2 -Returns a string containing a binary representation of the number -Returns a string containing a hexadecimal representation of the given number -Returns a string containing an octal representation of the given number -Converts the number in degrees to the radian equivalent -Returns e raised to the power of the number -Returns exp(number) - 1, computed in a way that accurate even when the value of number is close to zero -Returns the next lowest integer value from the number -Returns the remainder of dividing x by y as a float -Returns the decimal equivalent of the hexadecimal number -Returns sqrt(num1*num1 + num2*num2) -Returns whether argument is finite -Returns whether argument is infinite -Returns whether argument is not a number -Returns the natural logarithm of the number, or the base log if base is specified -Returns the base-10 logarithm of the number -Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero -Formats a number with grouped thousands -Returns the decimal equivalent of an octal string -Returns an approximation of pi -Returns base raised to the power of exponent. Returns integer result when possible -Converts the radian number to the equivalent number in degrees -Returns the number rounded to specified precision -Returns the sine of the number in radians -Returns the hyperbolic sine of the number, defined as (exp(number) - exp(-number))/2 -Returns the square root of the number -Returns the tangent of the number in radians -Returns the hyperbolic tangent of the number, defined as sinh(number)/cosh(number) -Calculate the md5 hash of a string -Calculate the md5 hash of given filename -Break english phrases down into their phonemes -Returns an array of usage statistics -Returns the current time as array -Returns either a string or a float containing the current time in seconds and microseconds -Takes one or more arguments and packs them into a binary string according to the format argument -Unpack binary string into named array elements according to format argument -Get time of last page modification -Get PHP script owner's GID -Get the inode of the current script being parsed -Get current process ID -Get PHP script owner's UID -close a process opened by proc_open -get information about a process opened by proc_open -Run a process with more control over it's file descriptors -kill a process opened by proc_open -Convert a quoted-printable string to an 8 bit string -Returns the maximum value a random number can have -Returns the maximum value a random number from Mersenne Twister can have -Returns a random number from Mersenne Twister -Seeds Mersenne Twister random number generator -Returns a random number -Seeds random number generator -Regular expression match -Replace regular expression -Case-insensitive regular expression match -Case insensitive replace regular expression -Split string into array by regular expression -Split string into array by regular expression case-insensitive -Make regular expression for case insensitive match -Calculate the sha1 hash of a string -Calculate the sha1 hash of given filename -Calculate the soundex key of a string -Create a file context and optionally set parameters -Get a handle on the default file/stream context and optionally set parameters -Retrieve options for a stream/wrapper/context -* Overloaded form: stream_context_set_option(resource context|resource stream, array options) * Set an option (or several options) for a wrapper -Set parameters for a file context -Reads up to maxlen bytes from source stream and writes them to dest stream. -Convenience wrapper for ini_set('unicode.stream_encoding', $encoding) -Set character set for stream encoding UTODO: Return current encoding charset -Append a filter to a stream -Prepend a filter to a stream -Flushes any data in the filter's internal buffer, removes it from the chain, and frees the resource -Reads all remaining bytes (or up to maxlen bytes) from a stream and returns them as a string. -Read up to maxlen bytes from a stream or until the ending string is found -Retrieves header/meta data from streams/file pointers -Retrieves list of registered socket transports -Retrieves list of registered stream wrappers - -Determine what file will be opened by calls to fopen() with a relative path -Runs the select() system call on the sets of streams with a timeout specified by tv_sec and tv_usec -Set blocking/non-blocking mode on a socket or stream -Set timeout on stream read to seconds + microseonds -Set file write buffer -Accept a client connection from a server socket -Open a client connection to a remote address -Enable or disable a specific kind of crypto on the stream -Returns either the locally bound or remote name for a socket stream -Creates a pair of connected, indistinguishable socket streams -Receives data from a socket stream -Send data to a socket stream. If target_addr is specified it must be in dotted quad (or [ipv6]) format -Create a server socket bound to localaddress -causes all or part of a full-duplex connection on the socket associated with stream to be shut down. If how is SHUT_RD, further receptions will be disallowed. If how is SHUT_WR, further transmissions will be disallowed. If how is SHUT_RDWR, further receptions and transmissions will be disallowed. -Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\n', '\r', '\t' etc...) -Escapes single quote, double quotes and backslash characters in a string with backslashes -Returns the filename component of the path -Converts the binary representation of data to hex -Converts a codepoint number to a character -Returns split line -Returns info about what characters are used in input -Returns the directory name component of the path -Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned. -Converts logical Hebrew text to visual text -Converts logical Hebrew text to visual text with newline conversion -Joins array elements placing glue string between items and return one string -An alias for implode -Returns numeric formatting information based on the current locale -Strips whitespace from the beginning of a string -Convert monetary value(s) to string -Converts newlines to HTML line breaks -Query language and locale information -Returns the codepoint value of a character -Parses GET/POST/COOKIE data and sets global variables -Returns information about a certain string -Quotes meta characters -Removes trailing whitespace -Set locale information -Calculates the similarity between two strings -Implements an ANSI C compatible sscanf -Parse a CSV string into an array -Replaces all occurrences of search in haystack with replace / case-insensitive -Returns input string padded on the left or right to specified length with pad_string -Returns the input string repeat mult times -Replaces all occurrences of search in haystack with replace -Perform the rot13 transform on a string -Shuffles string. One permutation of all possible is created -Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long. -Counts the number of words inside a string. If format of 1 is specified, then the function will return an array containing all the words found inside the string. If format of 2 is specified, then the function will return an associated array where the position of the word is the key and the word itself is the value. For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters. -An alias for strstr -Compares two strings using the current locale -Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars) -Strips HTML and PHP tags from a string -Strips backslashes from a string. Uses C-style conventions -Finds position of first occurrence of a string within another, case insensitive -Strips backslashes from a string -Finds first occurrence of a string within another, case insensitive -Returns the result of case-insensitive string comparison using 'natural' algorithm -Returns the result of string comparison using 'natural' algorithm -Search a string for any of a set of characters -Finds position of first occurrence of a string within another -Finds the last occurrence of a character in a string within another -Reverse a string -Finds position of last occurrence of a string within another string -Finds position of last occurrence of a string within another string -Finds length of initial segment consisting entirely of characters found in mask. If start or/and length is provided works like strspn(substr($s,$start,$len),$good_chars) -Finds first occurrence of a string within another -Tokenize a string -Makes a string lowercase -Makes a string titlecase -Makes a string uppercase -Translates characters in str using given translation tables -Returns part of a string -Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters -Returns the number of times a substring occurs in the string -Replaces part of a string with another string -Strips whitespace from the beginning and end of a string -Makes a string's first character uppercase -Uppercase the first character of every word in a string -Wraps buffer to selected number of characters using string break char -Close connection to system logger -Initializes all syslog-related variables -Open connection to system logger -Generate a system log message -Get the float value of a variable -Returns the type of the variable -Get the integer value of a variable using the optional base for the conversion -Returns true if variable is an array -Returns true if variable is a native (binary) string -Returns true if variable is a boolean -Returns true if variable is a native, unicode or binary string -Returns true if var is callable. -Returns true if variable is float point -Returns true if variable is a long (integer) -Returns true if variable is null -Returns true if value is a number or a numeric string -Returns true if variable is an object -Returns true if variable is a resource -Returns true if value is a scalar -Returns true if variable is a Unicode or binary string -Returns true if variable is a unicode string -Set the type of the variable -Get the string value of a variable -Generates a unique ID -fetches all the headers sent by the server in response to a HTTP request -Parse a URL and return its components -Decodes URL-encodes string -URL-encodes string -Decodes URL-encoded string -URL-encodes string -Append bucket to brigade -Return a bucket object from the brigade for operating on -Create a new bucket for use on the current stream -Prepend bucket to brigade -Registers a custom filter handler class -Returns a list of registered filters -Non-function -decode a uuencoded string -uuencode a string -Dumps a string representation of an internal zend value to output. -Returns the peak allocated by PHP memory -Returns the allocated by PHP memory -Returns a string representation of variable (which can later be unserialized) -Takes a string representation of variable and recreates it -Dumps a string representation of variable to output -Outputs or returns a string representation of a variable -Dumps a string representation of variable to output (verbose form) -Compares two "PHP-standardized" version number strings -Get number of affected rows in last query -Close Sybase connection -Open Sybase server connection -Move internal row pointer -Fetch row as array -Get field information -Fetch row as object -Get row as enumerated array -Set field offset -Free result memory -Returns the last message from server (over min_message_severity) -Sets the minimum error severity -Sets the minimum message severity -Get number of fields in result -Get number of rows in result -Open persistent Sybase connection -Send Sybase query -Get result data -Select Sybase database -Get number of affected rows in last query -Close Sybase connection -Open Sybase server connection -Move internal row pointer -Sets deadlock retry count -Fetch row as array -Fetch row as array without numberic indices -Get field information -Fetch row as object -Get row as enumerated array -Set field offset -Free result memory -Returns the last message from server (over min_message_severity) -Sets minimum client severity -Sets minimum server severity -Get number of fields in result -Get number of rows in result -Open persistent Sybase connection -Send Sybase query -Get result data -Select Sybase database -Set the error handler, to be called when a server message is raised. If error_func is NULL the handler will be deleted -Send Sybase query -Attach to a message queue -Send a message of type msgtype (must be > 0) to a message queue -Destroy the queue -Send a message of type msgtype (must be > 0) to a message queue -Set information for a message queue -Returns information about a message queue -Acquires the semaphore with the given id, blocking if necessary -Return an id for the semaphore with the given key, and allow max_acquire (default 1) processes to acquire it simultaneously -Releases the semaphore with the given id -Removes semaphore from Unix systems -Creates or open a shared memory segment -Disconnects from shared memory segment -Returns a variable from shared memory -Checks whether a specific entry exists -Inserts or updates a variable in shared memory -Removes shared memory from Unix systems -Removes variable from shared memory -Returns the parent node if available or NULL -Returns true if this node has children -Returns true if this node has siblings -Returns true if this node is ASP -Returns true if this node represents a comment -Returns true if this node is part of a HTML document -Returns true if this node is JSTE -Returns true if this node is PHP -Returns true if this node represents text (no markup) -Returns the Number of Tidy accessibility warnings encountered for specified document. -Execute configured cleanup and repair operations on parsed markup -Returns the Number of Tidy configuration errors encountered for specified document. -Run configured diagnostics on parsed and repaired markup. -Returns the Number of Tidy errors encountered for specified document. -Returns a TidyNode Object starting from the <BODY> tag of the tidy parse tree -Get current Tidy configuration -Return warnings and errors which occured parsing the specified document -Returns a TidyNode Object starting from the <HEAD> tag of the tidy parse tree -Returns a TidyNode Object starting from the <HTML> tag of the tidy parse tree -Get the Detected HTML version for the specified document. -Returns the documentation for the given option name -Return a string representing the parsed tidy markup -Get release date (version) for Tidy library -Returns a TidyNode Object representing the root of the tidy parse tree -Get status of specfied document. -Returns the value of the specified configuration option for the tidy document. -Indicates if the document is a XHTML document. -Indicates if the document is a generic (non HTML/XHTML) XML document. -Parse markup in file or URI -Parse a document stored in a string -Repair a file using an optionally provided configuration file -Repair a string using an optionally provided configuration file -Returns the Number of Tidy warnings encountered for specified document. - - -Compare two strings using collation }}} -Returns a collation attribute }}} -Returns the current collation strength }}} -Set a collation attribute }}} -Set the collation strength }}} -Sort an array using collation }}} -Compare two strings using collation -Create a new Collator object -Returns a collation attribute -Returns default collator -Returns the current collation strength -Set a collation attribute -Sets default collator -Set the collation strength -Sort an array using collation -Create a new Collator object -Returns default locale -Sets default locale -Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name. -Enumerate all code points with their general categories invoking a callback for each category -Get the character representation for the specified digit (optionally in the specified radix) -Translate a human readable character name into a codepoint -Get the "age" of the code point (the Unicode version when it was first designated or assigned a character) -Returns the combining class of the character -Returns the decimal digit value of the character (optionally in the specific radix). -Returns the bidirectional category value for the character, which is used in the Unicode bidirectional algorithm (UAX #9 http://www.unicode.org/reports/tr9/) -Maps the specified character to its "mirror-image" -Get the human readable name associated with the character -Get the numeric value for the character, as defined in the Unicode Character Database -Get the property ID for the given property name -Get the maximum possible value associated with the specified property -Get the minimum possible value for the specified property -Get the Unicode name for the given property -Get the value of a property associated with the character -Get the value ID for the given property value name -Get the Unicode name for the givenproperty value -Returns the general category value for the code point -Determines if all the characters in the string have the specified binary property -Determines if the string consists only of alpanumeric characters -Determines if the string consists only of letter characters -Determines if the string consists only of characters with Alphabetic property -Determines if the string consists of only of base characters -Determines if the string consists only of "blank" characters -Determines if the string consists only of control characters -Determines if the string consists only of defined characters (valid Unicode points) -Determines if the string consists only of digits -Determines if the string consists only of "graphic" characters -Determines if the specified characters should be regarded as an ignorable character in an identifier, according to Java -etermines if the specified characters are permissible in an identifier, according to Java -Determines if the specified character is permissible as the first character in an identifier according to Unicode -Determines whether the specified code points are ISO control codes -Determines if the string is lowercase -Determines whether the specified characters have the Bidi_Mirrored property -Determines if the string consists only of printable characters -Determines if the string consists only of punctuation characters -Determines if the string consists only of space characters -Determines whether the string consists only of titlecase characters -Determines if the string is uppercase -Determines if the string consists only of characters with Uppercase property -Determines if the the code point is valid character, according to Unicode -Determines if the string consists only of whitespace characters, according to Java/ICU -Determines if the string consists only of hexadecimal digits -Transliterate a string from the source script to the target script -Takes a binary string converts it to a Unicode string using the specifed encoding -Takes a Unicode string and converts it to a binary string using the specified encoding -Returns global conversion error mode for the specified conversion direction -Returns global substitution character for conversion from Unicode to codepage -Restores the active error handler to the one which was previously active (before the last unicode_set_error_handler() call) -Check whether unicode semantics are enabled -Set (or clear) the custom Unicode conversion error handler -Sets global conversion error mode for the specified conversion direction -Sets global substitution character for conversion from Unicode to codepage -TextIterator constructor -Returns the element at the current boundary -Positions iterator at the first character in the text and returns the offset -Advances to the text boundary following the specified offset and returns its offset -Return all text pieces determined by the text boundaries -Returns locales for which text boundary information is available -Return the status from the break rule that determined the most recent boundary -Return the statuses from the break rules that determined the most recent boundary -Determines whether specified offset is a text boundary -Returns the number boundaries iterated through -Positions iterator beyond the last character in the text and returns the offset -Advances to the n'th text boundary following the current one and returns its offset -Returns the offset of the current text boundary -Advances to the text boundary preceding the specified offset and returns its offset -Advances to the n'th text boundary preceding the current one and returns its offset -Determines validity of the iterator -Serializes given variables and adds them to packet given by packet_id -Ends specified WDDX packet and returns the string containing the packet -Starts a WDDX packet with optional comment and returns the packet id -Creates a new packet and serializes the given value -Creates a new packet and serializes given variables into a struct -Unserializes given packet and returns a PHP value -Converts a UTF-8 encoded string to ISO-8859-1 -Encodes an ISO-8859-1 string to UTF-8 -Get XML parser error string -Get current byte index for an XML parser -Get current column number for an XML parser -Get current line number for an XML parser -Get XML parser error code -Start parsing an XML document -Parsing a XML document -Create an XML parser -Create an XML parser -Free an XML parser -Get options from an XML parser -Set options in an XML parser -Set up character data handler -Set up default handler -Set up start and end element handlers -Set up character data handler -Set up external entity reference handler -Set up notation declaration handler -Set up object which should be used for callbacks -Set up processing instruction (PI) handler -Set up character data handler -Set up unparsed entity declaration handler -Sets the string that the the XMLReader will parse. -Closes xmlreader - current frees resources until xmlTextReaderClose is fixed in libxml -Moves the position of the current instance to the next node in the stream. -Get value of an attribute from current element -Get value of an attribute at index from current element -Get value of a attribute via name and namespace from current element -Indicates whether given property (one of the parser option constants) is set or not on parser -Returns boolean indicating if parsed document is valid or not. Must set XMLREADER_LOADDTD or XMLREADER_VALIDATE parser option prior to the first call to read or this method will always return FALSE -Return namespaceURI for associated prefix on current node -Positions reader at specified attribute - Returns TRUE on success and FALSE on failure -Positions reader at attribute at spcecified index. Returns TRUE on success and FALSE on failure -Positions reader at attribute spcified by name and namespaceURI. Returns TRUE on success and FALSE on failure -Moves the position of the current instance to the node that contains the current Attribute node. -Moves the position of the current instance to the first attribute associated with the current node. -Moves the position of the current instance to the next attribute associated with the current node. -Moves the position of the current instance to the next node in the stream. -Sets the URI that the the XMLReader will parse. -Moves the position of the current instance to the next node in the stream. -Reads the contents of the current node, including child nodes and markup. -Reads the contents of the current node, including child nodes and markup. -Reads the contents of an element or a text node as a string. -Sets parser property (one of the parser option constants). Properties must be set after open() or XML() and before the first read() is called -Sets the string that the the XMLReader will parse. -Sets the string that the the XMLReader will parse. -Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read(). -Decodes XML into native PHP types -Decodes XML into native PHP types -Generates XML for a PHP value -Generates XML for a method request -Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings -Determines if an array value represents an XMLRPC fault. -Decodes XML into a list of method descriptions -Adds introspection documentation -Parses XML requests and call methods -Creates an xmlrpc server -Destroys server resources -Register a PHP function to generate documentation -Register a PHP function to handle method matching method_name -Sets xmlrpc type, base64 or datetime, for a PHP string value -End attribute - returns FALSE on error -End current CDATA - returns FALSE on error -Create end comment - returns FALSE on error -End current document - returns FALSE on error -End current DTD - returns FALSE on error -End current DTD AttList - returns FALSE on error -End current DTD element - returns FALSE on error -End current DTD Entity - returns FALSE on error -End current element - returns FALSE on error -End current PI - returns FALSE on error -Output current buffer -End current element - returns FALSE on error -Create new xmlwriter using memory for string output -Create new xmlwriter using source uri for output -Output current buffer as string -Toggle indentation on/off - returns FALSE on error -Set string used for indenting - returns FALSE on error -Create start attribute - returns FALSE on error -Create start namespaced attribute - returns FALSE on error -Create start CDATA tag - returns FALSE on error -Create start comment - returns FALSE on error -Create document tag - returns FALSE on error -Create start DTD tag - returns FALSE on error -Create start DTD AttList - returns FALSE on error -Create start DTD element - returns FALSE on error -Create start DTD Entity - returns FALSE on error -Create start element tag - returns FALSE on error -Create start namespaced element tag - returns FALSE on error -Create start PI tag - returns FALSE on error -Write text - returns FALSE on error -Write full attribute - returns FALSE on error -Write full namespaced attribute - returns FALSE on error -Write full CDATA tag - returns FALSE on error -Write full comment tag - returns FALSE on error -Write full DTD tag - returns FALSE on error -Write full DTD AttList tag - returns FALSE on error -Write full DTD element tag - returns FALSE on error -Write full DTD Entity tag - returns FALSE on error -Write full element tag - returns FALSE on error -Write full namesapced element tag - returns FALSE on error -Write full PI tag - returns FALSE on error -Write text - returns FALSE on error - - -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since: - - - -URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since: - - -Add a file in a Zip archive using its path and the name to use. -Add a file using content and the entry name -close the zip archive -Returns the index of the entry named filename in the archive -Delete a file using its index -Delete a file using its index -Returns the comment of an entry using its index -Returns the comment of an entry using its index -Returns the comment of an entry using its name -get the contents of an entry using its index -get the contents of an entry using its name -Returns the name of the file at position index -get a stream for an entry using its name -Returns the index of the entry named filename in the archive -Create new zip using source uri for output, return TRUE on success or the error code -Rename an entry selected by its index to new_name -Rename an entry selected by its name to new_name -Set or remove (NULL/'') the comment of the archive -Set or remove (NULL/'') the comment of an entry using its index -Set or remove (NULL/'') the comment of an entry using its Name -Returns the zip entry informations using its index -Returns the information about a the zip entry filename -All changes to files and global information in archive are reverted -Revert all global changes to the archive archive. For now, this only reverts archive comment changes. -Changes to the file at position index are reverted -Changes to the file named 'name' are reverted -Close a Zip archive -Close a zip entry -Return the compressed size of a ZZip entry -Return a string containing the compression method used on a particular entry -Return the actual filesize of a ZZip entry -Return the name given a ZZip entry -Open a Zip File, pointed by the resource entry -Read from an open directory entry -Create new zip using source uri for output -Returns the next file in the archive -Encode data with the zlib encoding -Decode gzip encoded data -Encode data with the raw deflate encoding -Encode data with the gzip encoding -Read and uncompress entire .gz-file into an array -Decode raw deflate encoded data -Open a .gz-file and return a .gz-file pointer -Decode zlib encoded data -Output a .gz-file -Uncompress any raw/gzip/zlib encoded data -Compress data with the specified encoding -Returns the coding type used for output compression -Sets the maximum time a script can run -Clean (delete) the current output buffer -Clean the output buffer, and delete current output buffer -Flush (send) the output buffer, and delete current output buffer -Flush (send) contents of the output buffer. The last buffer content is sent to next buffer -Get current buffer contents and delete current output buffer -Return the contents of the output buffer -Get current buffer contents, flush (send) the output buffer, and delete current output buffer -Return the length of the output buffer -Return the nesting level of the output buffer -Turn implicit flush on/off and is equivalent to calling flush() after every output call -Turn on Output Buffering (specifying an optional output handler). -Add URL rewriter values -Reset(clear) URL rewriter values -Registers a custom URL protocol handler class -Restore the original protocol handler, overriding if necessary -Unregister a wrapper for the life of the current request. -Terminate apache process after this request -Get a list of loaded Apache modules -Fetch Apache version -Perform a partial request of the given URI to obtain information about it -Get and set Apache request notes -Fetch all HTTP request headers -Reset the Apache write timer -Fetch all HTTP response headers -Set an Apache subprocess_env variable -Alias for apache_request_headers() -Perform an Apache sub-request -Get a list of loaded Apache modules -Fetch Apache version -Get an Apache subprocess_env variable -Get and set Apache request notes -Fetch all HTTP response headers -Set an Apache subprocess_env variable -Fetch all HTTP request headers -Perform an apache sub-request -Get a list of loaded Apache modules -Fetch Apache version -Get an Apache subprocess_env variable -Get and set Apache request notes -Fetch all HTTP response headers -Set an Apache subprocess_env variable -Fetch all HTTP request headers -Perform an apache sub-request - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Terminate apache process after this request -Get a list of loaded Apache modules -Fetch Apache version -Perform a partial request of the given URI to obtain information about it -Get and set Apache request notes - - - -* fetch all headers that go out in case of an error or a subrequest -Fetch all HTTP request headers -* fetch all incoming request headers -* fetch all outgoing request headers - - - - -This is a wrapper for ap_sub_run_req and ap_destory_sub_req. It takes sub_request, runs it, destroys it, and returns it's status. - - - - - -Returns sub-request for the specified file. You would need to run it yourself with run(). -Returns sub-request for the specified uri. You would need to run it yourself with run() -Returns sub-request for the specified file. You would need to run it yourself with run(). - -Fetch all HTTP response headers -Set an Apache subprocess_env variable - -Perform an Apache sub-request -Adds a header to the current message. -Add a recipient to the message envelope. -Changes a header's value for the current message. -Removes the named recipient from the current message's envelope. -Returns the value of the given macro or NULL if the macro is not defined. -Replaces the body of the current message. If called more than once, subsequent calls result in data being appended to the new body. -Sets the flags describing the actions the filter may take. -Directly set the SMTP error reply code for this connection. This code will be used on subsequent error replies resulting from actions taken by this filter. -Sets the number of seconds libmilter will wait for an MTA connection before timing out a socket. -Get all headers from the request -Get all headers from the response -Perform an NSAPI sub-request -Dummy function which displays an error when a disabled function is called. -Checks if the class exists -Cause the process to crash by copying data to an inaccesible location -Creates an anonymous function, and returns its name (funny, eh?) -Return backtrace as array -Define a new constant -Check whether a constant exists -Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element -Return the current error_reporting level, and if an argument was passed - change to the new level -Returns true if the named extension is loaded -Get the $arg_num'th argument that was passed to the function -Get an array of the arguments that were passed to the function -Get the number of arguments that were passed to the function -Checks if the function exists -Retrieves the class name -Returns an array of method names for class or class instance. -Returns an array of default properties of the class. -Returns an array of all declared classes. -Returns an array of all declared interfaces. -Return an array containing the names and values of all defined constants -Returns an array of all defined functions -Returns an associative array of names and values of all currently defined variable names (variables in the current scope) -Returns an array with the names of functions belonging to the named extension -Returns an array with the file names that were included (includes require and once varieties) -Return an array containing names of loaded extensions -Returns an array of object properties -Retrieves the parent class name for object or class or current scope. -Get the resource type name for a given resource -Checks if the class exists -Returns true if the object is of this class or has this class as one of its parents -Returns true if the object has this class as one of its parents -Cause an intentional memory leak, for testing/debugging purposes -Checks if the class method exists -Checks if the object or class has a property -Restores the previously defined error handler function -Restores the previously defined exception handler function -Sets a user-defined error handler function. Returns the previously defined error handler, or false on error -Sets a user-defined exception handler function. Returns the previously defined exception handler, or false on error -Binary safe case-insensitive string comparison -Binary safe string comparison -Get string length -Binary safe string comparison -Binary safe string comparison -Generates a user-level error/warning/notice message -Generic test function -Returns a unique identifier for the current thread -Get the version of the Zend Engine -Get the exception severity -Clone the exception object -Obtain the string representation of the Exception object -Get the exception code -Get the file in which the exception occurred -Get the line in which the exception occurred -Get the exception message -Get the stack trace for the location in which the exception occurred -Obtain the backtrace for the exception as a string (instead of an array) -Exception constructor -ErrorException constructor -PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -3.14159265358979323846 -2.7182818284590452354 -1.4426950408889634074 -0.43429448190325182765 -0.69314718055994530942 -2.30258509299404568402 -1.57079632679489661923 -0.78539816339744830962 -0.31830988618379067154 -0.63661977236758134308 -1.77245385090551602729 -1.12837916709551257390 -1.41421356237309504880 -1.73205080756887729352 -0.70710678118654752440 -1.14472988584940017414 -0.57721566490153286061 -1 -2 -3 -4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 -4 -5 -6 -9 -255 -254 --1 - -1 -2 -3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur. -Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format. -When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify are used. The supplied certificates can still be used as untrusted CAs however. -Do not verify the signers certificate of a signed message. -Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs. -When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify for example). -Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included. -When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign . If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME. -Don't try and verify the signatures on a message - - - - - -Phar::SHA512 ( integer ) -Phar::PHPS ( integer ) - - - - - - - - - - - - - - - -ERR_NOERR -ERR_DUPLICATE -ERR_EOSCAN -ERR_EMPTY -ERR_CLOSE -ERR_WLOCKED -ERR_LOCKED -ERR_NOLOCK -ERR_READ -ERR_WRITE -ERR_CREATE -ERR_LSEEK -ERR_LENGTH -ERR_OPEN -ERR_WOPEN -ERR_MAGIC -ERR_VERSION -ERR_PGSIZE -ERR_CRC -ERR_PIPE -ERR_NIDX -ERR_MALLOC -ERR_NUSERS -ERR_PREEXIT -ERR_ONTRAP -ERR_PREPROC -ERR_DBPARSE -ERR_DBRUNERR -ERR_DBPREEXIT -ERR_WAIT -ERR_CORRUPT_TUPLE -ERR_WARNING0 -ERR_PANIC -ERR_FIFO -ERR_PERM -ERR_TCL -ERR_RESTRICTED -ERR_USER -ERR_UNKNOWN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -1 -2 -3 -4 -5 -7 -8 -9 -10 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Used to turn on-the-fly data compression on with Memcache::set , Memcache::add &listendand; Memcache::replace . -1 if this Memcache session handler is available, 0 otherwise. - - - - - - - - - - - - - - - - - - -Used with stream_filter_append and stream_filter_prepend to indicate that the specified filter should only be applied when reading -Used with stream_filter_append and stream_filter_prepend to indicate that the specified filter should only be applied when writing -This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE -Return Code indicating that the userspace filter returned buckets in $out . -Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available). -Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received). -Flag indicating if the stream used the include path. -Flag indicating if the wrapper is responsible for raising errors using trigger_error during opening of the stream. If this flag is not set, you should not raise any errors. -Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client . -Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client . -Client socket opened with stream_socket_client should remain persistent between page loads. -Tells a stream created with stream_socket_server to bind to the specified target. Server sockets should always include this flag. -Tells a stream created with stream_socket_server and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error. -A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened. -A connection with an external resource has been established. -Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR . -The mime-type of resource has been identified, refer to message for a description of the discovered type. -The size of the resource has been discovered. -The external resource has redirected the stream to an alternate location. Refer to message . -Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well. -There is no more data available on the stream. -A generic error occurred on the stream, consult message and message_code for details. -Authorization has been completed (with or without success). -Normal, non-error related, notification. -Non critical error condition. Processing may continue. -A critical error occurred. Processing cannot continue. -Provides a ICMP socket. -Provides a IP socket. -Provides a RAW socket. -Provides a TCP socket. -Provides a UDP socket. -Internet Protocol Version 4 (IPv4). -Internet Protocol Version 6 (IPv6). -Unix system internal protocols. -Provides datagrams, which are connectionless messages (UDP, for example). -Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user. -Provides a RDM (Reliably-delivered messages) socket. -Provides a sequenced packet stream socket. -Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example). -Used with stream_socket_shutdown to disable further receptions. Added in PHP 5.2.1. -Used with stream_socket_shutdown to disable further transmissions. Added in PHP 5.2.1. -Used with stream_socket_shutdown to disable further receptions and transmissions. Added in PHP 5.2.1. -Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -no color (black) -white -red - supported when terminal is in color mode -green - supported when terminal is in color mode -yellow - supported when terminal is in color mode -blue - supported when terminal is in color mode -cyan - supported when terminal is in color mode -magenta - supported when terminal is in color mode -down arrow -up arrow -left arrow -right arrow -home key (upward+left arrow) -backspace -delete line -insert line -delete character -insert char or enter insert mode -exit insert char mode -clear screen -clear to end of screen -clear to end of line -scroll one line forward -scroll one line backward -next page -previous page -set tab -clear tab -clear all tabs -soft (partial) reset -reset or hard reset -print -lower left -upper left of keypad -upper right of keypad -center of keypad -lower left of keypad -lower right of keypad -back tab -beginning -cancel -close -cmd (command) -copy -create -end -exit -find -help -mark -message -move -next -open -options -previous -redo -ref (reference) -refresh -replace -restart -resume -save -shiftet beg (beginning) -shifted cancel -shifted command -shifted copy -shifted create -shifted delete char -shifted delete line -select -shifted end -shifted end of line -shifted exit -shifted find -shifted help -shifted home -shifted input -shifted left arrow -shifted message -shifted move -shifted next -shifted options -shifted previous -shifted print -shifted redo -shifted replace -shifted right arrow -shifted resume -shifted save -shifted suspend -undo -mouse event has occurred -maximum key value -ctrl pressed during click -shift pressed during click -alt pressed during click -report all mouse events -report mouse position - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -1 -2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases. -Starts a read-only transaction. -Starts a read-write transaction. -Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions. -Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started. -Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION . This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction. -Indicated that a transaction should wait and retry when a conflict occurs. -Indicated that a transaction should fail immediately when a conflict occurs. -Also available as IBASE_TEXT for backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers. -Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available. -Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Unsigned 8-bit PCM. -Signed 8-bit PCM. -Unsigned 16-bit PCM. Little Endian byte order. -Unsigned 16-bit PCM. Big Endian byte order. -Signed 16-bit PCM. Little Endian byte order. -Signed 16-bit PCM. Big Endian byte order. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -if there is an error while sending data to the system logger, write directly to the system console -open the connection to the logger immediately -(default) delay opening the connection until the first message is logged - -print log message also to standard error -include PID with each message -security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined) -security/authorization messages (private) -clock daemon (cron and at) -other system daemons -kernel messages -line printer subsystem -mail subsystem -USENET news subsystem -messages generated internally by syslogd -generic user-level messages -UUCP subsystem -system is unusable -action must be taken immediately -critical conditions -error conditions -warning conditions -normal, but significant, condition -informational message -debug-level message -IPv4 Address Resource -Mail Exchanger Resource -Alias (Canonical Name) Resource -Authoritative Name Server Resource -Pointer Resource -Host Info Resource (See IANA's Operating System Names for the meaning of these values) -Start of Authority Resource -Text Resource -Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead. -IPv6 Address Resource -Iteratively query the name server for each available record type. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Use compression protocol -Allow space after function names -Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection. -Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5. -Columns are returned into the array having the fieldname as the array index. -Columns are returned into the array having both a numerical index and the fieldname as the array index. -Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -string -string -integer -integer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -KRB5_KDB_DISALLOW_FORWARDABLE -KRB5_KDB_DISALLOW_RENEWABLE -KRB5_KDB_DISALLOW_DUP_SKEY -KRB5_KDB_REQUIRES_PRE_AUTH -KRB5_KDB_REQUIRES_PWCHANGE -KRB5_KDB_PWCHANGE_SERVER -KRB5_KDB_NEW_PRINC -long -long -long -long -long -long -string -long -long -string -long -long -long -long -long -long - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -integer -integer -integer -integer -integer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Some value which can be obtained with fstat(1) changed for a file or directory. -A file or directory was deleted or renamed. -A file was created in a directory. -This event never occurs. -An event in response to fam_cancel_monitor . -An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. - - - - - - - - - - - - - - - - - - - - -1 -2 -4 -8 -16 -32 -64 -128 -256 -example: 1.0.2-dev - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -XMLReader::ENTITY_REF ( integer ) -Document Type node -Document Fragment node -Notation node -Whitespace node -Significant Whitespace node -End Element -End Entity -XML Declaration node -Character data with fixed length -Date, number of days since 1.1.0000 -Short integer (2 Bytes) -Long integer (4 Bytes) -same as PX_FIELD_NUMBER -Double -Boolean -Binary large object -Binary large object (not supported) -Binary large object -OLE object (basically a blob, not supported) -Graphic (basically a blob, not supported) -time, number of milli seconds since midnight -timestamp, number of milli seconds since 1.1.0000 -Auto incrementing interger (like PX_FIELD_LONG) -Decimal number stored in bcd format (not supported) -Array of Bytes with not more than 255 bytes (not supported) -Turn all field names into lower case -Turn all field names into upper case -Indexed database -Primary index -None indexed database -None incremental secondary index -Secondary index -Incremental secondary index -Non incremental secondary index -Secondary index -Non incremental secondary index - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -The component name used to initialise the SQLDBC runtime environment. -The application to be connected to the database. -The version of the application. -The SQL mode. -TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. -The maximum allowed time of inactivity after which the connection to the database is closed by the system. -Specifies whether and how shared locks and exclusive locks are implicitly requested or released. -The number of different request packets used for the connection. -The number of prepared statements to be cached for the connection for re-use. -The prefix to use for result tables that are automatically named. -Columns are returned into the array having the fieldname as the array index. -Columns are returned into the array having the upper case fieldname as the array index. -Columns are returned into the array having the lower case fieldname as the array index. -Columns are returned into the array having both a numerical index and the fieldname as the array index. -Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. - - - - - - - - - - -TIDY_TAG_A -TIDY_TAG_ACRONYM -TIDY_TAG_APPLET -TIDY_TAG_B -TIDY_TAG_BASEFONT -TIDY_TAG_BGSOUND -TIDY_TAG_BLINK -TIDY_TAG_BODY -TIDY_TAG_BUTTON -TIDY_TAG_CENTER -TIDY_TAG_CODE -TIDY_TAG_COLGROUP -TIDY_TAG_DD -TIDY_TAG_DFN -TIDY_TAG_DIV -TIDY_TAG_DT -TIDY_TAG_EMBED -TIDY_TAG_FONT -TIDY_TAG_FRAME -TIDY_TAG_H1 -TIDY_TAG_H3 -TIDY_TAG_H5 -TIDY_TAG_HEAD -TIDY_TAG_HTML -TIDY_TAG_IFRAME -TIDY_TAG_IMG -TIDY_TAG_INS -TIDY_TAG_KBD -TIDY_TAG_LABEL -TIDY_TAG_LEGEND -TIDY_TAG_LINK -TIDY_TAG_MAP -TIDY_TAG_MENU -TIDY_TAG_MULTICOL -TIDY_TAG_NOEMBED -TIDY_TAG_NOLAYER -TIDY_TAG_NOSCRIPT -TIDY_TAG_OL -TIDY_TAG_OPTION -TIDY_TAG_PARAM -TIDY_TAG_PRE -TIDY_TAG_RP -TIDY_TAG_RTC -TIDY_TAG_S -TIDY_TAG_SCRIPT -TIDY_TAG_SERVER -TIDY_TAG_SMALL -TIDY_TAG_SPAN -TIDY_TAG_STRONG -TIDY_TAG_SUB -TIDY_TAG_TBODY -TIDY_TAG_TEXTAREA -TIDY_TAG_TH -TIDY_TAG_TITLE -TIDY_TAG_TR -TIDY_TAG_U -TIDY_TAG_VAR -TIDY_TAG_XMP -TIDY_ATTR_ABBR -TIDY_ATTR_ACCEPT_CHARSET -TIDY_ATTR_ACTION -TIDY_ATTR_ALIGN -TIDY_ATTR_ALT -TIDY_ATTR_AXIS -TIDY_ATTR_BGCOLOR -TIDY_ATTR_BORDER -TIDY_ATTR_BOTTOMMARGIN -TIDY_ATTR_CELLSPACING -TIDY_ATTR_CHAROFF -TIDY_ATTR_CHECKED -TIDY_ATTR_CLASS -TIDY_ATTR_CLEAR -TIDY_ATTR_CODEBASE -TIDY_ATTR_COLOR -TIDY_ATTR_COLSPAN -TIDY_ATTR_CONTENT -TIDY_ATTR_DATA -TIDY_ATTR_DATAPAGESIZE -TIDY_ATTR_DATETIME -TIDY_ATTR_DEFER -TIDY_ATTR_DISABLED -TIDY_ATTR_ENCTYPE -TIDY_ATTR_FOR -TIDY_ATTR_FRAMEBORDER -TIDY_ATTR_GRIDX -TIDY_ATTR_HEADERS -TIDY_ATTR_HREF -TIDY_ATTR_HSPACE -TIDY_ATTR_ID -TIDY_ATTR_LABEL -TIDY_ATTR_LANGUAGE -TIDY_ATTR_LAST_VISIT -TIDY_ATTR_LINK -TIDY_ATTR_LOWSRC -TIDY_ATTR_MARGINWIDTH -TIDY_ATTR_MEDIA -TIDY_ATTR_MULTIPLE -TIDY_ATTR_NOHREF -TIDY_ATTR_NOSHADE -TIDY_ATTR_OBJECT -TIDY_ATTR_PROMPT -TIDY_ATTR_READONLY -TIDY_ATTR_REV -TIDY_ATTR_ROWS -TIDY_ATTR_RULES -TIDY_ATTR_SCOPE -TIDY_ATTR_SELECTED -TIDY_ATTR_SHOWGRID -TIDY_ATTR_SHOWGRIDY -TIDY_ATTR_SPAN -TIDY_ATTR_STANDBY -TIDY_ATTR_STYLE -TIDY_ATTR_TABINDEX -TIDY_ATTR_TEXT -TIDY_ATTR_TOPMARGIN -TIDY_ATTR_USEMAP -TIDY_ATTR_VALUE -TIDY_ATTR_VERSION -TIDY_ATTR_VSPACE -TIDY_ATTR_WRAP -TIDY_ATTR_XML_SPACE -constant -root node -doctype -HTML comment -Processing Instruction -Text -start tag -end tag -empty tag -CDATA -XML section -ASP code -JSTE code -PHP code -XML declaration -hotkey defined by newt_form_add_hot_key was pressed -some component has caused form to exit -file descriptor specified in newt_form_watch_fd is ready to be read or written to -time specified in newt_form_set_timer has elapsed - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Exit form, when component is activated -Component is hidden -Component is scrollable -Component is disabled - -Wrap text -Don't exit form on pressing F12 - -Component is selected -Component is checkbox -Entry component is password entry -Show cursor - - - - - - - - - - - - - - -Wrap text in the textbox -Scroll text in the textbox -Don't exit form on F12 press - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all . -Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all . -See the description of PREG_SPLIT_OFFSET_CAPTURE . This flag is available since PHP 4.3.0. -This flag tells preg_split to return only non-empty pieces. -This flag tells preg_split to capture parenthesized expression in the delimiter pattern as well. This flag is available since PHP 4.0.5. -If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is available since PHP 4.3.0 and is only used for preg_split . -Returned by preg_last_error if there were no errors. Available since PHP 5.2.0. -Returned by preg_last_error if there was an internal PCRE error. Available since PHP 5.2.0. -Returned by preg_last_error if <link linkend="ini.pcre.backtrack-limit">backtrack limit was exhausted. Available since PHP 5.2.0. -Returned by preg_last_error if <link linkend="ini.pcre.recursion-limit">recursion limit was exhausted. Available since PHP 5.2.0. -Returned by preg_last_error if the last error was caused by malformed UTF-8 data (only when running a regex in <link linkend="reference.pcre.pattern.modifiers">UTF-8 mode ). Available since PHP 5.2.0. -Returned by preg_last_error if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode ). Available since PHP 5.3.0. -PCRE version and release date (e.g. "7.0 18-Dec-2006"). Available since PHP 5.2.4. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -1 -2 -4 -8 -16 -32 -64 --1 -1 -2 -4 -8 -16 -32 -64 --1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java deleted file mode 100644 index 972a207..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java +++ /dev/null @@ -1,86 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor.util; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; - -/** - * Manager for colors used in the Java editor - */ -public class PHPColorProvider { - - public static final RGB MULTI_LINE_COMMENT = new RGB(63, 127, 95); - - public static final RGB SINGLE_LINE_COMMENT = new RGB(63, 127, 95); - - public static final RGB TAG = new RGB(255, 0, 128); - - public static final RGB KEYWORD = new RGB(127, 0, 85); - - public static final RGB VARIABLE = new RGB(127, 159, 191); - - public static final /*RGB*/String FUNCTION_NAME = "127, 127, 159"; //new RGB(127, 127, 159); - - public static final RGB STRING_DQ = new RGB(42, 0, 255); - - public static final RGB STRING_SQ = new RGB(42, 0, 255); - - public static final RGB DEFAULT = new RGB(0, 0, 0); - - public static final RGB TYPE = new RGB(127, 0, 85); - - public static final RGB CONSTANT = new RGB(127, 0, 85); - - public static final RGB BACKGROUND = new RGB(255, 255, 255); - - // public static final RGB LINKED_POSITION_COLOR = new RGB(0, 0, 0); - - // public static final RGB LINE_NUMBER_COLOR = new RGB(0, 0, 0); - // public static final RGB BACKGROUND_COLOR = new RGB(255, 255, 255); - - public static final RGB PHPDOC_TAG = new RGB(63, 127, 95); - - public static final RGB PHPDOC_LINK = new RGB(63, 63, 191); - - public static final RGB PHPDOC_DEFAULT = new RGB(63, 95, 191); - - public static final RGB PHPDOC_KEYWORD = new RGB(127, 159, 191); - - protected Map fColorTable = new HashMap(10); - - /** - * Release all of the color resources held onto by the receiver. - */ - public void dispose() { - Iterator e = fColorTable.values().iterator(); - while (e.hasNext()) - ((Color) e.next()).dispose(); - } - - /** - * Return the Color that is stored in the Color table as rgb. - */ - public Color getColor(RGB rgb) { - Color color = (Color) fColorTable.get(rgb); - if (color == null) { - color = new Color(Display.getCurrent(), rgb); - fColorTable.put(rgb, color); - } - return color; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java deleted file mode 100644 index 9922f48..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java +++ /dev/null @@ -1,165 +0,0 @@ -package net.sourceforge.phpeclipse.preferences; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import net.sourceforge.phpdt.internal.core.JavaProject; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.ide.IDE.SharedImages; - -public class PHPProjectLibraryPage { - protected JavaProject workingProject; - - protected PHPProjectLibraryPage(JavaProject theWorkingProject) { - super(); - workingProject = theWorkingProject; - } - - protected Control getControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(new FillLayout()); - - Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER - | SWT.MULTI | SWT.FULL_SELECTION); - projectsTable.setHeaderVisible(false); - projectsTable.setLinesVisible(false); - projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); - - TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); - tableColumn.setWidth(200); - tableColumn.setText(PHPPreferencesMessages - .getString("PHPEditorPreferencePageLibraryPage.project")); //$NON-NLS-1$ - - CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer( - projectsTable); - projectsTableViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - projectCheckedUnchecked(event); - } - }); - - projectsTableViewer.setContentProvider(getContentProvider()); - projectsTableViewer.setLabelProvider(getLabelProvider()); - - projectsTableViewer.setInput(getWorkspaceProjects()); - projectsTableViewer.setCheckedElements(workingProject - .getReferencedProjects().toArray()); - - return composite; - } - - protected void projectCheckedUnchecked(CheckStateChangedEvent event) { - IProject checkEventProject = (IProject) event.getElement(); - if (event.getChecked()) - getWorkingProject().addLoadPathEntry(checkEventProject); - else - getWorkingProject().removeLoadPathEntry(checkEventProject); - } - - protected JavaProject getWorkingProject() { - return workingProject; - } - - protected List getWorkspaceProjects() { - IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); - return Arrays.asList(root.getProjects()); - } - - protected ITableLabelProvider getLabelProvider() { - ITableLabelProvider labelProvider = new ITableLabelProvider() { - public Image getColumnImage(Object element, int columnIndex) { - IWorkbench workbench = WebUI.getDefault() - .getWorkbench(); - return workbench.getSharedImages().getImage( - SharedImages.IMG_OBJ_PROJECT); - } - - public String getColumnText(Object element, int columnIndex) { - if (element instanceof IProject) - return ((IProject) element).getName(); - - return PHPPreferencesMessages - .getString("PHPEditorPreferencePageLibraryPage.elementNotIProject"); //$NON-NLS-1$ - } - - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - } - }; - - return labelProvider; - } - - protected IContentProvider getContentProvider() { - IStructuredContentProvider contentProvider = new IStructuredContentProvider() { - protected List PHPEditorPreferencePages; - - public Object[] getElements(Object inputElement) { - return PHPEditorPreferencePages.toArray(); - } - - public void dispose() { - } - - public void inputChanged(Viewer viewer, Object oldInput, - Object newInput) { - PHPEditorPreferencePages = new ArrayList(); - - if (!(newInput instanceof List)) - return; - - Iterator workspaceProjectsIterator = ((List) newInput) - .iterator(); - while (workspaceProjectsIterator.hasNext()) { - Object anObject = workspaceProjectsIterator.next(); - if (anObject instanceof IProject) { - IProject project = (IProject) anObject; - if (project.getName() != workingProject.getProject() - .getName()) { - try { - if (project - .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) - PHPEditorPreferencePages.add(project); - } catch (CoreException e) { - } - } - } - } - } - }; - - return contentProvider; - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ExternalStorageDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ExternalStorageDocumentProvider.java deleted file mode 100644 index 56c01ad..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/ExternalStorageDocumentProvider.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.sourceforge.phpeclipse.ui; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.ExternalEditorInput; -import net.sourceforge.phpeclipse.builder.FileStorage; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.text.IDocument; -import org.eclipse.ui.editors.text.StorageDocumentProvider; - -/** - * @author ed - * @version 1.0, May 19, 2003 - */ -public class ExternalStorageDocumentProvider extends StorageDocumentProvider { - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, - * java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ - protected void doSaveDocument(IProgressMonitor monitor, Object element, - IDocument document, boolean overwrite) throws CoreException { - if (element instanceof ExternalEditorInput) { - ExternalEditorInput external = (ExternalEditorInput) element; - FileStorage storage = (FileStorage) external.getStorage(); - String encoding = getEncoding(element); - if (encoding == null) - encoding = getDefaultEncoding(); - try { - InputStream stream = new ByteArrayInputStream(document.get() - .getBytes(encoding)); - try { - // inform about the upcoming content change - fireElementStateChanging(element); - storage.setContents(stream, overwrite, true, monitor); - } catch (RuntimeException e) { - // inform about failure - fireElementStateChangeFailed(element); - throw e; - } - } catch (IOException e) { - IStatus s = new Status(IStatus.ERROR, - PHPeclipsePlugin.PLUGIN_ID, IStatus.OK, e.getMessage(), - e); - throw new CoreException(s); - } - - } else { - super.doSaveDocument(monitor, element, document, overwrite); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java index fb23514..816f5e9 100644 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java +++ b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/ui/WebUI.java @@ -13,114 +13,29 @@ package net.sourceforge.phpeclipse.ui; -import org.eclipse.jface.resource.JFaceResources; -import java.io.File; import java.io.IOException; -//import java.io.InputStream; import java.net.URL; -//import java.util.Enumeration; -import java.util.HashMap; -//import java.util.PropertyResourceBundle; - -//import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.core.IBuffer; -import net.sourceforge.phpdt.core.ICompilationUnit; -import net.sourceforge.phpdt.core.IJavaElement; -import net.sourceforge.phpdt.core.WorkingCopyOwner; -import net.sourceforge.phpdt.internal.core.JavaModelManager; -import net.sourceforge.phpdt.internal.core.util.Util; -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; -import net.sourceforge.phpdt.internal.corext.template.php.HTMLContextType; -import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; -import net.sourceforge.phpdt.internal.corext.template.php.JavaDocContextType; -import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants; -import net.sourceforge.phpdt.internal.ui.JavaElementAdapterFactory; -import net.sourceforge.phpdt.internal.ui.ResourceAdapterFactory; -import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; -import net.sourceforge.phpdt.internal.ui.preferences.MockupPreferenceStore; -import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter; -import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry; -import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; -import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; -import net.sourceforge.phpdt.internal.ui.viewsupport.ProblemMarkerManager; -import net.sourceforge.phpdt.ui.IContextMenuConstants; -import net.sourceforge.phpdt.ui.IWorkingCopyManager; -import net.sourceforge.phpdt.ui.text.JavaTextTools; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.builder.ExternalEditorInput; -import net.sourceforge.phpeclipse.builder.ExternalStorageDocumentProvider; -import net.sourceforge.phpeclipse.builder.FileStorage; -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; -import net.sourceforge.phpeclipse.DocumentAdapter; -import net.sourceforge.phpeclipse.phpeditor.ICompilationUnitDocumentProvider; -import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider; -//import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; -import net.sourceforge.phpeclipse.phpeditor.WorkingCopyManager; -//import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; - import net.sourceforge.phpeclipse.ui.templates.template.HTMLTemplateContextType; -//import net.sourceforge.phpdt.internal.corext.template.php.HTMLContextType; - import net.sourceforge.phpeclipse.ui.templates.template.JSTemplateContextType; import net.sourceforge.phpeclipse.ui.templates.template.SmartyTemplateContextType; import net.sourceforge.phpeclipse.ui.templates.template.XMLTemplateContextType; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.ISavedState; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.resources.WorkspaceJob; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdapterManager; -import org.eclipse.core.runtime.IConfigurationElement; -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.Platform; -//import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; -import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -//import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; -//import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.ContextTypeRegistry; import org.eclipse.jface.text.templates.persistence.TemplateStore; -//import org.eclipse.swt.graphics.RGB; 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.IEditorRegistry; -import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry; import org.eclipse.ui.editors.text.templates.ContributionTemplateStore; -import org.eclipse.ui.ide.IDE; import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.ui.texteditor.ConfigurationElementSorter; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; -import org.osgi.framework.BundleContext; /** * The web development tools UI plugin. @@ -129,41 +44,7 @@ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.ui"; - public static final String EDITOR_ID = WebUI.PLUGIN_ID + ".PHPUnitEditor"; - - - /** - * The key to store customized templates. - * - * @since 3.0 - */ - private static final String TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_templates"; //$NON-NLS-1$ - - /** - * The key to store customized code templates. - * - * @since 3.0 - */ - private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ - - - - - - private static final String CUSTOM_TEMPLATES_KEY = "net.sourceforge.phpeclipse.ui.templates"; //$NON-NLS-1$ - - /** - * The key to store customized code templates. - * - * @since 3.0 - */ -// private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ - /** - * The maximum number of allowed proposals by category - */ - public final static int MAX_PROPOSALS = 200; - - public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature"; + private static final String CUSTOM_TEMPLATES_KEY = "net.sourceforge.phpeclipse.ui.templates"; //$NON-NLS-1$ // Constants --------------------------------------------------------------- @@ -175,67 +56,6 @@ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { /** The shared instance. */ private static WebUI plugin; - - /** - * The combined preference store. - * - * @since 3.0 - */ - private IPreferenceStore fCombinedPreferenceStore; - - /** - * The coded template store for the java editor. - * - * @since 3.0 - */ - private TemplateStore fCodeTemplateStore; - - /** - * The code template context type registry for the java editor. - * - * @since 3.0 - */ - private ContextTypeRegistry fCodeTemplateContextTypeRegistry; - - /** - * The template context type registry for the java editor. - * - * @since 3.0 - */ - private ContextTypeRegistry fContextTypeRegistry; - - private ResourceAdapterFactory fResourceAdapterFactory; - - private JavaElementAdapterFactory fJavaElementAdapterFactory; - - private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider; - - private JavaTextTools fJavaTextTools; - - private IWorkingCopyManager fWorkingCopyManager; - - private IPropertyChangeListener fFontPropertyChangeListener; - - private ProblemMarkerManager fProblemMarkerManager; - - private MockupPreferenceStore fMockupPreferenceStore; - - private ImageDescriptorRegistry fImageDescriptorRegistry; - - private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors; - - private MembersOrderPreferenceCache fMembersOrderPreferenceCache; - - private HashMap fIndexManagerMap = new HashMap(); - - /** - * The extension point registry for the - * net.sourceforge.phpdt.ui.javaFoldingStructureProvider - * extension point. - * - * @since 3.0 - */ - private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry; public static IWorkbenchPage getActivePage() { return getDefault().internalGetActivePage(); @@ -328,8 +148,8 @@ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { */ public TemplateStore getTemplateStore() { if (fStore == null) { - fStore = new ContributionTemplateStore(/*getContextTypeRegistry()*/getTemplateContextRegistry(), - getDefault().getPreferenceStore(), /*CUSTOM_*/TEMPLATES_KEY); + fStore = new ContributionTemplateStore(getContextTypeRegistry(), + getDefault().getPreferenceStore(), CUSTOM_TEMPLATES_KEY); try { fStore.load(); } catch (IOException e) { @@ -345,6 +165,19 @@ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { return fStore; } + protected void initializeDefaultPreferences(IPreferenceStore store) { + store.setDefault(PHP_LOCALHOST_PREF, "http://localhost"); + store.setDefault(PHP_DOCUMENTROOT_PREF, getWorkspace().getRoot() + .getFullPath().toString()); + // store.setDefault(PHP_BOOKMARK_DEFAULT, ""); + + store.setDefault(PHP_AUTO_PREVIEW_DEFAULT, "false"); + store.setDefault(PHP_BRING_TO_TOP_PREVIEW_DEFAULT, "false"); + store.setDefault(PHP_STICKY_BROWSER_URL_DEFAULT, "false"); + // store.setDefault(PHP_SHOW_HTML_FILES_LOCAL, "true"); + // store.setDefault(PHP_SHOW_XML_FILES_LOCAL, "false"); + } + /* * @see AbstractUIPlugin#initializeImageRegistry(ImageRegistry) */ @@ -368,543 +201,4 @@ public class WebUI extends AbstractUIPlugin implements IPreferenceConstants { log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "" + e.getLocalizedMessage(), e)); } - - public static String getPluginId() { - return getDefault().getBundle().getSymbolicName(); - } - - /** - * Returns a combined preference store, this store is read-only. - * - * @return the combined preference store - * - * @since 3.0 - */ - public IPreferenceStore getCombinedPreferenceStore() { - if (fCombinedPreferenceStore == null) { - IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); - fCombinedPreferenceStore = new ChainedPreferenceStore( - new IPreferenceStore[] { - getPreferenceStore(), - new PreferencesAdapter(WebUI - .getDefault().getPluginPreferences()), - generalTextStore }); - } - return fCombinedPreferenceStore; - } - - // TODO: refactor this into a better method name ! - public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { - if (fCompilationUnitDocumentProvider == null) - fCompilationUnitDocumentProvider = new PHPDocumentProvider(); - return fCompilationUnitDocumentProvider; - } - - public synchronized JavaTextTools getJavaTextTools() { - if (fJavaTextTools == null) - fJavaTextTools = new JavaTextTools(getPreferenceStore(), /*JavaCore - .getPlugin().*/getPluginPreferences()); - return fJavaTextTools; - } - - public synchronized IWorkingCopyManager getWorkingCopyManager() { - if (fWorkingCopyManager == null) { - ICompilationUnitDocumentProvider provider = getCompilationUnitDocumentProvider(); - fWorkingCopyManager = new WorkingCopyManager(provider); - } - return fWorkingCopyManager; - } - - public synchronized ProblemMarkerManager getProblemMarkerManager() { - if (fProblemMarkerManager == null) - fProblemMarkerManager = new ProblemMarkerManager(); - return fProblemMarkerManager; - } - - /** - * Returns the mockup preference store for firing events and registering - * listeners on project setting changes. Temporary solution. - */ - public MockupPreferenceStore getMockupPreferenceStore() { - if (fMockupPreferenceStore == null) - fMockupPreferenceStore = new MockupPreferenceStore(); - - return fMockupPreferenceStore; - } - - public static ImageDescriptorRegistry getImageDescriptorRegistry() { - return getDefault().internalGetImageDescriptorRegistry(); - } - - private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { - if (fImageDescriptorRegistry == null) - fImageDescriptorRegistry = new ImageDescriptorRegistry(); - return fImageDescriptorRegistry; - } - - /** - * Returns the registry of the extensions to the - * net.sourceforge.phpdt.ui.javaFoldingStructureProvider - * extension point. - * - * @return the registry of contributed - * IJavaFoldingStructureProvider - * @since 3.0 - */ - public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() { - if (fFoldingStructureProviderRegistry == null) - fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry(); - return fFoldingStructureProviderRegistry; - } - /** - * Returns all Java editor text hovers contributed to the workbench. - * - * @return an array of JavaEditorTextHoverDescriptor - * @since 2.1 - */ - public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() { - if (fJavaEditorTextHoverDescriptors == null) { - fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor - .getContributedHovers(); - ConfigurationElementSorter sorter = new ConfigurationElementSorter() { - /* - * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) - */ - public IConfigurationElement getConfigurationElement( - Object object) { - return ((JavaEditorTextHoverDescriptor) object) - .getConfigurationElement(); - } - }; - sorter.sort(fJavaEditorTextHoverDescriptors); - - // The Problem hover has to be the first and the Annotation hover - // has to - // be the last one in the JDT UI's hover list - int length = fJavaEditorTextHoverDescriptors.length; - int first = -1; - int last = length - 1; - int problemHoverIndex = -1; - int annotationHoverIndex = -1; - for (int i = 0; i < length; i++) { - if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith( - PLUGIN_ID)) { - if (problemHoverIndex == -1 || annotationHoverIndex == -1) - continue; - else { - last = i - 1; - break; - } - } - if (first == -1) - first = i; - - if (fJavaEditorTextHoverDescriptors[i].getId().equals( - "net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$ - annotationHoverIndex = i; - continue; - } - if (fJavaEditorTextHoverDescriptors[i].getId().equals( - "net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$ - problemHoverIndex = i; - continue; - } - } - - JavaEditorTextHoverDescriptor hoverDescriptor = null; - - if (first > -1 && problemHoverIndex > -1 - && problemHoverIndex != first) { - // move problem hover to beginning - hoverDescriptor = fJavaEditorTextHoverDescriptors[first]; - fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex]; - fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor; - - // update annotation hover index if needed - if (annotationHoverIndex == first) - annotationHoverIndex = problemHoverIndex; - } - - if (annotationHoverIndex > -1 && annotationHoverIndex != last) { - // move annotation hover to end - hoverDescriptor = fJavaEditorTextHoverDescriptors[last]; - fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex]; - fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor; - } - - // Move Best Match hover to front - for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) { - if (PreferenceConstants.ID_BESTMATCH_HOVER - .equals(fJavaEditorTextHoverDescriptors[i].getId())) { - hoverDescriptor = fJavaEditorTextHoverDescriptors[i]; - for (int j = i; j > 0; j--) - fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1]; - fJavaEditorTextHoverDescriptors[0] = hoverDescriptor; - break; - } - - } - } - - return fJavaEditorTextHoverDescriptors; - } - - public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() { - if (fMembersOrderPreferenceCache == null) - fMembersOrderPreferenceCache = new MembersOrderPreferenceCache(); - return fMembersOrderPreferenceCache; - } - /** - * Open a file in the Workbench that may or may not exist in the workspace. - * Must be run on the UI thread. - * - * @param filename - * @throws CoreException - */ - public ITextEditor openFileInTextEditor(String filename) - throws CoreException { - // reject directories - if (new File(filename).isDirectory()) - return null; - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; - IWorkbenchPage page = window.getActivePage(); - IPath path = new Path(filename); - // If the file exists in the workspace, open it - IFile file = getWorkspace().getRoot().getFile(path); - IEditorPart editor; - ITextEditor textEditor; - if (file != null && file.exists()) { - editor = IDE.openEditor(page, file, true); - textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - } else { - // Otherwise open the stream directly - if (page == null) - return null; - FileStorage storage = new FileStorage(path); - IEditorRegistry registry = getWorkbench().getEditorRegistry(); - IEditorDescriptor desc = registry.getDefaultEditor(filename); - if (desc == null) { - desc = registry - .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); - // desc = registry.getDefaultEditor(); - } - IEditorInput input = new ExternalEditorInput(storage); - editor = page.openEditor(input, desc.getId()); - textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - // If the storage provider is not ours, we can't guarantee - // read/write. - if (textEditor != null) { - IDocumentProvider documentProvider = textEditor - .getDocumentProvider(); - if (!(documentProvider instanceof ExternalStorageDocumentProvider)) { - storage.setReadOnly(); - } - } - } - return textEditor; - } - /** - * Creates the PHP plugin standard groups in a context menu. - */ - public static void createStandardGroups(IMenuManager menu) { - if (!menu.isEmpty()) - return; - menu.add(new Separator(IContextMenuConstants.GROUP_NEW)); - menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO)); - menu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); - menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW)); - menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); - menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); - menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); - menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); - menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); - menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP)); - menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES)); - } - - public IdentifierIndexManager getIndexManager(IProject iProject) { - IPath path = iProject.getWorkingLocation(/*WebUI*/PHPeclipsePlugin.PLUGIN_ID); - path = path.append("project.index"); - String indexFilename = path.toString(); - // try { - // IdentDB db = IdentDB.getInstance(); - // } catch (ClassNotFoundException e) { - // e.printStackTrace(); - // } catch (SQLException e) { - // e.printStackTrace(); - // } - IdentifierIndexManager indexManager = (IdentifierIndexManager) fIndexManagerMap - .get(indexFilename); - if (indexManager == null) { - indexManager = new IdentifierIndexManager(indexFilename); - fIndexManagerMap.put(indexFilename, indexManager); - } - return indexManager; - } - - /** - * Returns the template store for the code generation templates. - * - * @return the template store for the code generation templates - * @since 3.0 - */ - public TemplateStore getCodeTemplateStore() { - if (fCodeTemplateStore == null) { - fCodeTemplateStore = new ContributionTemplateStore( - getCodeTemplateContextRegistry(), getPreferenceStore(), - CODE_TEMPLATES_KEY); - try { - fCodeTemplateStore.load(); - } catch (IOException e) { - log(e); - } - } - - return fCodeTemplateStore; - } - /** - * Returns the template context type registry for the code generation - * templates. - * - * @return the template context type registry for the code generation - * templates - * @since 3.0 - */ - public ContextTypeRegistry getCodeTemplateContextRegistry() { - if (fCodeTemplateContextTypeRegistry == null) { - fCodeTemplateContextTypeRegistry = new ContributionContextTypeRegistry(); - - CodeTemplateContextType - .registerContextTypes(fCodeTemplateContextTypeRegistry); - } - - return fCodeTemplateContextTypeRegistry; - } - - public void openFileAndGotoOffset(String filename, int offset, int length) - throws CoreException { - ITextEditor textEditor = openFileInTextEditor(filename); - if (textEditor != null) { - // If a line number was given, go to it - if (offset >= 0) { -// IDocument document = textEditor.getDocumentProvider() -// .getDocument(textEditor.getEditorInput()); - textEditor.selectAndReveal(offset, length); - } - } - } - - public void openFileAndFindString(String filename, String findString) - throws CoreException { - ITextEditor textEditor = openFileInTextEditor(filename); - if (textEditor != null) { - // If a string was given, go to it - if (findString != null) { - try { - IDocument document = textEditor.getDocumentProvider() - .getDocument(textEditor.getEditorInput()); - int offset = document.search(0, findString, true, false, - true); - textEditor.selectAndReveal(offset, findString.length()); - } catch (BadLocationException e) { - // invalid text position -> do nothing - } - } - } - } - - public static void logErrorMessage(String message) { - log(new Status(IStatus.ERROR, getPluginId(),IJavaStatusConstants.INTERNAL_ERROR, message, null)); - } - public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, - null); - log(status); - } - - public static void log(String message, Throwable t) { - log(error(message, t)); - } - public static IStatus error(Throwable t) { - return error("PHPeclipsePlugin.internalErrorOccurred", t); //$NON-NLS-1$ - } - - public static IStatus error(String message, Throwable t) { - return new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, message, t); - } - - /** - * Resets the Java editor text hovers contributed to the workbench. - *

- * This will force a rebuild of the descriptors the next time a client asks - * for them. - *

- * - * @return an array of JavaEditorTextHoverDescriptor - * @since 2.1 - */ - public void resetJavaEditorTextHoverDescriptors() { - fJavaEditorTextHoverDescriptors = null; - } - - /** - * Returns the template context type registry for the java plugin. - * - * @return the template context type registry for the java plugin - * @since 3.0 - */ - public ContextTypeRegistry getTemplateContextRegistry() { - if (fContextTypeRegistry == null) { - fContextTypeRegistry = new ContributionContextTypeRegistry(); - - fContextTypeRegistry.addContextType(new JavaContextType()); - fContextTypeRegistry.addContextType(new JavaDocContextType()); - fContextTypeRegistry.addContextType(new HTMLContextType()); - } - - return fContextTypeRegistry; - } - // public static void logErrorMessage(String message) { - // log(new Status(IStatus.ERROR, getPluginId(), - // JavaStatusConstants.INTERNAL_ERROR, message, null)); - // } - - - - /* - * (non - Javadoc) Method declared in Plugin - */ - public void start(BundleContext context) throws Exception { - super.start(context); - - // JavaCore.start(this, context); - final JavaModelManager modelManager = JavaModelManager - .getJavaModelManager(); - try { - modelManager.configurePluginDebugOptions(); - - // request state folder creation (workaround 19885) - getStateLocation(); - // retrieve variable values - PHPeclipsePlugin.getDefault().getPluginPreferences() - .addPropertyChangeListener( - new JavaModelManager.PluginPreferencesListener()); - // manager.loadVariablesAndContainers(); - - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - workspace.addResourceChangeListener(modelManager.deltaState, - IResourceChangeEvent.PRE_BUILD - | IResourceChangeEvent.POST_BUILD - | IResourceChangeEvent.POST_CHANGE - | IResourceChangeEvent.PRE_DELETE - | IResourceChangeEvent.PRE_CLOSE); - -// ISavedState savedState = workspace.addSaveParticipant( -// /*PHPeclipsePlugin*/WebUI.this, modelManager); - - WorkspaceJob processSavedState = new WorkspaceJob( - Util.bind("savedState.jobName")) { //$NON-NLS-1$ - public IStatus runInWorkspace(IProgressMonitor monitor) - throws CoreException { - ISavedState savedState = workspace.addSaveParticipant( - /*PHPeclipsePlugin*/WebUI.this, modelManager); - if (savedState != null) { - modelManager.deltaState.getDeltaProcessor().overridenEventType - = IResourceChangeEvent.POST_CHANGE; - savedState.processResourceChangeEvents(modelManager.deltaState); - } - return Status.OK_STATUS; - } - }; - processSavedState.setSystem(true); - processSavedState.setPriority(Job.SHORT); // process asap - processSavedState.schedule(); - } catch (RuntimeException e) { - modelManager.shutdown(); - throw e; - } - - registerAdapters(); - - // if (USE_WORKING_COPY_OWNERS) { - WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { - public IBuffer createBuffer(ICompilationUnit workingCopy) { - ICompilationUnit original = workingCopy.getPrimary(); - IResource resource = original.getResource(); - if (resource instanceof IFile) - return new DocumentAdapter(workingCopy, (IFile) resource); - return DocumentAdapter.NULL; - } - }); - // } - - installPreferenceStoreBackwardsCompatibility(); - - } - - - private void registerAdapters() { - fJavaElementAdapterFactory = new JavaElementAdapterFactory(); - fResourceAdapterFactory = new ResourceAdapterFactory(); - - IAdapterManager manager = Platform.getAdapterManager(); - manager - .registerAdapters(fJavaElementAdapterFactory, - IJavaElement.class); - manager.registerAdapters(fResourceAdapterFactory, IResource.class); - } - - - - /** - * Installs backwards compatibility for the preference store. - */ - private void installPreferenceStoreBackwardsCompatibility() { - - /* - * Installs backwards compatibility: propagate the Java editor font from - * a pre-2.1 plug-in to the Platform UI's preference store to preserve - * the Java editor font from a pre-2.1 workspace. This is done only - * once. - */ - String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$ - if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) - && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) { - if (!getPreferenceStore().getBoolean(fontPropagatedKey)) - PreferenceConverter - .setValue(PlatformUI.getWorkbench() - .getPreferenceStore(), - PreferenceConstants.EDITOR_TEXT_FONT, - PreferenceConverter.getFontDataArray( - getPreferenceStore(), - JFaceResources.TEXT_FONT)); - } - getPreferenceStore().setValue(fontPropagatedKey, true); - - /* - * Backwards compatibility: set the Java editor font in this plug-in's - * preference store to let older versions access it. Since 2.1 the Java - * editor font is managed by the workbench font preference page. - */ - PreferenceConverter.putValue(getPreferenceStore(), - JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry() - .getFontData(PreferenceConstants.EDITOR_TEXT_FONT)); - - fFontPropertyChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event - .getProperty())) - PreferenceConverter.putValue(getPreferenceStore(), - JFaceResources.TEXT_FONT, - JFaceResources.getFontRegistry().getFontData( - PreferenceConstants.EDITOR_TEXT_FONT)); - } - }; - // incastrix - /*JFaceResources.getFontRegistry().addListener( - fFontPropertyChangeListener);*/ - } - - } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java deleted file mode 100644 index 4e2f2b6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java +++ /dev/null @@ -1,194 +0,0 @@ -package net.sourceforge.phpeclipse.wizards; - -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -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.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -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.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWizard; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; - -/** - * This wizard creates one file with the extension "html". - */ -public class HTMLFileWizard extends Wizard implements INewWizard { - - private HTMLFileWizardPage page; - - private ISelection selection; - - public HTMLFileWizard() { - super(); - setNeedsProgressMonitor(true); - setWindowTitle(PHPWizardMessages - .getString("WizardNewProjectCreationPage.html.windowTitle")); - } - - /** - * Adding the page to the wizard. - */ - public void addPages() { - page = new HTMLFileWizardPage(selection); - addPage(page); - } - - /** - * This method is called when 'Finish' button is pressed in the wizard. We - * will create an operation and run it using wizard as execution context. - */ - public boolean performFinish() { - final String containerName = page.getContainerName(); - final String fileName = page.getFileName(); - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) - throws InvocationTargetException { - try { - doFinish(containerName, fileName, monitor); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - try { - getContainer().run(true, false, op); - } catch (InterruptedException e) { - return false; - } catch (InvocationTargetException e) { - Throwable realException = e.getTargetException(); - MessageDialog.openError(getShell(), PHPWizardMessages - .getString("Wizard.error"), realException.getMessage()); - return false; - } - return true; - } - - /** - * The worker method. It will find the container, create the file if missing - * or just replace its contents, and open the editor on the newly created - * file. - */ - private void doFinish(String containerName, String fileName, - IProgressMonitor monitor) throws CoreException { - // create a sample file - monitor.beginTask(PHPWizardMessages - .getString("Wizard.Monitor.creating") - + " " + fileName, 2); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(containerName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - throwCoreException(PHPWizardMessages - .getString("Wizard.Monitor.containerDoesNotExistException")); - } - IContainer container = (IContainer) resource; - final IFile file = container.getFile(new Path(fileName)); - IProject project = file.getProject(); - String projectName = project.getName(); - try { - InputStream stream; - stream = openContentStream(fileName, projectName); - if (file.exists()) { - file.setContents(stream, true, true, monitor); - } else { - file.create(stream, true, monitor); - } - stream.close(); - } catch (IOException e) { - } - monitor.worked(1); - monitor.setTaskName(PHPWizardMessages - .getString("Wizard.Monitor.openingFile")); - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow().getActivePage(); - try { - IDE.openEditor(page, file, true); - } catch (PartInitException e) { - } - } - }); - monitor.worked(1); - } - - /** - * We will initialize file contents with a sample text. - */ - private InputStream openContentStream(String fileName, String projectname) { - try { - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate( - CodeTemplateContextType.NEWHTML); - if (template == null) { - return null; - } - String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), null, lineDelimiter); - context.setFileNameVariable(fileName, projectname); - return new ByteArrayInputStream(StubUtility.evaluateTemplate( - context, template).getBytes()); - } catch (CoreException e) { - e.printStackTrace(); - return null; - } - } - - private void throwCoreException(String message) throws CoreException { - IStatus status = new Status(IStatus.ERROR, - "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); - throw new CoreException(status); - } - - /** - * We will accept the selection in the workbench to see if we can initialize - * from it. - * - * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java deleted file mode 100644 index 1b26e93..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java +++ /dev/null @@ -1,242 +0,0 @@ -package net.sourceforge.phpeclipse.wizards; - -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; - -import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; -import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.ui.WebUI; - -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.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -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.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.ui.INewWizard; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWizard; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; - -/** - * This wizard creates one file with the extension "php". - */ -public class PHPFileWizard extends Wizard implements INewWizard { - - private PHPFileWizardPage page; - - private ISelection selection; - - public PHPFileWizard() { - super(); - setNeedsProgressMonitor(true); - setWindowTitle(PHPWizardMessages - .getString("WizardNewProjectCreationPage.windowTitle")); - } - - /** - * Adding the page to the wizard. - */ - public void addPages() { - page = new PHPFileWizardPage(selection); - addPage(page); - } - - /** - * This method is called when 'Finish' button is pressed in the wizard. We - * will create an operation and run it using wizard as execution context. - */ - public boolean performFinish() { - final String containerName = page.getContainerName(); - final String fileName = page.getFileName(); - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) - throws InvocationTargetException { - try { - doFinish(containerName, fileName, monitor); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - try { - getContainer().run(true, false, op); - } catch (InterruptedException e) { - return false; - } catch (InvocationTargetException e) { - Throwable realException = e.getTargetException(); - MessageDialog.openError(getShell(), PHPWizardMessages - .getString("Wizard.error"), realException.getMessage()); - return false; - } - return true; - } - - /** - * The worker method. It will find the container, create the file if missing - * or just replace its contents, and open the editor on the newly created - * file. - */ - private void doFinish(String containerName, String fileName, - IProgressMonitor monitor) throws CoreException { - // create a sample file - monitor.beginTask(PHPWizardMessages - .getString("Wizard.Monitor.creating") - + " " + fileName, 2); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IResource resource = root.findMember(new Path(containerName)); - if (!resource.exists() || !(resource instanceof IContainer)) { - throwCoreException(PHPWizardMessages - .getString("Wizard.Monitor.containerDoesNotExistException")); - } - IContainer container = (IContainer) resource; - final IFile file = container.getFile(new Path(fileName)); - IProject project = file.getProject(); - String projectName = project.getName(); - String className = getClassName(fileName); - - try { - InputStream stream; - if (className == null) { - stream = openContentStream(fileName, projectName); - } else { - stream = openContentStreamClass(className); - } - if (file.exists()) { - file.setContents(stream, true, true, monitor); - } else { - file.create(stream, true, monitor); - } - stream.close(); - } catch (IOException e) { - } - monitor.worked(1); - monitor.setTaskName(PHPWizardMessages - .getString("Wizard.Monitor.openingFile")); - getShell().getDisplay().asyncExec(new Runnable() { - public void run() { - IWorkbenchPage page = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow().getActivePage(); - try { - IDE.openEditor(page, file, true); - } catch (PartInitException e) { - } - } - }); - monitor.worked(1); - } - - /** - * Check if the filename is like this anyname.class.php - * - * @param fFileName - * the filename - * @return the anyname or null - */ - private static final String getClassName(final String fileName) { - final int lastDot = fileName.lastIndexOf('.'); - if (lastDot == -1) - return null; - final int precLastDot = fileName.lastIndexOf('.', lastDot - 1); - if (precLastDot == -1) - return null; - if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals( - "CLASS")) - return null; - return fileName.substring(0, precLastDot); - } - - /** - * We will initialize file contents for a class - * - * @param className - * the classname - */ - private InputStream openContentStreamClass(final String className) { - StringBuffer contents = new StringBuffer(""); - return new ByteArrayInputStream(contents.toString().getBytes()); - } - - /** - * We will initialize file contents with a sample text. - */ - private InputStream openContentStream(String fileName, String projectname) { - try { - Template template = WebUI.getDefault() - .getCodeTemplateStore().findTemplate( - CodeTemplateContextType.NEWTYPE); - if (template == null) { - return null; - } - String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - CodeTemplateContext context = new CodeTemplateContext(template - .getContextTypeId(), null, lineDelimiter); - context.setFileNameVariable(fileName, projectname); - String content = StubUtility.evaluateTemplate(context, template); - if (content == null) { - content = ""; - } - return new ByteArrayInputStream(content.getBytes()); - } catch (CoreException e) { - e.printStackTrace(); - return null; - } - - } - - private void throwCoreException(String message) throws CoreException { - IStatus status = new Status(IStatus.ERROR, - "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); - throw new CoreException(status); - } - - /** - * We will accept the selection in the workbench to see if we can initialize - * from it. - * - * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) - */ - public void init(IWorkbench workbench, IStructuredSelection selection) { - this.selection = selection; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java deleted file mode 100644 index d886c5a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPlugin.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLPlugin.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui; - -import java.net.URL; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import net.sourceforge.phpeclipse.xml.ui.text.DTDTextTools; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.ImageRegistry; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.osgi.framework.BundleContext; - -/** - * The main plugin class to be used in the desktop. - */ -public class XMLPlugin extends AbstractUIPlugin { - public static final String ICON_ELEMENT = "element_obj.gif"; //$NON-NLS-1$ - - // The shared instance. - private static XMLPlugin plugin; - - // Resource bundle. - private ResourceBundle resources; - - private XMLTextTools xmlTextTools; - - private DTDTextTools dtdTextTools; - - /** - * The constructor. - */ - public XMLPlugin() { - plugin = this; - - try { - resources = ResourceBundle - .getBundle("net.sourceforge.phpeclipse.xml.ui.XMLPluginResources"); //$NON-NLS-1$ - } catch (MissingResourceException x) { - } - } - - /* - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - try { - if (xmlTextTools != null) { - xmlTextTools.dispose(); - xmlTextTools = null; - } - - if (dtdTextTools != null) { - dtdTextTools.dispose(); - dtdTextTools = null; - } - } finally { - super.stop(context); - } - } - - /** - * Returns the shared instance. - */ - public static XMLPlugin getDefault() { - return plugin; - } - - /** - * Returns the string from the plugin's resource bundle, or 'key' if not - * found. - */ - public static String getResourceString(String key) { - ResourceBundle bundle = XMLPlugin.getDefault().getResourceBundle(); - try { - return bundle.getString(key); - } catch (MissingResourceException e) { - return key; - } - } - - /** - * Returns the plugin's resource bundle. - */ - public ResourceBundle getResourceBundle() { - return resources; - } - - /** - * Returns instance of text tools for XML. - */ - public XMLTextTools getXMLTextTools() { - if (xmlTextTools == null) { - xmlTextTools = new XMLTextTools(getPreferenceStore()); - } - return xmlTextTools; - } - - /** - * Returns instance of text tools for DTD. - */ - public DTDTextTools getDTDTextTools() { - if (dtdTextTools == null) { - dtdTextTools = new DTDTextTools(getPreferenceStore()); - } - return dtdTextTools; - } - - /* - * @see AbstractUIPlugin#initializeImageRegistry(ImageRegistry) - */ - protected void initializeImageRegistry(ImageRegistry reg) { - reg.put(ICON_ELEMENT, getImageDescriptor(ICON_ELEMENT)); - } - - /** - * Returns an image descriptor for the image corresponding to the specified - * key (which is the name of the image file). - * - * @param key - * The key of the image - * @return The descriptor for the requested image, or null if - * the image could not be found - */ - private ImageDescriptor getImageDescriptor(String key) { - try { - URL url = getBundle().getEntry("/icons/" + key); //$NON-NLS-1$ - return ImageDescriptor.createFromURL(url); - } catch (IllegalStateException e) { - return null; - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPluginResources.properties b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPluginResources.properties deleted file mode 100644 index 3b08588..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/XMLPluginResources.properties +++ /dev/null @@ -1,54 +0,0 @@ -# -# Copyright (c) 2003 Christopher Lenz and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Common Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/cpl-v10.html -# -# Contributors: -# Igor Malinin - initial english resources -# -# $Id: XMLPluginResources.properties,v 1.1 2004-09-02 18:28:04 jsurfer Exp $ -# - -#### -# XML Syntax Highlighting Preferences -#### - -XmlSyntaxPreferencePage.others=Others -XmlSyntaxPreferencePage.PI=Precessing Instruction -XmlSyntaxPreferencePage.Declaration=Declaration -XmlSyntaxPreferencePage.Comment=Comment -XmlSyntaxPreferencePage.Tag=Tag Name -XmlSyntaxPreferencePage.AttName=Attribute Name -XmlSyntaxPreferencePage.AttValue=Attribute Value -XmlSyntaxPreferencePage.Entity=XML Entity -XmlSyntaxPreferencePage.CDATA=CDATA Section -XmlSyntaxPreferencePage.SmartyTag=Smarty Tag Name -XmlSyntaxPreferencePage.Conditional=Conditional Section - - -XmlSyntaxPreferencePage.description=XML Syntax Colors -XmlSyntaxPreferencePage.backgroundColor=Background Color -XmlSyntaxPreferencePage.systemDefault=System Default -XmlSyntaxPreferencePage.custom=Custom -XmlSyntaxPreferencePage.foreground=Foreground -XmlSyntaxPreferencePage.color=Color -XmlSyntaxPreferencePage.bold=Bold -XmlSyntaxPreferencePage.italic=Italic -XmlSyntaxPreferencePage.preview=Preview - -DTDMergeViewer.title=DTD Source Compare -XMLMergeViewer.title=XML Source Compare - -## Actions ## - -ContentAssistProposal.label=Content Assist@Ctrl+SPACE -ContentAssistProposal.tooltip=Content Assist -ContentAssistProposal.image= -ContentAssistProposal.description=Content Assist - -CompletionProcessor.ContextInfo.display.pattern=proposal {0} at position {1} -CompletionProcessor.ContextInfo.value.pattern=proposal {0} valid from {1} to {2} -CompletionProcessor.Proposal.ContextInfo.pattern={0} valid 5 characters around insertion point -CompletionProcessor.Proposal.hoverinfo.pattern=Java keyword: {0} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java deleted file mode 100644 index a833e92..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewer.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: DTDMergeViewer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.compare; - -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.text.DTDConfiguration; -import net.sourceforge.phpeclipse.xml.ui.text.DTDTextTools; - -import org.eclipse.compare.CompareConfiguration; -import org.eclipse.compare.contentmergeviewer.TextMergeViewer; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.TextViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -/** - * @author Igor Malinin - */ -public class DTDMergeViewer extends TextMergeViewer { - - /** - * The preference store. - */ - private IPreferenceStore preferenceStore; - - /** - * The listener for changes to the preference store. - */ - private IPropertyChangeListener propertyChangeListener; - - /** - * The DTD text tools. - */ - private DTDTextTools textTools; - - /* - * @see TextMergeViewer#TextMergeViewer(Composite, int, - * CompareConfiguration) - */ - public DTDMergeViewer(Composite parent, int style, - CompareConfiguration configuration) { - super(parent, style, configuration); - } - - // TextMergeViewer Implementation ------------------------------------------ - - /* - * @see TextMergeViewer#configureTextViewer() - */ - protected void configureTextViewer(TextViewer textViewer) { - XMLPlugin plugin = XMLPlugin.getDefault(); - - preferenceStore = plugin.getPreferenceStore(); - if (preferenceStore != null) { - propertyChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - handlePreferenceStoreChanged(event); - } - }; - preferenceStore.addPropertyChangeListener(propertyChangeListener); - } - - textTools = plugin.getDTDTextTools(); - - if (textViewer instanceof SourceViewer) { - SourceViewer sourceViewer = (SourceViewer) textViewer; - sourceViewer.configure(new DTDConfiguration(textTools)); - } - - updateBackgroundColor(); - } - - /* - * @see TextMergeViewer#getDocumentPartitioner() - */ - protected IDocumentPartitioner getDocumentPartitioner() { - return textTools.createDTDPartitioner(); - } - - /* - * @see org.eclipse.compare.contentmergeviewer.ContentMergeViewer#getTitle() - */ - public String getTitle() { - return XMLPlugin.getResourceString("DTDMergeViewer.title"); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.jface.viewers.ContentViewer#handleDispose(org.eclipse.swt.events.DisposeEvent) - */ - protected void handleDispose(DisposeEvent event) { - if (propertyChangeListener != null) { - if (preferenceStore != null) { - preferenceStore - .removePropertyChangeListener(propertyChangeListener); - } - - propertyChangeListener = null; - } - - super.handleDispose(event); - } - - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - String p = event.getProperty(); - - if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) - || p - .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - updateBackgroundColor(); - } else if (textTools.affectsBehavior(event)) { - invalidateTextPresentation(); - } - } - - private void updateBackgroundColor() { - boolean defaultBackgroundColor = preferenceStore - .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); - - if (defaultBackgroundColor) { - setBackgroundColor(null); - } else { - RGB backgroundColor = PreferenceConverter.getColor(preferenceStore, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); - setBackgroundColor(backgroundColor); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewerCreator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewerCreator.java deleted file mode 100644 index 6eeb9fc..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/DTDMergeViewerCreator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: DTDMergeViewerCreator.java,v 1.1 2004-09-02 18:28:05 jsurfer Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.compare; - -import org.eclipse.compare.CompareConfiguration; -import org.eclipse.compare.IViewerCreator; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; - -/** - * @author Igor Malinin - */ -public class DTDMergeViewerCreator implements IViewerCreator { - - /* - * @see IViewerCreator#createViewer(Composite, CompareConfiguration) - */ - public Viewer createViewer(Composite parent, CompareConfiguration config) { - return new DTDMergeViewer(parent, SWT.NULL, config); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java deleted file mode 100644 index 7947a8e..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewer.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLMergeViewer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.compare; - -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLConfiguration; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.compare.CompareConfiguration; -import org.eclipse.compare.contentmergeviewer.TextMergeViewer; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.TextViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -/** - * @author Igor Malinin - */ -public class XMLMergeViewer extends TextMergeViewer { - - /** - * The preference store. - */ - private IPreferenceStore preferenceStore; - - /** - * The listener for changes to the preference store. - */ - private IPropertyChangeListener propertyChangeListener; - - /** - * The XML text tools. - */ - private XMLTextTools textTools; - - /* - * @see TextMergeViewer#TextMergeViewer(Composite, int, - * CompareConfiguration) - */ - public XMLMergeViewer(Composite parent, int style, - CompareConfiguration configuration) { - super(parent, style, configuration); - } - - // TextMergeViewer Implementation - // ------------------------------------------ - - /* - * @see TextMergeViewer#configureTextViewer() - */ - protected void configureTextViewer(TextViewer textViewer) { - XMLPlugin plugin = XMLPlugin.getDefault(); - - preferenceStore = plugin.getPreferenceStore(); - if (preferenceStore != null) { - propertyChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - handlePreferenceStoreChanged(event); - } - }; - preferenceStore.addPropertyChangeListener(propertyChangeListener); - } - - textTools = plugin.getXMLTextTools(); - - if (textViewer instanceof SourceViewer) { - SourceViewer sourceViewer = (SourceViewer) textViewer; - sourceViewer.configure(new XMLConfiguration(textTools)); - } - - updateBackgroundColor(); - } - - /* - * @see TextMergeViewer#getDocumentPartitioner() - */ - protected IDocumentPartitioner getDocumentPartitioner() { - return textTools.createXMLPartitioner(); - } - - /* - * @see org.eclipse.compare.contentmergeviewer.ContentMergeViewer#getTitle() - */ - public String getTitle() { - return XMLPlugin.getResourceString("XMLMergeViewer.title"); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.jface.viewers.ContentViewer#handleDispose(org.eclipse.swt.events.DisposeEvent) - */ - protected void handleDispose(DisposeEvent event) { - if (propertyChangeListener != null) { - if (preferenceStore != null) { - preferenceStore - .removePropertyChangeListener(propertyChangeListener); - } - - propertyChangeListener = null; - } - - super.handleDispose(event); - } - - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - String p = event.getProperty(); - - if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) - || p - .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - updateBackgroundColor(); - } else if (textTools.affectsBehavior(event)) { - invalidateTextPresentation(); - } - } - - private void updateBackgroundColor() { - boolean defaultBackgroundColor = preferenceStore - .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); - - if (defaultBackgroundColor) { - setBackgroundColor(null); - } else { - RGB backgroundColor = PreferenceConverter.getColor(preferenceStore, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); - setBackgroundColor(backgroundColor); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewerCreator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewerCreator.java deleted file mode 100644 index 60f84c0..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/compare/XMLMergeViewerCreator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLMergeViewerCreator.java,v 1.1 2004-09-02 18:28:05 jsurfer Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.compare; - -import org.eclipse.compare.CompareConfiguration; -import org.eclipse.compare.IViewerCreator; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; - -/** - * @author Igor Malinin - */ -public class XMLMergeViewerCreator implements IViewerCreator { - - /* - * @see IViewerCreator#createViewer(Composite, CompareConfiguration) - */ - public Viewer createViewer(Composite parent, CompareConfiguration config) { - return new XMLMergeViewer(parent, SWT.NULL, config); - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java deleted file mode 100644 index 43f76d7..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/DTDEditor.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: DTDEditor.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.text.DTDConfiguration; -import net.sourceforge.phpeclipse.xml.ui.internal.text.DTDDocumentProvider; -import net.sourceforge.phpeclipse.xml.ui.text.DTDTextTools; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.ui.editors.text.TextEditor; -import org.eclipse.ui.texteditor.ContentAssistAction; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; - -/** - * DTD Editor. - * - * @author Igor Malinin - */ -public class DTDEditor extends TextEditor { - - public DTDEditor() { - setPreferenceStore(XMLPlugin.getDefault().getPreferenceStore()); - } - - /* - * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() - */ - protected void initializeEditor() { - super.initializeEditor(); - - DTDTextTools dtdTextTools = XMLPlugin.getDefault().getDTDTextTools(); - - setSourceViewerConfiguration(new DTDConfiguration(dtdTextTools)); - - setDocumentProvider(new DTDDocumentProvider()); - } - - protected boolean affectsTextPresentation(PropertyChangeEvent event) { - return XMLPlugin.getDefault().getDTDTextTools().affectsBehavior(event); - } - - protected void createActions() { - super.createActions(); - - IAction action = new ContentAssistAction(XMLEditorMessages - .getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - - // IAction action= new TextOperationAction( - // TemplateMessages.getResourceBundle(), - // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ - // this, - // ISourceViewer.CONTENTASSIST_PROPOSALS); - // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - // setAction(TEMPLATE_PROPOSALS, action); - // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java deleted file mode 100644 index 999fd08..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentProvider.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2003-2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLDocumentProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import java.net.MalformedURLException; - -import net.sourceforge.phpeclipse.xml.core.internal.model.XMLDocument; -import net.sourceforge.phpeclipse.xml.core.model.IXMLDocument; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.ui.editors.text.TextFileDocumentProvider; - -/** - * Document provider for XML files. - * - * TODO Merge the encoding detection support from I18NDocumentProvider and - * AbstractDocumentProvider into this class - * - * TODO This class currently doubles as a model manager which will need to be - * moved into core at some point, and would make this class pretty much useless - */ -public class XMLDocumentProvider extends TextFileDocumentProvider { - - // Inner Classes ----------------------------------------------------------- - - private class XMLFileInfo extends FileInfo { - IXMLDocument xmlDocument; - } - - // TestFileDocumentProvider Implementation --------------------------------- - - /* - * @see TextFileDocumentProvider#createEmptyFileInfo() - */ - protected FileInfo createEmptyFileInfo() { - return new XMLFileInfo(); - } - - /* - * @see TextFileDocumentProvider#createFileInfo(Object) - */ - protected FileInfo createFileInfo(Object element) throws CoreException { - FileInfo fileInfo = super.createFileInfo(element); - if (!(fileInfo instanceof XMLFileInfo)) { - return null; - } - - IDocument document = fileInfo.fTextFileBuffer.getDocument(); - - String systemId = null; - try { - systemId = getSystemFile(fileInfo).toURL().toString(); - } catch (MalformedURLException e) { - } - - IXMLDocument xmlDocument = createModel(document, systemId); - if (xmlDocument instanceof IDocumentListener) { - document.addDocumentListener((IDocumentListener) xmlDocument); - } - - XMLFileInfo xmlFileInfo = (XMLFileInfo) fileInfo; - xmlFileInfo.xmlDocument = xmlDocument; - - return xmlFileInfo; - } - - /* - * @see TextFileDocumentProvider#disposeFileInfo(Object, - * TextFileDocumentProvider.FileInfo) - */ - protected void disposeFileInfo(Object element, FileInfo info) { - if (info instanceof XMLFileInfo) { - IDocument document = getDocument(element); - if (document != null) { - IXMLDocument xmlDocument = ((XMLFileInfo) info).xmlDocument; - if (xmlDocument instanceof IDocumentListener) { - document - .removeDocumentListener((IDocumentListener) xmlDocument); - } - } - } - - super.disposeFileInfo(element, info); - } - - // Public Methods ---------------------------------------------------------- - - /** - * Creates the XML document model object corresponding to the specified - * document. - * - * @param document - * the document to parse - * @param systemId - * the system ID of the document - * @return the document model object - */ - public IXMLDocument createModel(IDocument document, String systemId) { - return new XMLDocument(document, systemId); - } - - /** - * Returns the XML document model associated with the specified element. - * - * @param element - * the element - * @return the document model associated with the element - */ - public IXMLDocument getModel(Object element) { - FileInfo info = getFileInfo(element); - if (info instanceof XMLFileInfo) { - XMLFileInfo xmlFileInfo = (XMLFileInfo) info; - return xmlFileInfo.xmlDocument; - } - - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java deleted file mode 100644 index 40fa9a4..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLDocumentSetupParticipant.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2004 Christopher Lenz and others - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial implementation - * - * $Id: XMLDocumentSetupParticipant.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.core.filebuffers.IDocumentSetupParticipant; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; - -/** - * Document setup participant that sets up the CSS specific partitioning. - */ -public class XMLDocumentSetupParticipant implements IDocumentSetupParticipant { - - /* - * @see IDocumentSetupParticipant#setup(IDocument) - */ - public void setup(IDocument document) { - if (document != null) { - XMLTextTools tools = XMLPlugin.getDefault().getXMLTextTools(); - IDocumentPartitioner partitioner = tools.createXMLPartitioner(); - partitioner.connect(document); - document.setDocumentPartitioner(partitioner); - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java deleted file mode 100644 index bd096c2..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditor.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * Christopher Lenz - integrated outline page - * - * $Id: XMLEditor.java,v 1.4 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import java.util.ArrayList; -import java.util.List; - -import net.sourceforge.phpeclipse.core.model.ISourceReference; -import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; -import net.sourceforge.phpeclipse.ui.text.IReconcilingParticipant; -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.outline.XMLOutlinePage; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLConfiguration; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.editors.text.TextEditor; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.ui.texteditor.ContentAssistAction; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; - -/** - * XML Editor. - * - * @author Igor Malinin - */ -public class XMLEditor extends TextEditor implements IReconcilingParticipant { - - /** - * Listens to changes to the selection in the outline page, and changes the - * selection and highlight range in the editor accordingly. - */ - private class OutlineSelectionChangedListener implements - ISelectionChangedListener { - - /* - * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection selection = (IStructuredSelection) event - .getSelection(); - if (selection.isEmpty()) { - resetHighlightRange(); - } else { - ISourceReference element = (ISourceReference) selection - .getFirstElement(); - highlightElement(element, true); - } - } - - } - - /** - * The associated outline page. - */ - XMLOutlinePage outlinePage; - - int fType; - - /** - * Listens to changes in the outline page's selection to update the editor - * selection and highlight range. - */ - private ISelectionChangedListener outlineSelectionChangedListener; - - public XMLEditor() { - this(ShowExternalPreviewAction.XML_TYPE); - } - - /** - * Constructor. - */ - public XMLEditor(int type) { - fType = type; - List stores = new ArrayList(3); - - stores.add(XMLPlugin.getDefault().getPreferenceStore()); - stores.add(EditorsUI.getPreferenceStore()); - - setPreferenceStore(new ChainedPreferenceStore( - (IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores - .size()]))); - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class adapter) { - if (adapter.equals(IContentOutlinePage.class)) { - if (outlinePage == null) { - outlinePage = new XMLOutlinePage(this); - outlineSelectionChangedListener = new OutlineSelectionChangedListener(); - outlinePage - .addSelectionChangedListener(outlineSelectionChangedListener); - } - - return outlinePage; - } - - return super.getAdapter(adapter); - } - - /* - * @see IReconcilingParticipant#reconciled() - */ - public void reconciled() { - Shell shell = getSite().getShell(); - if ((shell != null) && !shell.isDisposed()) { - shell.getDisplay().asyncExec(new Runnable() { - public void run() { - if (outlinePage != null) { - outlinePage.update(); - } - } - }); - } - } - - /* - * @see org.eclipse.ui.editors.text.TextEditor#initializeEditor() - */ - protected void initializeEditor() { - super.initializeEditor(); - - XMLTextTools xmlTextTools = XMLPlugin.getDefault().getXMLTextTools(); - setSourceViewerConfiguration(new XMLConfiguration(xmlTextTools, this)); - setDocumentProvider(new XMLDocumentProvider()); - - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction - .getInstance(); - fShowExternalPreviewAction.setEditor(this); - fShowExternalPreviewAction.update(); - if (fShowExternalPreviewAction != null) - fShowExternalPreviewAction.doRun(fType); - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) - */ - protected boolean affectsTextPresentation(PropertyChangeEvent event) { - return XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event); - } - - void highlightElement(ISourceReference element, boolean moveCursor) { - if (element != null) { - IRegion highlightRegion = element.getSourceRegion(); - setHighlightRange(highlightRegion.getOffset(), highlightRegion - .getLength(), moveCursor); - } else { - resetHighlightRange(); - } - } - - protected void createActions() { - super.createActions(); - - IAction action = new ContentAssistAction(XMLEditorMessages - .getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ - action - .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction("ContentAssistProposal", action); //$NON-NLS-1$ - markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ - - // IAction action= new TextOperationAction( - // TemplateMessages.getResourceBundle(), - // "Editor." + TEMPLATE_PROPOSALS + ".", //$NON-NLS-1$ //$NON-NLS-2$ - // this, - // ISourceViewer.CONTENTASSIST_PROPOSALS); - // action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - // setAction(TEMPLATE_PROPOSALS, action); - // markAsStateDependentAction(TEMPLATE_PROPOSALS, true); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() - */ - protected void editorSaved() { - super.editorSaved(); - ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); - if (a != null) { - a.refresh(fType); - } - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java deleted file mode 100644 index e62f203..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorActionContributor.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; - -//import org.eclipse.core.resources.IFile; -//import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -//import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.texteditor.BasicTextEditorActionContributor; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Common base class for action contributors for Java editors. - */ -public class XMLEditorActionContributor extends - BasicTextEditorActionContributor { - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart) - */ - public void setActiveEditor(IEditorPart part) { - super.setActiveEditor(part); - ITextEditor textEditor = null; - if (part instanceof ITextEditor) - textEditor = (ITextEditor) part; - - if (textEditor != null) { - //IFile file = null; - //IEditorInput editorInput = textEditor.getEditorInput(); - -// if (editorInput instanceof IFileEditorInput) { -// file = ((IFileEditorInput) editorInput).getFile(); -// } - - ShowExternalPreviewAction fShowExternalPreviewAction = ShowExternalPreviewAction - .getInstance(); - fShowExternalPreviewAction.setEditor(textEditor); - fShowExternalPreviewAction.update(); - if (fShowExternalPreviewAction != null) - fShowExternalPreviewAction - .doRun(ShowExternalPreviewAction.PHP_TYPE); - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java deleted file mode 100644 index 906e74b..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.java +++ /dev/null @@ -1,46 +0,0 @@ -/********************************************************************** - Copyright (c) 2000, 2002 IBM Corp. and others. - All rights reserved. This program and the accompanying materials - are made available under the terms of the Common Public License v1.0 - which accompanies this distribution, and is available at - http://www.eclipse.org/legal/cpl-v10.html - - Contributors: - IBM Corporation - Initial implementation - www.phpeclipse.de - **********************************************************************/ -package net.sourceforge.phpeclipse.xml.ui.internal.editor; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class XMLEditorMessages { - - private static final String RESOURCE_BUNDLE = "net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLEditorMessages";//$NON-NLS-1$ - - private static ResourceBundle fgResourceBundle = ResourceBundle - .getBundle(RESOURCE_BUNDLE); - - private XMLEditorMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - /** - * Gets a string from the resource bundle and formats it with arguments - */ - public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } - - public static ResourceBundle getResourceBundle() { - return fgResourceBundle; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.properties b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.properties deleted file mode 100644 index bea66ef..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/editor/XMLEditorMessages.properties +++ /dev/null @@ -1,10 +0,0 @@ -############################################################# -# -# (c) Copyright IBM Corp. 2000, 2001. -# All Rights Reserved. -# -############################################################# -ContentAssistProposal.label=Content Assist@Ctrl+SPACE -ContentAssistProposal.tooltip=Content Assist -ContentAssistProposal.image= -ContentAssistProposal.description=Content Assist diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java deleted file mode 100644 index 4484e94..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineContentProvider.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLOutlineContentProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.outline; - -import net.sourceforge.phpeclipse.xml.core.model.IXMLDocument; -import net.sourceforge.phpeclipse.xml.core.model.IXMLElement; - -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; - -/** - * Content provider for the XML outline page. - */ -public class XMLOutlineContentProvider implements ITreeContentProvider { - - // Instance Variables ------------------------------------------------------ - - /** - * The parsed XML document. - */ - private IXMLDocument document; - - // ITreeContentProvider Implementation ------------------------------------- - - /* - * ITreeContentProvider#getChildren(Object) - */ - public Object[] getChildren(Object parentElement) { - if (parentElement instanceof IXMLElement) { - return ((IXMLElement) parentElement).getChildren(); - } - return new Object[0]; - } - - /* - * @see ITreeContentProvider#getParent(Object) - */ - public Object getParent(Object element) { - if (element instanceof IXMLElement) { - return ((IXMLElement) element).getParent(); - } - return null; - } - - /* - * @see ITreeContentProvider#hasChildren(Object) - */ - public boolean hasChildren(Object element) { - return getChildren(element).length > 0; - } - - /* - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object) - */ - public Object[] getElements(Object inputElement) { - if ((document != null) && (document.getRoot() != null)) { - return new Object[] { document.getRoot() }; - } - return new Object[0]; - } - - /* - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - public void dispose() { - document = null; - } - - /* - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(Viewer, - * Object, Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - if (oldInput != newInput) { - if (oldInput instanceof IXMLDocument) { - document = null; - } - if (newInput instanceof IXMLDocument) { - document = (IXMLDocument) newInput; - } - } - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java deleted file mode 100644 index 38fd25c..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlineLabelProvider.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLOutlineLabelProvider.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.outline; - -import net.sourceforge.phpeclipse.xml.core.model.IXMLElement; -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; - -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.graphics.Image; - -/** - * Label provider for the XML outline page. - */ -public class XMLOutlineLabelProvider extends LabelProvider { - - // LabelProvider Implementation -------------------------------------------- - - /** - * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - if (element instanceof IXMLElement) { - return XMLPlugin.getDefault().getImageRegistry().get( - XMLPlugin.ICON_ELEMENT); - } - return null; - } - - /** - * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element instanceof IXMLElement) { - IXMLElement xmlElement = (IXMLElement) element; - StringBuffer buf = new StringBuffer(); - if (xmlElement.getPrefix() != null) { - buf.append(xmlElement.getPrefix()); - buf.append(':'); - } - buf.append(xmlElement.getLocalName()); - return buf.toString(); - } - return null; - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java deleted file mode 100644 index 0daae7d..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/outline/XMLOutlinePage.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLOutlinePage.java,v 1.3 2006-10-21 23:14:14 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.outline; - -import java.util.List; - -import net.sourceforge.phpeclipse.core.model.ISourceReference; -import net.sourceforge.phpeclipse.ui.views.outline.ProblemsLabelDecorator; -import net.sourceforge.phpeclipse.xml.core.model.IXMLDocument; -import net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLDocumentProvider; -import net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLEditor; - -import org.eclipse.jface.viewers.DecoratingLabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.views.contentoutline.ContentOutlinePage; - -/** - * Implements the outline page associated with the XML editor. - */ -public class XMLOutlinePage extends ContentOutlinePage { - - // Instance Variables ------------------------------------------------------ - - /** - * The associated editor. - */ - private XMLEditor editor; - - // Constructors ------------------------------------------------------------ - - /** - * Constructor. - * - * @param editor - * The associated text editor - */ - public XMLOutlinePage(XMLEditor editor) { - this.editor = editor; - } - - // ContentOutlinePage Implementation --------------------------------------- - - /* - * @see org.eclipse.ui.part.IPage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - TreeViewer viewer = getTreeViewer(); - viewer.setContentProvider(new XMLOutlineContentProvider()); - viewer.setLabelProvider(new DecoratingLabelProvider( - new XMLOutlineLabelProvider(), new ProblemsLabelDecorator( - editor))); - viewer.setInput(getDocument()); - } - - // Public Methods ---------------------------------------------------------- - - /** - * Selects a specific element in the outline page. - * - * @param element - * the element to select - */ - public void select(ISourceReference element) { - TreeViewer viewer = getTreeViewer(); - if (viewer != null) { - ISelection selection = viewer.getSelection(); - if (selection instanceof IStructuredSelection) { - IStructuredSelection structuredSelection = (IStructuredSelection) selection; - List elements = structuredSelection.toList(); - if (!elements.contains(element)) { - if (element == null) { - selection = StructuredSelection.EMPTY; - } else { - selection = new StructuredSelection(element); - } - viewer.setSelection(selection, true); - } - } - } - } - - /** - * Updates the outline page. - */ - public void update() { - IXMLDocument document = getDocument(); - if (document != null) { - TreeViewer viewer = getTreeViewer(); - if (viewer != null) { - Control control = viewer.getControl(); - if ((control != null) && !control.isDisposed()) { - control.setRedraw(false); - viewer.setInput(document); - viewer.expandAll(); - control.setRedraw(true); - } - } - } - } - - // Private Methods --------------------------------------------------------- - - /** - * Returns the parsed model of the XML document that is loaded into the - * associated editor. - * - * @return the parsed XML document - */ - private IXMLDocument getDocument() { - IDocumentProvider provider = editor.getDocumentProvider(); - if (provider instanceof XMLDocumentProvider) { - XMLDocumentProvider xmlProvider = (XMLDocumentProvider) provider; - return xmlProvider.getModel(editor.getEditorInput()); - } - return null; - } - -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java deleted file mode 100644 index 4b6aefb..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLPreferenceInitializer.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2002-2004 Roberto Gonzalez Rocha and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Roberto Gonzalez Rocha - Initial version - * Igor Malinin - refactoring, minor changes - * - * $Id: XMLPreferenceInitializer.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.preferences; - -/*import java.io.InputStream; -import java.util.Enumeration; -import java.util.PropertyResourceBundle; -*/ -import net.sourceforge.phpdt.core.JavaCore; -import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpeclipse.ui.IPreferenceConstants; - -import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; -import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; -import net.sourceforge.phpeclipse.ui.WebUI; -import net.sourceforge.phpeclipse.ui.preferences.ITextStylePreferences; -//import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.text.IXMLSyntaxConstants; - -//import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -/** - * @author Igor Malinin - */ -public class XMLPreferenceInitializer extends AbstractPreferenceInitializer implements IPreferenceConstants { - /* - * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() - */ - public void initializeDefaultPreferences() { - final IPreferenceStore store = /*XMLPlugin*/WebUI.getDefault() - .getPreferenceStore(); - final Display display = Display.getDefault(); - - // TODO: ChainedPreferenceStore does not work for preferences preview - - display.syncExec(new Runnable() { - public void run() { - PreferenceConverter.setDefault(store, - AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, display - .getSystemColor(SWT.COLOR_LIST_FOREGROUND) - .getRGB()); - } - }); - - store.setDefault( - AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, - true); - - display.syncExec(new Runnable() { - public void run() { - PreferenceConverter.setDefault(store, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, display - .getSystemColor(SWT.COLOR_LIST_BACKGROUND) - .getRGB()); - } - }); - - store.setDefault( - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, - true); - - // end of common preferences - - setDefault(store, IXMLSyntaxConstants.XML_DEFAULT, "0,0,0", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_TAG, "127,0,127", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_ATT_NAME, "0,127,0", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_ATT_VALUE, "0,0,255", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_ENTITY, "127,127,0", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_CDATA, "127,127,0", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_PI, "127,127,127", - ITextStylePreferences.STYLE_BOLD); - - setDefault(store, IXMLSyntaxConstants.XML_COMMENT, "127,0,0", - ITextStylePreferences.STYLE_NORMAL); - - setDefault(store, IXMLSyntaxConstants.XML_DECL, "127,0,127", - ITextStylePreferences.STYLE_BOLD); - - setDefault(store, IXMLSyntaxConstants.XML_SMARTY, "255,0,127", - ITextStylePreferences.STYLE_BOLD); - - setDefault(store, IXMLSyntaxConstants.DTD_CONDITIONAL, "127,127,0", - ITextStylePreferences.STYLE_BOLD); - - String operatingSystem = Platform.getOS(); - // maxosx, linux, solaris, win32,... - try { - /*InputStream is = getDefault() - .openStream( - new Path("prefs/default_" + operatingSystem - + ".properties")); - PropertyResourceBundle resourceBundle = new PropertyResourceBundle( - is); - Enumeration e = resourceBundle.getKeys(); - String key; - while (e.hasMoreElements()) { - key = (String) e.nextElement(); - store.setDefault(key, resourceBundle.getString(key)); - }*/ - } catch (Exception e) { - // no default properties found - if (operatingSystem.equals(Platform.OS_WIN32)) { - // store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); - // store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php - // -l -f {0}"); - // store.setDefault(MYSQL_RUN_PREF, - // "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); - // store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); - // store.setDefault(XAMPP_START_PREF, - // "c:\\xampp\\xampp_start.exe"); - // store.setDefault(XAMPP_STOP_PREF, - // "c:\\xampp\\xampp_stop.exe"); - // store.setDefault( - // ETC_HOSTS_PATH_PREF, - // "c:\\windows\\system32\\drivers\\etc\\hosts"); - } else { - // store.setDefault(PHP_RUN_PREF, "/apache/php/php"); - // store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f - // {0}"); - // store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); - // store.setDefault(APACHE_RUN_PREF, "/apache/apache"); - // store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); - // store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); - } - // store.setDefault(MYSQL_PREF, "--standalone"); - // store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot - // \"{0}\"\""); - // store.setDefault(APACHE_STOP_PREF, "-k shutdown"); - // store.setDefault(APACHE_RESTART_PREF, "-k restart"); - // store.setDefault(MYSQL_START_BACKGROUND, "true"); - // store.setDefault(APACHE_START_BACKGROUND, "true"); - // store.setDefault(APACHE_STOP_BACKGROUND, "true"); - // store.setDefault(APACHE_RESTART_BACKGROUND, "true"); - } - store.setDefault(PHP_USERDEF_XMLFILE, ""); - PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG); - PreferenceConverter.setDefault(store, PHP_KEYWORD, - PHPColorProvider.KEYWORD); - PreferenceConverter.setDefault(store, PHP_VARIABLE, - PHPColorProvider.VARIABLE); - PreferenceConverter.setDefault(store, PHP_VARIABLE_DOLLAR, - PHPColorProvider.VARIABLE); - /*PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, - PHPColorProvider.FUNCTION_NAME);*/ - - setDefault(store, PHP_FUNCTIONNAME, PHPColorProvider.FUNCTION_NAME, - ITextStylePreferences.STYLE_BOLD); - - PreferenceConverter.setDefault(store, PHP_CONSTANT, - PHPColorProvider.CONSTANT); - PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); - PreferenceConverter.setDefault(store, PHP_DEFAULT, - PHPColorProvider.DEFAULT); - PreferenceConverter.setDefault(store, PHPDOC_KEYWORD, - PHPColorProvider.PHPDOC_KEYWORD); - - PreferenceConverter.setDefault(store, PHPDOC_TAG, - PHPColorProvider.PHPDOC_TAG); - PreferenceConverter.setDefault(store, PHPDOC_LINK, - PHPColorProvider.PHPDOC_LINK); - PreferenceConverter.setDefault(store, PHPDOC_DEFAULT, - PHPColorProvider.PHPDOC_DEFAULT); - - PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, - new RGB(127, 0, 85)); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, - new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, - new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); - - - PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, - new RGB(127, 0, 85)); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); - store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, - new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); - - PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, - new RGB(0, 0, 0)); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); - store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); - - // this will initialize the static fields in the syntaxrdr class - new PHPSyntaxRdr(); - JavaCore.initializeDefaultPluginPreferences(); - PreferenceConstants.initializeDefaultValues(store); - } - - private static void setDefault(IPreferenceStore store, String constant, - String color, String style) { - store.setDefault(constant + ITextStylePreferences.SUFFIX_FOREGROUND, - color); - store.setDefault(constant + ITextStylePreferences.SUFFIX_STYLE, style); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java deleted file mode 100644 index e855df2..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/XMLSyntaxPreferencePage.java +++ /dev/null @@ -1,587 +0,0 @@ -/* - * Copyright (c) 2002-2004 Roberto Gonzalez Rocha and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Roberto Gonzalez Rocha - Initial version - * Igor Malinin - refactoring, minor changes - * - * $Id: XMLSyntaxPreferencePage.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.preferences; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import net.sourceforge.phpeclipse.ui.ColorEditor; -import net.sourceforge.phpeclipse.ui.preferences.ITextStylePreferences; -import net.sourceforge.phpeclipse.ui.preferences.OverlayPreferenceStore; -import net.sourceforge.phpeclipse.ui.preferences.PreferenceDescriptor; -import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLConfiguration; -import net.sourceforge.phpeclipse.xml.ui.text.IXMLSyntaxConstants; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.RowLayout; -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.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.List; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -/** - * The XMLSyntaxPreferencePage is a preference page that handles setting the - * colors used by the XML editors. - */ -public class XMLSyntaxPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - - public final PreferenceDescriptor[] fKeys = new PreferenceDescriptor[] { - new PreferenceDescriptor( - PreferenceDescriptor.BOOLEAN, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_DEFAULT - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_DEFAULT - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_TAG - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_TAG - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ATT_NAME - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ATT_NAME - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ATT_VALUE - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ATT_VALUE - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ENTITY - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_ENTITY - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_CDATA - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_CDATA - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_PI - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_PI - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_COMMENT - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_COMMENT - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_DECL - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_DECL - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_SMARTY - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.XML_SMARTY - + ITextStylePreferences.SUFFIX_STYLE), - - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.DTD_CONDITIONAL - + ITextStylePreferences.SUFFIX_FOREGROUND), - new PreferenceDescriptor(PreferenceDescriptor.STRING, - IXMLSyntaxConstants.DTD_CONDITIONAL - + ITextStylePreferences.SUFFIX_STYLE), }; - - OverlayPreferenceStore overlay; - - final String[][] fSyntaxColorListModel = new String[][] { - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.others"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_DEFAULT }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Tag"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_TAG }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttName"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ATT_NAME }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.AttValue"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ATT_VALUE }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Entity"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_ENTITY }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.CDATA"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_CDATA }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.PI"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_PI }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.Comment"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_COMMENT }, - { - XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.Declaration"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_DECL }, - { - XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.Conditional"), //$NON-NLS-1$ - IXMLSyntaxConstants.XML_SMARTY }, - { XMLPlugin.getResourceString("XmlSyntaxPreferencePage.SmartyTag"), //$NON-NLS-1$ - IXMLSyntaxConstants.DTD_CONDITIONAL }, }; - - private XMLTextTools xmlTextTools; - - private Color bgColor; - - Button bgDefault; - - Button bgCustom; - - ColorEditor bgColorEditor; - - List colors; - - ColorEditor fgColorEditor; - - Button fgBold; - - SourceViewer preview; - - /** - * Constructor for XMLSyntaxPreferencePage. - */ - public XMLSyntaxPreferencePage() { - setDescription(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.description")); //$NON-NLS-1$ - - setPreferenceStore(XMLPlugin.getDefault().getPreferenceStore()); - - overlay = new OverlayPreferenceStore(getPreferenceStore(), fKeys); - } - - protected Control createContents(Composite parent) { - overlay.load(); - overlay.start(); - - Composite colorComposite = new Composite(parent, SWT.NULL); - colorComposite.setLayout(new GridLayout()); - - Group backgroundComposite = new Group(colorComposite, - SWT.SHADOW_ETCHED_IN); - - backgroundComposite.setLayout(new RowLayout()); - backgroundComposite.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.backgroundColor")); //$NON-NLS-1$ - - SelectionListener backgroundSelectionListener = new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - boolean custom = bgCustom.getSelection(); - bgColorEditor.getButton().setEnabled(custom); - overlay - .setValue( - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, - !custom); - } - - public void widgetDefaultSelected(SelectionEvent e) { - } - }; - - bgDefault = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - bgDefault.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.systemDefault")); //$NON-NLS-1$ - bgDefault.addSelectionListener(backgroundSelectionListener); - - bgCustom = new Button(backgroundComposite, SWT.RADIO | SWT.LEFT); - bgCustom.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.custom")); //$NON-NLS-1$ - bgCustom.addSelectionListener(backgroundSelectionListener); - - bgColorEditor = new ColorEditor(backgroundComposite); - - Label label = new Label(colorComposite, SWT.LEFT); - label.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.foreground")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Composite editorComposite = new Composite(colorComposite, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - GridData gd = new GridData(GridData.FILL_BOTH); - editorComposite.setLayoutData(gd); - - colors = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL - | SWT.BORDER); - gd = new GridData(GridData.FILL_BOTH); - gd.heightHint = convertHeightInCharsToPixels(5); - colors.setLayoutData(gd); - - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - label = new Label(stylesComposite, SWT.LEFT); - label.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.color")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - - fgColorEditor = new ColorEditor(stylesComposite); - - Button fgColorButton = fgColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - fgColorButton.setLayoutData(gd); - - label = new Label(stylesComposite, SWT.LEFT); - label.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.bold")); //$NON-NLS-1$ - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - - fgBold = new Button(stylesComposite, SWT.CHECK); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - fgBold.setLayoutData(gd); - - label = new Label(colorComposite, SWT.LEFT); - label.setText(XMLPlugin - .getResourceString("XmlSyntaxPreferencePage.preview")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - Control previewer = createPreviewer(colorComposite); - gd = new GridData(GridData.FILL_BOTH); - gd.widthHint = convertWidthInCharsToPixels(20); - gd.heightHint = convertHeightInCharsToPixels(5); - previewer.setLayoutData(gd); - - colors.addSelectionListener(new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - handleSyntaxColorListSelection(); - } - }); - - bgColorEditor.getButton().addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - PreferenceConverter.setValue(overlay, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, - bgColorEditor.getColorValue()); - } - }); - - fgColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - PreferenceConverter.setValue(overlay, key - + ITextStylePreferences.SUFFIX_FOREGROUND, - fgColorEditor.getColorValue()); - } - }); - - fgBold.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - String value = (fgBold.getSelection()) ? ITextStylePreferences.STYLE_BOLD - : ITextStylePreferences.STYLE_NORMAL; - - overlay.setValue(key + ITextStylePreferences.SUFFIX_STYLE, - value); - } - }); - - initialize(); - - return colorComposite; - } - - private Control createPreviewer(Composite parent) { - xmlTextTools = new XMLTextTools(overlay); // REVISIT: DTD - - preview = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL - | SWT.BORDER); - - preview.configure(new XMLConfiguration(xmlTextTools)); - preview.getTextWidget().setFont( - JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); - preview.setEditable(false); - - initializeViewerColors(preview); - - String content = loadPreviewContentFromFile("preview.xml"); //$NON-NLS-1$ - IDocument document = new Document(content); - - // REVISIT: DTD - IDocumentPartitioner partitioner = xmlTextTools.createXMLPartitioner(); - - partitioner.connect(document); - document.setDocumentPartitioner(partitioner); - - preview.setDocument(document); - - overlay.addPropertyChangeListener(new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - String p = event.getProperty(); - if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) - || p - .equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - initializeViewerColors(preview); - } - - preview.invalidateTextPresentation(); - } - }); - - return preview.getControl(); - } - - /** - * Initializes the given viewer's colors. - * - * @param viewer - * the viewer to be initialized - */ - void initializeViewerColors(ISourceViewer viewer) { - if (overlay != null) { - StyledText styledText = viewer.getTextWidget(); - - // ---------- background color ---------------------- - Color color = null; - if (!overlay - .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { - color = createColor(overlay, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, - styledText.getDisplay()); - } - - styledText.setBackground(color); - - if (bgColor != null) { - bgColor.dispose(); - } - - bgColor = color; - } - } - - /** - * Creates a color from the information stored in the given preference - * store. Returns null if there is no such information - * available. - */ - private Color createColor(IPreferenceStore store, String key, - Display display) { - RGB rgb = null; - - if (store.contains(key)) { - if (store.isDefault(key)) { - rgb = PreferenceConverter.getDefaultColor(store, key); - } else { - rgb = PreferenceConverter.getColor(store, key); - } - - if (rgb != null) { - return new Color(display, rgb); - } - } - - return null; - } - - void handleSyntaxColorListSelection() { - int i = colors.getSelectionIndex(); - - String key = fSyntaxColorListModel[i][1]; - - RGB rgb = PreferenceConverter.getColor(overlay, key - + ITextStylePreferences.SUFFIX_FOREGROUND); - - fgColorEditor.setColorValue(rgb); - - // REVISIT - fgBold.setSelection(overlay.getString( - key + ITextStylePreferences.SUFFIX_STYLE).indexOf( - ITextStylePreferences.STYLE_BOLD) >= 0); - } - - private String loadPreviewContentFromFile(String filename) { - StringBuffer string = new StringBuffer(512); - - try { - char[] buf = new char[512]; - BufferedReader reader = new BufferedReader( - new InputStreamReader(XMLSyntaxPreferencePage.class - .getResourceAsStream(filename))); - - try { - while (true) { - int n = reader.read(buf); - if (n < 0) { - break; - } - - string.append(buf, 0, n); - } - } finally { - reader.close(); - } - } catch (IOException e) { - } - - return string.toString(); - } - - /** - * - */ - private void initialize() { - initializeFields(); - - for (int i = 0; i < fSyntaxColorListModel.length; i++) { - colors.add(fSyntaxColorListModel[i][0]); - } - - colors.getDisplay().asyncExec(new Runnable() { - - public void run() { - colors.select(0); - handleSyntaxColorListSelection(); - } - }); - } - - private void initializeFields() { - RGB rgb = PreferenceConverter.getColor(overlay, - AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); - bgColorEditor.setColorValue(rgb); - - boolean def = overlay - .getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT); - bgDefault.setSelection(def); - bgCustom.setSelection(!def); - bgColorEditor.getButton().setEnabled(!def); - } - - /* - * @see IWorkbenchPreferencePage#init(IWorkbench) - */ - public void init(IWorkbench workbench) { - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - overlay.loadDefaults(); - // initializeFields(); - handleSyntaxColorListSelection(); - - super.performDefaults(); - - preview.invalidateTextPresentation(); - } - - /* - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - overlay.propagate(); - XMLPlugin.getDefault().savePluginPreferences(); - - return true; - } - - /* - * @see org.eclipse.jface.dialogs.IDialogPage#dispose() - */ - public void dispose() { - if (xmlTextTools != null) { - xmlTextTools.dispose(); - xmlTextTools = null; - } - - if (overlay != null) { - overlay.stop(); - overlay = null; - } - - super.dispose(); - } -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/preview.xml b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/preview.xml deleted file mode 100644 index 2fc0edc..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/preferences/preview.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - -]> - - - - - - <text> - ]]> - - diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java deleted file mode 100644 index 10d4fee..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/AbstractDocumentProvider.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: AbstractDocumentProvider.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; - -import net.sourceforge.phpeclipse.ui.editor.I18NDocumentProvider; - -import org.eclipse.jface.text.rules.IWhitespaceDetector; - -/** - * - * - * @author Igor Malinin - */ -public abstract class AbstractDocumentProvider extends I18NDocumentProvider { - protected IWhitespaceDetector detector = new WhitespaceDetector(); - - /* - * @see org.eclipse.ui.editors.text.IStorageDocumentProvider#getDefaultEncoding() - */ - public String getDefaultEncoding() { - return "UTF-8"; - } - - public String getDeclaredEncoding(InputStream in) throws IOException { - if (!in.markSupported()) { - in = new BufferedInputStream(in, 512); - } - - in.mark(512); - String encoding = super.getDeclaredEncoding(in); - if (encoding != null) { - return encoding; - } - - in.reset(); - - // check Prolog-Start ': - state = STATE_DEFAULT; - return getToken(XML_TAG); - - case '"': - case '\'': - while (true) { - int ch = read(); - - if (ch == quot) { - state = STATE_TAG; - return getToken(XML_ATTRIBUTE); - } - - switch (ch) { - case '<': - unread(); - - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(XML_ATTRIBUTE); - } - } - default: - unread(); - } - - while (true) { - switch (read()) { - case '<': - unread(); - - case ICharacterScanner.EOF: - case '>': - state = STATE_DEFAULT; - return getToken(XML_TAG); - - case '"': - case '\'': - unread(); - - state = STATE_TAG; - return getToken(XML_TAG); - } - } - } - - private IToken nextDeclToken() { - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - - case '<': - if (parsedtd || isInternal()) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL : null); - - case '!': - case '?': - unread(); - break; - - default: - continue loop; - } - } - - unread(); - - case '>': - state &= STATE_INTERNAL; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - - case '[': // - if (!isInternal()) { - state = STATE_INTERNAL; - return getToken(XML_DECL); - } - } - } - } - - private IToken nextCommentToken() { - state &= STATE_INTERNAL; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); - continue loop; - } - } - } - - return getToken(isInternal() ? DTD_INTERNAL_COMMENT : XML_COMMENT); - } - - private IToken nextCDATAToken() { - state = STATE_DEFAULT; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ] ]]> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ]] ]]> - switch (read()) { - case ICharacterScanner.EOF: - case '>': // ]]> - break loop; - } - - unread(); - unread(); - continue loop; - } - } - } - - return getToken(XML_CDATA); - } - - private IToken nextConditionalToken() { - state = STATE_DEFAULT; - - int level = 1; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '<': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '!': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '[': - ++level; - continue loop; - } - - unread(); - continue loop; - } - - unread(); - continue loop; - - case ']': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - if (--level == 0) { - break loop; - } - - continue loop; - } - - unread(); - unread(); - continue loop; - } - } - } - - return getToken(DTD_CONDITIONAL); - } - - private IToken getToken(String type) { - length = position - offset; - - if (length == 0) { - return Token.EOF; - } - - if (type == null) { - return Token.UNDEFINED; - } - - IToken token = (IToken) tokens.get(type); - if (token == null) { - token = new Token(type); - tokens.put(type, token); - } - - return token; - } - - private boolean isInternal() { - return (state & STATE_INTERNAL) != 0; - } - - private int read() { - if (position >= end) { - return ICharacterScanner.EOF; - } - - try { - return document.getChar(position++); - } catch (BadLocationException e) { - --position; - return ICharacterScanner.EOF; - } - } - - private void unread() { - --position; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() - */ - public int getTokenOffset() { - Assert.isTrue(offset >= 0, Integer.toString(offset)); - return offset; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenLength() - */ - public int getTokenLength() { - return length; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, - * int) - */ - public void setRange(IDocument document, int offset, int length) { - this.document = document; - this.end = offset + length; - - this.offset = offset; - this.position = offset; - this.length = 0; - - this.state = STATE_DEFAULT; - } - - /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ - // public void setPartialRange(IDocument document, int offset, int length, - // String contentType, int partitionOffset) { - // state = STATE_DEFAULT; - // if (partitionOffset > -1) { - // int delta = offset - partitionOffset; - // if (delta > 0) { - // setRange(document, partitionOffset, length + delta); - // return; - // } - // } - // setRange(document, partitionOffset, length); - // } - /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ - public void setPartialRange(IDocument document, int offset, int length, - String contentType, int partitionOffset) { - // boolean flag = false; - this.document = document; - this.end = offset + length; - - // NB! Undocumented value: -1 - if (partitionOffset >= 0) { - offset = partitionOffset; - // flag = true; - } - - this.offset = offset; - this.position = offset; - this.length = 0; - - // if (flag) { - // state = STATE_DEFAULT; - // return; - // } - if (contentType == XML_ATTRIBUTE) { - state = STATE_TAG; - return; - } - - if (contentType == XML_TAG) { - state = isContinuationPartition() ? STATE_TAG : STATE_DEFAULT; - return; - } - - if (contentType == XML_DECL) { - state = isContinuationPartition() ? STATE_DECL : STATE_DEFAULT; - return; - } - - if (contentType == DTD_INTERNAL || contentType == DTD_INTERNAL_DECL - || contentType == DTD_INTERNAL_COMMENT) { - state = STATE_INTERNAL; - return; - } - - state = STATE_DEFAULT; - } - - private boolean isContinuationPartition() { - try { - String type = document.getContentType(offset - 1); - - if (type != IDocument.DEFAULT_CONTENT_TYPE) { - return true; - } - } catch (BadLocationException e) { - } - - return false; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java deleted file mode 100644 index 3eb545a..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SimpleDoubleClickStrategy.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: SimpleDoubleClickStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import net.sourceforge.phpeclipse.ui.text.TextDoubleClickStrategy; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; - -/** - * - * - * @author Igor Malinin - */ -public class SimpleDoubleClickStrategy extends TextDoubleClickStrategy { - /* - * @see org.eclipse.jface.text.ITextDoubleClickStrategy#doubleClicked(ITextViewer) - */ - public void doubleClicked(ITextViewer viewer) { - int offset = viewer.getSelectedRange().x; - if (offset < 0) { - return; - } - - try { - IDocument document = viewer.getDocument(); - - ITypedRegion region = document.getPartition(offset); - - int start = region.getOffset(); - int length = region.getLength(); - - if (offset == start) { - viewer.setSelectedRange(start, length); - return; - } - - int end = start + length - 1; - - if (offset == end && document.getChar(end) == '>') { - viewer.setSelectedRange(start, length); - return; - } - - super.doubleClicked(viewer); - } catch (BadLocationException e) { - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SingleTokenScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SingleTokenScanner.java deleted file mode 100644 index b78c796..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/SingleTokenScanner.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: SingleTokenScanner.java,v 1.1 2004-09-02 18:28:03 jsurfer Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Map; - -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.jface.text.rules.Token; - -/** - * @author Igor Malinin - */ -public class SingleTokenScanner extends RuleBasedScanner { - - /** - * Creates a single token scanner. - */ - public SingleTokenScanner(Map tokens, String property) { - setDefaultReturnToken((Token) tokens.get(property)); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java deleted file mode 100644 index 3e70d8f..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TagDoubleClickStrategy.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: TagDoubleClickStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import net.sourceforge.phpeclipse.ui.text.TextDoubleClickStrategy; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; - -/** - * - * - * @author Igor Malinin - */ -public class TagDoubleClickStrategy extends TextDoubleClickStrategy { - /* - * @see org.eclipse.jface.text.ITextDoubleClickStrategy#doubleClicked(ITextViewer) - */ - public void doubleClicked(ITextViewer viewer) { - int offset = viewer.getSelectedRange().x; - if (offset < 0) { - return; - } - - try { - IDocument document = viewer.getDocument(); - - ITypedRegion region = document.getPartition(offset); - - int start = region.getOffset(); - - if (offset == start && document.getChar(offset) == '<') { - region = document.getPartition(offset); - offset = region.getOffset() + region.getLength(); - - if (document.getChar(offset - 1) != '>') { - while (true) { - if (offset >= document.getLength()) { - break; - } - - region = document.getPartition(offset); - offset = region.getOffset() + region.getLength(); - - if (XMLPartitionScanner.XML_ATTRIBUTE.equals(region - .getType())) { - continue; - } - - if (XMLPartitionScanner.XML_TAG - .equals(region.getType())) { - if (document.getChar(region.getOffset()) == '<') { - break; - } - - if (document.getChar(offset - 1) == '>') { - break; - } - - continue; - } - - offset = region.getOffset(); - break; - } - } - - viewer.setSelectedRange(start, offset - start); - return; - } - - int end = start + region.getLength(); - - if (offset == end - 1 && document.getChar(offset) == '>') { - region = document.getPartition(offset); - offset = region.getOffset(); - - if (document.getChar(offset) != '<') { - while (true) { - if (offset <= 0) { - break; - } - - region = document.getPartition(offset - 1); - offset = region.getOffset(); - - if (XMLPartitionScanner.XML_ATTRIBUTE.equals(region - .getType())) { - continue; - } - - if (XMLPartitionScanner.XML_TAG - .equals(region.getType())) { - if (document.getChar(offset) == '<') { - break; - } - - continue; - } - - offset += region.getLength(); - break; - } - } - - viewer.setSelectedRange(offset, end - offset); - return; - } - - super.doubleClicked(viewer); - } catch (BadLocationException e) { - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java deleted file mode 100644 index 3ef9542..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/TextScanner.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: TextScanner.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Map; - -import net.sourceforge.phpeclipse.xml.ui.text.IXMLSyntaxConstants; - -import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; -import org.eclipse.jface.text.rules.IRule; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.Token; - -/** - * @author Igor Malinin - */ -public class TextScanner extends BufferedRuleBasedScanner { - - /** - * Creates a color scanner for XML text or attribute value. - */ - public TextScanner(Map tokens, char startEntity, String defaultProperty) { - setDefaultReturnToken((Token) tokens.get(defaultProperty)); - - IToken entity = (Token) tokens.get(IXMLSyntaxConstants.XML_ENTITY); - - IRule[] rules = { new EntityRule(startEntity, entity) }; - - setRules(rules); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java deleted file mode 100644 index 3efcc3e..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/WhitespaceDetector.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: WhitespaceDetector.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import org.eclipse.jface.text.rules.IWhitespaceDetector; - -/** - * XML white-space detector. - * - * @author Igor Malinin - */ -public class WhitespaceDetector implements IWhitespaceDetector { - - /** - * @see IWhitespaceDetector#isWhitespace(char) - */ - public boolean isWhitespace(char ch) { - switch (ch) { - case 0x09: - case 0x0A: - case 0x0D: - case 0x20: - return true; - - default: - return false; - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java deleted file mode 100644 index fb371b8..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotation.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLAnnotation.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import org.eclipse.jface.text.source.Annotation; - -/** - * @author Igor Malinin - */ -public class XMLAnnotation extends Annotation { - public static final String TYPE_ERROR = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ - - public static final String TYPE_WARNING = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ - - public static final String TYPE_INFO = "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$ - - public XMLAnnotation(String type, boolean persistent, String text) { - super(type, persistent, text); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java deleted file mode 100644 index 3e38663..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationHover.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2003-2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLAnnotationHover.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationHover; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.ISourceViewer; - -/** - * Implements simple annotation hover to show the associated messages. - */ -public class XMLAnnotationHover implements IAnnotationHover { - /* - * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, - * int) - */ - public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { - List annotations = getAnnotationsForLine(sourceViewer, lineNumber); - if (annotations != null) { - List messages = new ArrayList(); - - Iterator e = annotations.iterator(); - while (e.hasNext()) { - Annotation annotation = (Annotation) e.next(); - - String message = annotation.getText(); - if (message != null) { - message = message.trim(); - if (message.length() > 0) { - messages.add(message); - } - } - } - - if (messages.size() == 1) { - return (String) messages.get(0); - } - - if (messages.size() > 1) { - return formatMessages(messages); - } - } - - return null; - } - - /** - * Formats multiple annotation messages for display. - */ - private String formatMessages(List messages) { - StringBuffer buffer = new StringBuffer(); - - Iterator e = messages.iterator(); - while (e.hasNext()) { - buffer.append("- "); //$NON-NLS-1$ - buffer.append(e.next()); - buffer.append('\n'); - } - - return buffer.toString(); - } - - /** - * Returns annotations for the ruler's line of activity. - */ - private List getAnnotationsForLine(ISourceViewer viewer, int line) { - IDocument document = viewer.getDocument(); - - IAnnotationModel model = viewer.getAnnotationModel(); - if (model == null) { - return null; - } - - List retVal = new ArrayList(); - - Iterator e = new XMLAnnotationIterator(model, true); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - - Position position = model.getPosition(a); - if (position != null) { - try { - int annotationLine = document.getLineOfOffset(position - .getOffset()); - if (annotationLine == line) { - retVal.add(a); - } - } catch (BadLocationException e1) { - // ignore - } - } - } - - return retVal; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java deleted file mode 100644 index b86dea6..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLAnnotationIterator.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLAnnotationIterator.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Iterator; - -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; - -/** - * @author Igor Malinin - */ -public class XMLAnnotationIterator implements Iterator { - private boolean skipIrrelevants; - - private Iterator iterator; - - private Annotation next; - - public XMLAnnotationIterator(IAnnotationModel model, boolean skipIrrelevants) { - this.skipIrrelevants = skipIrrelevants; - - iterator = model.getAnnotationIterator(); - skip(); - } - - private void skip() { - while (iterator.hasNext()) { - Annotation next = (Annotation) iterator.next(); - if (next instanceof XMLAnnotation) { - if (skipIrrelevants) { - if (!next.isMarkedDeleted()) { - this.next = next; - return; - } - } else { - this.next = next; - return; - } - } - } - - this.next = null; - } - - /* - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() { - return (next != null); - } - - /* - * @see java.util.Iterator#next() - */ - public Object next() { - try { - return next; - } finally { - skip(); - } - } - - /* - * @see java.util.Iterator#remove() - */ - public void remove() { - throw new UnsupportedOperationException(); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLCDATAScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLCDATAScanner.java deleted file mode 100644 index 848f207..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLCDATAScanner.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLCDATAScanner.java,v 1.4 2007-06-03 11:39:00 toshihiro Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Map; - -import net.sourceforge.phpeclipse.xml.ui.text.IXMLSyntaxConstants; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.ITokenScanner; -import org.eclipse.jface.text.rules.Token; - -/** - * @author Igor Malinin - */ -public class XMLCDATAScanner implements ITokenScanner { - - private Map tokens; - - private IDocument document; - - private int begin; - - private int end; - - private int offset; - - private int length; - - private int position; - - public XMLCDATAScanner(Map tokens) { - this.tokens = tokens; - } - - /* - * @see ITokenScanner#setRange(IDocument, int, int) - */ - public void setRange(IDocument document, int offset, int length) { - this.document = document; - - this.begin = offset; - this.end = offset + length; - - this.offset = offset; - this.position = offset; - this.length = 0; - } - - /* - * @see ITokenScanner#nextToken() - */ - public IToken nextToken() { - offset += length; - - if (position == begin) { - - try { - if (document.get(position, 9).equals("")) { - if (position == p) { - position = end; - return getToken(IXMLSyntaxConstants.XML_CDATA); - } - position = p; - } else { - position = end; - } - } catch (BadLocationException e) { - } - - return getToken(IXMLSyntaxConstants.XML_DEFAULT); - } - - private IToken getToken(String type) { - length = position - offset; - - if (length == 0) { - return Token.EOF; - } - - if (type == null) { - return Token.UNDEFINED; - } - - IToken token = (IToken) tokens.get(type); - if (token == null) { - return Token.UNDEFINED; - } - - return token; - } - - /* - * @see ITokenScanner#getTokenOffset() - */ - public int getTokenOffset() { - return offset; - } - - /* - * @see ITokenScanner#getTokenLength() - */ - public int getTokenLength() { - return length; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java deleted file mode 100644 index 14a17c9..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLConfiguration.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLConfiguration.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import net.sourceforge.phpeclipse.ui.templates.template.BasicCompletionProcessor; -import net.sourceforge.phpeclipse.ui.text.TextDoubleClickStrategy; -import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; - -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextDoubleClickStrategy; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.presentation.IPresentationReconciler; -import org.eclipse.jface.text.presentation.PresentationReconciler; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.reconciler.MonoReconciler; -import org.eclipse.jface.text.rules.DefaultDamagerRepairer; -import org.eclipse.jface.text.source.IAnnotationHover; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.editors.text.TextSourceViewerConfiguration; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * XML editor configuration. - * - * @author Igor Malinin - */ -public class XMLConfiguration extends TextSourceViewerConfiguration { - protected XMLTextTools xmlTextTools; - - private ITextDoubleClickStrategy dcsDefault; - - private ITextDoubleClickStrategy dcsSimple; - - private ITextDoubleClickStrategy dcsTag; - - private ITextDoubleClickStrategy dcsAttValue; - - /** The associated editor. */ - private ITextEditor editor; - - public XMLConfiguration(XMLTextTools tools) { - this(tools, null); - } - - public XMLConfiguration(XMLTextTools tools, ITextEditor editor) { - xmlTextTools = tools; - this.editor = editor; - dcsDefault = new TextDoubleClickStrategy(); - dcsSimple = new SimpleDoubleClickStrategy(); - dcsTag = new TagDoubleClickStrategy(); - dcsAttValue = new AttValueDoubleClickStrategy(); - } - - /* - * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) - */ - public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - return new XMLAnnotationHover(); - } - - /* - * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) - */ - public ITextHover getTextHover(ISourceViewer sourceViewer, - String contentType) { - if (editor != null) { - IDocumentProvider provider = editor.getDocumentProvider(); - IEditorInput input = editor.getEditorInput(); - IAnnotationModel model = provider.getAnnotationModel(input); - return new XMLTextHover(model); - } - - return super.getTextHover(sourceViewer, contentType); - } - - /* - * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, - * String) - */ - public ITextDoubleClickStrategy getDoubleClickStrategy( - ISourceViewer sourceViewer, String contentType) { - if (XMLPartitionScanner.XML_COMMENT.equals(contentType)) { - return dcsSimple; - } - - if (XMLPartitionScanner.XML_PI.equals(contentType)) { - return dcsSimple; - } - - if (XMLPartitionScanner.XML_TAG.equals(contentType)) { - return dcsTag; - } - - if (XMLPartitionScanner.XML_ATTRIBUTE.equals(contentType)) { - return dcsAttValue; - } - - if (XMLPartitionScanner.XML_CDATA.equals(contentType)) { - return dcsSimple; - } - - if (contentType.startsWith(XMLPartitionScanner.DTD_INTERNAL)) { - return dcsSimple; - } - - return dcsDefault; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) - */ - public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { - return new String[] { IDocument.DEFAULT_CONTENT_TYPE, - XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, - XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, - XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, - XMLPartitionScanner.DTD_INTERNAL, - XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, }; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) - */ - public IPresentationReconciler getPresentationReconciler( - ISourceViewer sourceViewer) { - PresentationReconciler reconciler = new PresentationReconciler(); - - DefaultDamagerRepairer dr; - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTextScanner()); - reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); - reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); - - dr = new DefaultDamagerRepairer(xmlTextTools.getDTDTextScanner()); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLPIScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_PI); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_PI); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCommentScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_COMMENT); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_COMMENT); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLDeclScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_DECL); - reconciler.setDamager(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - reconciler.setRepairer(dr, XMLPartitionScanner.DTD_INTERNAL_DECL); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLTagScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_TAG); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_TAG); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLAttributeScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_ATTRIBUTE); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_ATTRIBUTE); - - dr = new DefaultDamagerRepairer(xmlTextTools.getXMLCDATAScanner()); - - reconciler.setDamager(dr, XMLPartitionScanner.XML_CDATA); - reconciler.setRepairer(dr, XMLPartitionScanner.XML_CDATA); - - return reconciler; - } - - /* - * @see SourceViewerConfiguration#getReconciler(ISourceViewer) - */ - public IReconciler getReconciler(ISourceViewer sourceViewer) { - if ((editor != null) && editor.isEditable()) { - MonoReconciler reconciler = new MonoReconciler( - new XMLReconcilingStrategy(editor), false); - reconciler.setProgressMonitor(new NullProgressMonitor()); - reconciler.setDelay(500); - return reconciler; - } - - return null; - } - - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - ContentAssistant assistant = new ContentAssistant(); - assistant - .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - IContentAssistProcessor processor = new BasicCompletionProcessor(); - assistant.setContentAssistProcessor(processor, - IDocument.DEFAULT_CONTENT_TYPE); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_PI); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_COMMENT); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_DECL); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_TAG); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_ATTRIBUTE); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.XML_CDATA); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.DTD_INTERNAL); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.DTD_INTERNAL_PI); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.DTD_INTERNAL_COMMENT); - assistant.setContentAssistProcessor(processor, - XMLPartitionScanner.DTD_INTERNAL_DECL); - assistant - .setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); - assistant - .setInformationControlCreator(getInformationControlCreator(sourceViewer)); - - return assistant; - } - -} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java deleted file mode 100644 index 0f41873..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLPartitionScanner.java +++ /dev/null @@ -1,592 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLPartitionScanner.java,v 1.5 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.HashMap; -import java.util.Map; - -//incastrix -//import org.eclipse.jface.text.Assert; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.rules.ICharacterScanner; -import org.eclipse.jface.text.rules.IPartitionTokenScanner; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.Token; - -/** - * - * - * @author Igor Malinin - */ -public class XMLPartitionScanner implements IPartitionTokenScanner { - public static final String XML_PI = "__xml_processing_instruction"; - - public static final String XML_COMMENT = "__xml_comment"; - - public static final String XML_DECL = "__xml_declaration"; - - public static final String XML_TAG = "__xml_tag"; - - public static final String XML_ATTRIBUTE = "__xml_attribute"; - - public static final String XML_CDATA = "__xml_cdata"; - - public static final String DTD_INTERNAL = "__dtd_internal"; - - public static final String DTD_INTERNAL_PI = "__dtd_internal_pi"; - - public static final String DTD_INTERNAL_COMMENT = "__dtd_internal_comment"; - - public static final String DTD_INTERNAL_DECL = "__dtd_internal_declaration"; - - public static final String DTD_CONDITIONAL = "__dtd_conditional"; - - public static final int STATE_DEFAULT = 0; - - public static final int STATE_TAG = 1; - - public static final int STATE_DECL = 2; - - public static final int STATE_CDATA = 4; - - public static final int STATE_INTERNAL = 8; - - protected IDocument document; - - protected int end; - - protected int offset; - - protected int length; - - protected int position; - - protected int state; - - protected boolean parsedtd; - - protected Map tokens = new HashMap(); - - public XMLPartitionScanner(boolean parsedtd) { - this.parsedtd = parsedtd; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#nextToken() - */ - public IToken nextToken() { - offset += length; - - switch (state) { - case STATE_TAG: - return nextTagToken(); - - case STATE_DECL: - return nextDeclToken(); - - case STATE_CDATA: - return nextCDATAToken(); - } - - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(null); - - case '<': - switch (read()) { - case ICharacterScanner.EOF: - if (parsedtd || isInternal()) { - break; - } - - state = STATE_DEFAULT; - return getToken(XML_TAG); - - case '?': // ': - state = STATE_DEFAULT; - return getToken(XML_TAG); - - case '"': - case '\'': - while (true) { - int ch = read(); - - if (ch == quot) { - state = STATE_TAG; - return getToken(XML_ATTRIBUTE); - } - - switch (ch) { - case '<': - unread(); - - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(XML_ATTRIBUTE); - } - } - default: - unread(); - } - - while (true) { - switch (read()) { - case '<': - unread(); - - case ICharacterScanner.EOF: - case '>': - state = STATE_DEFAULT; - return getToken(XML_TAG); - - case '"': - case '\'': - unread(); - - state = STATE_TAG; - return getToken(XML_TAG); - } - } - } - - private IToken nextDeclToken() { - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - - case '<': - if (parsedtd || isInternal()) { - switch (read()) { - case ICharacterScanner.EOF: - state = STATE_DEFAULT; - return getToken(isInternal() ? DTD_INTERNAL : null); - - case '!': - case '?': - unread(); - break; - - default: - continue loop; - } - } - - unread(); - - case '>': - state &= STATE_INTERNAL; - return getToken(isInternal() ? DTD_INTERNAL_DECL : XML_DECL); - - case '[': // - if (!isInternal()) { - state = STATE_INTERNAL; - return getToken(XML_DECL); - } - } - } - } - - private IToken nextCommentToken() { - state &= STATE_INTERNAL; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '-': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); - continue loop; - } - } - } - - return getToken(isInternal() ? DTD_INTERNAL_COMMENT : XML_COMMENT); - } - - private IToken nextPIToken() { - state &= STATE_INTERNAL; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '?': // ? ?> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - break loop; - } - - unread(); - } - } - - return getToken(isInternal() ? DTD_INTERNAL_PI : XML_PI); - } - - private IToken nextCDATAToken() { - state = STATE_DEFAULT; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ] ]]> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // ]] ]]> - switch (read()) { - case ICharacterScanner.EOF: - case '>': // ]]> - break loop; - } - - unread(); - unread(); - continue loop; - } - } - } - - return getToken(XML_CDATA); - } - - private IToken nextConditionalToken() { - state = STATE_DEFAULT; - - int level = 1; - - loop: while (true) { - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '<': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '!': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case '[': - ++level; - continue loop; - } - - unread(); - continue loop; - } - - unread(); - continue loop; - - case ']': // - --> - switch (read()) { - case ICharacterScanner.EOF: - break loop; - - case ']': // -- --> - switch (read()) { - case ICharacterScanner.EOF: - case '>': - if (--level == 0) { - break loop; - } - - continue loop; - } - - unread(); - unread(); - continue loop; - } - } - } - - return getToken(DTD_CONDITIONAL); - } - - private IToken getToken(String type) { - length = position - offset; - - if (length == 0) { - return Token.EOF; - } - - if (type == null) { - return Token.UNDEFINED; - } - - IToken token = (IToken) tokens.get(type); - if (token == null) { - token = new Token(type); - tokens.put(type, token); - } - - return token; - } - - private boolean isInternal() { - return (state & STATE_INTERNAL) != 0; - } - - private int read() { - if (position >= end) { - return ICharacterScanner.EOF; - } - - try { - return document.getChar(position++); - } catch (BadLocationException e) { - --position; - return ICharacterScanner.EOF; - } - } - - private void unread() { - --position; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenOffset() - */ - public int getTokenOffset() { - Assert.isTrue(offset >= 0, Integer.toString(offset)); - return offset; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#getTokenLength() - */ - public int getTokenLength() { - return length; - } - - /* - * @see org.eclipse.jface.text.rules.ITokenScanner#setRange(IDocument, int, - * int) - */ - public void setRange(IDocument document, int offset, int length) { - this.document = document; - this.end = offset + length; - - this.offset = offset; - this.position = offset; - this.length = 0; - - this.state = STATE_DEFAULT; - } - - /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ - // public void setPartialRange(IDocument document, int offset, int length, - // String contentType, int partitionOffset) { - // state = STATE_DEFAULT; - // if (partitionOffset > -1) { - // int delta = offset - partitionOffset; - // if (delta > 0) { - // setRange(document, partitionOffset, length + delta); - // return; - // } - // } - // setRange(document, partitionOffset, length); - // } - /* - * @see org.eclipse.jface.text.rules.IPartitionTokenScanner - */ - public void setPartialRange(IDocument document, int offset, int length, - String contentType, int partitionOffset) { - // boolean flag = false; - this.document = document; - this.end = offset + length; - - // NB! Undocumented value: -1 - if (partitionOffset >= 0) { - offset = partitionOffset; - // flag = true; - } - - this.offset = offset; - this.position = offset; - this.length = 0; - - // if (flag) { - // state = STATE_DEFAULT; - // return; - // } - if (contentType == XML_ATTRIBUTE) { - state = STATE_TAG; - return; - } - - if (contentType == XML_TAG) { - state = isContinuationPartition() ? STATE_TAG : STATE_DEFAULT; - return; - } - - if (contentType == XML_DECL) { - state = isContinuationPartition() ? STATE_DECL : STATE_DEFAULT; - return; - } - - if (contentType == DTD_INTERNAL || contentType == DTD_INTERNAL_PI - || contentType == DTD_INTERNAL_DECL - || contentType == DTD_INTERNAL_COMMENT) { - state = STATE_INTERNAL; - return; - } - - state = STATE_DEFAULT; - } - - private boolean isContinuationPartition() { - try { - String type = document.getContentType(offset - 1); - - if (type != IDocument.DEFAULT_CONTENT_TYPE) { - return true; - } - } catch (BadLocationException e) { - } - - return false; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java deleted file mode 100644 index 4bfbac7..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcileStep.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) 2003-2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLReconcileStep.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sourceforge.phpeclipse.xml.core.model.IXMLDocument; -import net.sourceforge.phpeclipse.xml.core.parser.IProblem; -import net.sourceforge.phpeclipse.xml.core.parser.IProblemCollector; -import net.sourceforge.phpeclipse.xml.ui.internal.editor.XMLDocumentProvider; - -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.reconciler.AbstractReconcileStep; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilableModel; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Implementation of a reconcile step for building the XML parse tree on changes - * to the editor content. - */ -public class XMLReconcileStep extends AbstractReconcileStep { - - // Inner Classes ----------------------------------------------------------- - - /** - * Adapts an IXMLDocument to the - * IReconcilableModel interface. - */ - private class XMLDocumentAdapter implements IReconcilableModel { - private IXMLDocument document; - - public XMLDocumentAdapter(IXMLDocument document) { - this.document = document; - } - - public IXMLDocument getDocument() { - return document; - } - - } - - /** - * Implementation of the problem collector interface for creating problem - * annotations when there are problems parsing the style sheet. - */ - private class ProblemCollector implements IProblemCollector { - /** - * The list of problems added to this collector. - */ - private List collectedProblems = new ArrayList(); - - /** - * @see IProblemCollector#addProblem(IProblem) - */ - public void addProblem(IProblem problem) { - collectedProblems.add(problem); - } - - /** - * Returns the list of problems collected while the CSS source has been - * parsed, in the order they were reported. The list returned is - * immutable. - * - * @return the list of collected problems (of type {@link IProblem}) - */ - public List getProblems() { - return Collections.unmodifiableList(collectedProblems); - } - } - - /** - * Adapter that adapts an {@link IProblem} to an {@link Annotation}. - */ - private class ProblemAdapter extends AnnotationAdapter { - private IProblem problem; - - private Position position; - - public ProblemAdapter(IProblem problem) { - this.problem = problem; - } - - public Position getPosition() { - if (position == null) { - position = createPositionFromProblem(); - } - - return position; - } - - public Annotation createAnnotation() { - int start = problem.getSourceStart(); - if (start < 0) { - return null; - } - - int length = problem.getSourceEnd() - start + 1; - if (length < 0) { - return null; - } - - String type; - if (problem.isWarning()) { - type = XMLAnnotation.TYPE_ERROR; - } else if (problem.isError()) { - type = XMLAnnotation.TYPE_WARNING; - } else { - type = XMLAnnotation.TYPE_INFO; - } - - return new XMLAnnotation(type, false, problem.getMessage()); - } - - private Position createPositionFromProblem() { - int start = problem.getSourceStart(); - if (start < 0) { - return null; - } - - int length = problem.getSourceEnd() - problem.getSourceStart() + 1; - if (length < 0) { - return null; - } - - return new Position(start, length); - } - - } - - // Instance Variables ------------------------------------------------------ - - private ITextEditor editor; - - private XMLDocumentAdapter xmlDocumentAdapter; - - // Constructors ------------------------------------------------------------ - - /** - * Default constructor. - */ - public XMLReconcileStep(ITextEditor editor) { - this.editor = editor; - - xmlDocumentAdapter = new XMLDocumentAdapter(getXMLDocument()); - } - - /** - * Constructor. - * - * @param step - * the step to add to the pipe - * @param editor - * the associated text editor - */ - public XMLReconcileStep(IReconcileStep step, ITextEditor editor) { - super(step); - - this.editor = editor; - - xmlDocumentAdapter = new XMLDocumentAdapter(getXMLDocument()); - } - - // AbstractReconcileStep Implementation ------------------------------------ - - /* - * @see AbstractReconcileStep#reconcileModel(DirtyRegion, IRegion) - */ - protected IReconcileResult[] reconcileModel(DirtyRegion dirtyRegion, - IRegion subRegion) { - IXMLDocument model = xmlDocumentAdapter.getDocument(); - - IEditorInput editorInput = null; - IFile file = null; - if (editor != null) { - editorInput = editor.getEditorInput(); - } - - if (editorInput instanceof IFileEditorInput) - file = ((IFileEditorInput) editorInput).getFile(); - ProblemCollector problemCollector = new ProblemCollector(); - model.reconcile(problemCollector, file); - - List problems = problemCollector.getProblems(); - IReconcileResult[] retVal = new IReconcileResult[problems.size()]; - for (int i = 0; i < problems.size(); i++) { - IProblem problem = (IProblem) problems.get(i); - retVal[i] = new ProblemAdapter(problem); - } - - return retVal; - } - - /* - * @see AbstractReconcileStep#getModel() - */ - public IReconcilableModel getModel() { - return xmlDocumentAdapter; - } - - // Private Methods Implementation ------------------------------------------ - - /** - * Retrieve the style sheet associated with the editor input. - */ - private IXMLDocument getXMLDocument() { - IDocumentProvider documentProvider = editor.getDocumentProvider(); - if (documentProvider instanceof XMLDocumentProvider) { - XMLDocumentProvider xmlDocumentProvider = (XMLDocumentProvider) documentProvider; - return xmlDocumentProvider.getModel(editor.getEditorInput()); - } - - return null; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java deleted file mode 100644 index 47a7798..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLReconcilingStrategy.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2003-2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLReconcilingStrategy.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; - -import net.sourceforge.phpeclipse.ui.text.IReconcilingParticipant; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.actions.WorkspaceModifyOperation; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * Reconciling strategy for XML document. This class is responsible for keeping - * the parsed model in sync with the text. - */ -public class XMLReconcilingStrategy implements IReconcilingStrategy, - IReconcilingStrategyExtension { - - // Instance Variables ------------------------------------------------------ - - /** - * The associated text editor. - */ - private ITextEditor editor; - - /** - * A progress monitor that should be used for long-running operations. - */ - IProgressMonitor progressMonitor; - - /** - * The first (and only) reconcile step is the parsing of the style sheet. - */ - private IReconcileStep firstStep; - - // Constructors ------------------------------------------------------------ - - public XMLReconcilingStrategy(ITextEditor editor) { - this.editor = editor; - firstStep = new XMLReconcileStep(editor); - } - - // IReconcilingStrategy Implementation ------------------------------------- - - /** - * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - removeTemporaryAnnotations(); - process(firstStep.reconcile(dirtyRegion, subRegion)); - } - - /** - * @see IReconcilingStrategy#reconcile(IRegion) - */ - public void reconcile(IRegion partition) { - removeTemporaryAnnotations(); - process(firstStep.reconcile(partition)); - } - - /** - * @see IReconcilingStrategy#setDocument(IDocument) - */ - public void setDocument(IDocument document) { - // FIXME - firstStep.setInputModel(null); // new DocumentAdapter(document); - } - - // IReconcilingStrategyExtension Implementation ---------------------------- - - /** - * @see IReconcilingStrategyExtension#initialReconcile() - */ - public void initialReconcile() { - process(firstStep.reconcile(null)); - } - - /** - * @see IReconcilingStrategyExtension#setProgressMonitor(IProgressMonitor) - */ - public void setProgressMonitor(IProgressMonitor monitor) { - firstStep.setProgressMonitor(monitor); - progressMonitor = monitor; - } - - // Private Methods --------------------------------------------------------- - - /** - * Returns the annotation model for the editor input. - * - * @return the annotation model - */ - IAnnotationModel getAnnotationModel() { - IEditorInput input = editor.getEditorInput(); - return editor.getDocumentProvider().getAnnotationModel(input); - } - - /** - * Adds results of the reconcilation to the annotation model. - */ - private void process(final IReconcileResult[] results) { - if (results == null) { - return; - } - - IRunnableWithProgress runnable = new WorkspaceModifyOperation() { - protected void execute(IProgressMonitor monitor) { - for (int i = 0; i < results.length; i++) { - if ((progressMonitor != null) - && (progressMonitor.isCanceled())) { - return; - } - - if (results[i] instanceof AnnotationAdapter) { - AnnotationAdapter result = (AnnotationAdapter) results[i]; - Position pos = result.getPosition(); - Annotation annotation = result.createAnnotation(); - getAnnotationModel().addAnnotation(annotation, pos); - } - } - } - }; - - try { - runnable.run(null); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - if (editor instanceof IReconcilingParticipant) { - ((IReconcilingParticipant) editor).reconciled(); - } - } - - /* - * TODO A "real" implementation must be smarter, i.e. don't remove and add - * the annotations which are the same. - */ - private void removeTemporaryAnnotations() { - Iterator i = getAnnotationModel().getAnnotationIterator(); - while (i.hasNext()) { - Annotation annotation = (Annotation) i.next(); - if (!annotation.isPersistent()) { - getAnnotationModel().removeAnnotation(annotation); - } - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java deleted file mode 100644 index da8fa87..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagRule.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLTagRule.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import org.eclipse.jface.text.rules.ICharacterScanner; -import org.eclipse.jface.text.rules.IRule; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.Token; - -/** - * Rule detecting XML tag brackets and name. - * - * @author Igor Malinin - */ -public class XMLTagRule implements IRule { - - private IToken token; - - public XMLTagRule(IToken token) { - this.token = token; - } - - public IToken evaluate(ICharacterScanner scanner) { - int ch = scanner.read(); - if (ch == '>') { - return token; - } - if (ch == '/') { - ch = scanner.read(); - if (ch == '>') { - return token; - } - - scanner.unread(); - scanner.unread(); - return Token.UNDEFINED; - } - if (ch == '<') { - ch = scanner.read(); - if (ch == '/') { - ch = scanner.read(); - } - loop: while (true) { - switch (ch) { - case ICharacterScanner.EOF: - case 0x09: - case 0x0A: - case 0x0D: - case 0x20: - break loop; - } - - ch = scanner.read(); - } - - scanner.unread(); - return token; - } - scanner.unread(); - return Token.UNDEFINED; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java deleted file mode 100644 index f0ef3d1..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTagScanner.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLTagScanner.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Map; - -import net.sourceforge.phpeclipse.xml.ui.text.IXMLSyntaxConstants; - -import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; -import org.eclipse.jface.text.rules.IRule; -import org.eclipse.jface.text.rules.IToken; -import org.eclipse.jface.text.rules.Token; -import org.eclipse.jface.text.rules.WordRule; - -/** - * @author Igor Malinin - */ -public class XMLTagScanner extends BufferedRuleBasedScanner { - - /** - * Creates a color token scanner. - */ - public XMLTagScanner(Map tokens) { - setDefaultReturnToken((Token) tokens - .get(IXMLSyntaxConstants.XML_DEFAULT)); - - IToken tag = (Token) tokens.get(IXMLSyntaxConstants.XML_TAG); - IToken attribute = (Token) tokens.get(IXMLSyntaxConstants.XML_ATT_NAME); - - IRule[] rules = { new XMLTagRule(tag), - new WordRule(new NameDetector(), attribute), }; - - setRules(rules); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java deleted file mode 100644 index 998f415..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLTextHover.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2003-2004 Christopher Lenz and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Christopher Lenz - initial API and implementation - * - * $Id: XMLTextHover.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import java.util.Iterator; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; - -/** - * Implements simple annotation hover to show the associated messages. - */ -public class XMLTextHover implements ITextHover { - /** - * This hovers annotation model. - */ - private IAnnotationModel model; - - /** - * Creates a new annotation hover. - * - * @param model - * this hover's annotation model - */ - public XMLTextHover(IAnnotationModel model) { - this.model = model; - } - - /* - * @see ITextHover#getHoverInfo(ITextViewer, IRegion) - */ - public String getHoverInfo(ITextViewer textViewer, IRegion region) { - Iterator e = new XMLAnnotationIterator(model, true); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - - Position p = model.getPosition(a); - if (p.overlapsWith(region.getOffset(), region.getLength())) { - String text = a.getText(); - if ((text != null) && (text.trim().length() > 0)) { - return text; - } - } - } - - return null; - } - - /* - * @see ITextHover#getHoverRegion(ITextViewer, int) - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - return XMLWordFinder.findWord(textViewer.getDocument(), offset); - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java deleted file mode 100644 index 4e2fbd8..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/internal/text/XMLWordFinder.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial implementation - * - * $Id: XMLWordFinder.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ -package net.sourceforge.phpeclipse.xml.ui.internal.text; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; - -/** - * - * - * @author Igor Malinin - */ -public class XMLWordFinder { - public static IRegion findWord(IDocument document, int offset) { - int length = document.getLength(); - - try { - int pos = offset; - - while (pos >= 0) { - if (!Character.isUnicodeIdentifierPart(document.getChar(pos))) { - break; - } - --pos; - } - - int start = pos; - - pos = offset; - - while (pos < length) { - if (!Character.isUnicodeIdentifierPart(document.getChar(pos))) { - break; - } - ++pos; - } - - int end = pos; - - if (start == offset) { - return new Region(start, end - start); - } - - return new Region(start + 1, end - start - 1); - } catch (BadLocationException x) { - return null; - } - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java deleted file mode 100644 index 04b79fc..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/DTDTextTools.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: DTDTextTools.java,v 1.3 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.text; - -import java.util.Map; - -import net.sourceforge.phpeclipse.ui.text.AbstractTextTools; -import net.sourceforge.phpeclipse.xml.ui.internal.text.DeclScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.SingleTokenScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.TextScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLPartitionScanner; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IDocumentPartitioner; -//import org.eclipse.jface.text.rules.DefaultPartitioner; -import org.eclipse.jface.text.rules.FastPartitioner; -//import org.eclipse.jface.text.rules.IPartitionTokenScanner; -import org.eclipse.jface.text.rules.RuleBasedScanner; - -/** - * - * - * @author Igor Malinin - */ -public class DTDTextTools extends AbstractTextTools { - private static final String[] TOKENS = { IXMLSyntaxConstants.XML_DEFAULT, - IXMLSyntaxConstants.XML_ATT_NAME, - IXMLSyntaxConstants.XML_ATT_VALUE, IXMLSyntaxConstants.XML_ENTITY, - IXMLSyntaxConstants.XML_PI, IXMLSyntaxConstants.XML_COMMENT, - IXMLSyntaxConstants.XML_DECL, IXMLSyntaxConstants.DTD_CONDITIONAL, }; - - private static final String[] TYPES = { XMLPartitionScanner.XML_PI, - XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.DTD_CONDITIONAL, }; - - /** The DTD partitions scanner */ - private XMLPartitionScanner dtdPartitionScanner; - - /** The DTD text scanner */ - private TextScanner dtdTextScanner; - - /** The DTD conditional sections scanner */ - private SingleTokenScanner dtdConditionalScanner; - - /** The XML processing instructions scanner */ - private SingleTokenScanner xmlPIScanner; - - /** The XML comments scanner */ - private SingleTokenScanner xmlCommentScanner; - - /** The XML declarations scanner */ - private DeclScanner xmlDeclScanner; - - /** - * Creates a new DTD text tools collection. - */ - public DTDTextTools(IPreferenceStore store) { - super(store, TOKENS); - - dtdPartitionScanner = new XMLPartitionScanner(true); - - Map tokens = getTokens(); - - dtdTextScanner = new TextScanner(tokens, '%', - IXMLSyntaxConstants.XML_DEFAULT); - - dtdConditionalScanner = new SingleTokenScanner(tokens, - IXMLSyntaxConstants.DTD_CONDITIONAL); // cond - - xmlPIScanner = new SingleTokenScanner(tokens, - IXMLSyntaxConstants.XML_PI); - - xmlCommentScanner = new SingleTokenScanner(tokens, - IXMLSyntaxConstants.XML_COMMENT); - - xmlDeclScanner = new DeclScanner(tokens); - } - - /** - * - */ - public IDocumentPartitioner createDTDPartitioner() { - return new /*DefaultPartitioner*/FastPartitioner(dtdPartitionScanner, TYPES); - } - - /** - * - */ -// public IPartitionTokenScanner getDTDPartitionScanner() { -// return dtdPartitionScanner; -// } - - /** - * Returns a scanner which is configured to scan DTD text. - * - * @return an DTD text scanner - */ - public RuleBasedScanner getDTDTextScanner() { - return dtdTextScanner; - } - - /** - * Returns a scanner which is configured to scan DTD conditional sections. - * - * @return an DTD conditional section scanner - */ - public RuleBasedScanner getDTDConditionalScanner() { - return dtdConditionalScanner; - } - - /** - * Returns a scanner which is configured to scan XML processing - * instructions. - * - * @return an XML processing instruction scanner - */ - public RuleBasedScanner getXMLPIScanner() { - return xmlPIScanner; - } - - /** - * Returns a scanner which is configured to scan XML comments. - * - * @return an XML comment scanner - */ - public RuleBasedScanner getXMLCommentScanner() { - return xmlCommentScanner; - } - - /** - * Returns a scanner which is configured to scan XML declarations. - * - * @return an XML declaration scanner - */ - public RuleBasedScanner getXMLDeclScanner() { - return xmlDeclScanner; - } -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java deleted file mode 100644 index 7f3e194..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/IXMLSyntaxConstants.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: IXMLSyntaxConstants.java,v 1.2 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.text; - -/** - * @author Igor Malinin - */ -public interface IXMLSyntaxConstants { - - /** - * Note: This constant is for internal use only. Clients should not use this - * constant. The prefix all color constants start with. - */ - String PREFIX = "xml_"; //$NON-NLS-1$ - - /** The style key for XML text. */ - String XML_DEFAULT = PREFIX + "text"; //$NON-NLS-1$ - - /** The style key for XML tag names. */ - String XML_TAG = PREFIX + "tag"; //$NON-NLS-1$ - - /** The style key for XML attribute names. */ - String XML_ATT_NAME = PREFIX + "attribute"; //$NON-NLS-1$ - - /** The style key for XML attribute values. */ - String XML_ATT_VALUE = PREFIX + "string"; //$NON-NLS-1$ - - /** The style key for XML entities. */ - String XML_ENTITY = PREFIX + "entity"; //$NON-NLS-1$ - - /** The style key for XML processing instructions. */ - String XML_PI = PREFIX + "processing_instruction"; //$NON-NLS-1$ - - /** The style key for XML CDATA sections. */ - String XML_CDATA = PREFIX + "cdata"; //$NON-NLS-1$ - - /** The style key for XML comments. */ - String XML_COMMENT = PREFIX + "comment"; //$NON-NLS-1$ - - /** The style key for XML declaration. */ - String XML_DECL = PREFIX + "declaration"; //$NON-NLS-1$ - - /** The style key for external DTD conditional sections. */ - String DTD_CONDITIONAL = PREFIX + "conditional"; //$NON-NLS-1$ - - /** The style key for SMARTY tag names. */ - String XML_SMARTY = PREFIX + "smarty"; //$NON-NLS-1$ -} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java b/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java deleted file mode 100644 index 5ae2620..0000000 --- a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/xml/ui/text/XMLTextTools.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2002-2004 Widespace, OU and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Common Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/cpl-v10.html - * - * Contributors: - * Igor Malinin - initial contribution - * - * $Id: XMLTextTools.java,v 1.4 2006-10-21 23:14:13 pombredanne Exp $ - */ - -package net.sourceforge.phpeclipse.xml.ui.text; - -import java.util.Map; - -import net.sourceforge.phpeclipse.ui.text.AbstractTextTools; -import net.sourceforge.phpeclipse.xml.ui.internal.text.DeclScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.PHPXMLPartitionScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.SingleTokenScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.TextScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLCDATAScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLPartitionScanner; -import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLTagScanner; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IDocumentPartitioner; -//import org.eclipse.jface.text.rules.DefaultPartitioner; -import org.eclipse.jface.text.rules.FastPartitioner; -import org.eclipse.jface.text.rules.ITokenScanner; -import org.eclipse.jface.text.rules.RuleBasedScanner; - -/** - * - * - * @author Igor Malinin - */ -public class XMLTextTools extends AbstractTextTools { - /** Text Attributes for XML editors */ - public static final String[] TOKENS = { IXMLSyntaxConstants.XML_DEFAULT, - IXMLSyntaxConstants.XML_TAG, IXMLSyntaxConstants.XML_ATT_NAME, - IXMLSyntaxConstants.XML_ATT_VALUE, IXMLSyntaxConstants.XML_ENTITY, - IXMLSyntaxConstants.XML_PI, IXMLSyntaxConstants.XML_CDATA, - IXMLSyntaxConstants.XML_COMMENT, IXMLSyntaxConstants.XML_SMARTY, - IXMLSyntaxConstants.XML_DECL, }; - - /** Content types for XML editors */ - public static final String[] TYPES = { XMLPartitionScanner.XML_PI, - XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, - XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, - XMLPartitionScanner.XML_CDATA, XMLPartitionScanner.DTD_INTERNAL, - XMLPartitionScanner.DTD_INTERNAL_PI, - XMLPartitionScanner.DTD_INTERNAL_COMMENT, - XMLPartitionScanner.DTD_INTERNAL_DECL, }; - - /** The XML partitions scanner */ - private XMLPartitionScanner xmlPartitionScanner; - - private PHPXMLPartitionScanner phpXMLPartitionScanner; - - /** The XML text scanner */ - private TextScanner xmlTextScanner; - - /** The DTD text scanner */ - private TextScanner dtdTextScanner; - - /** The XML tags scanner */ - private XMLTagScanner xmlTagScanner; - - /** The XML attributes scanner */ - private TextScanner xmlAttributeScanner; - - /** The XML CDATA sections scanner */ - private XMLCDATAScanner xmlCDATAScanner; - - /** The XML processing instructions scanner */ - private SingleTokenScanner xmlPIScanner; - - /** The XML comments scanner */ - private SingleTokenScanner xmlCommentScanner; - - /** The XML declarations scanner */ - private DeclScanner xmlDeclScanner; - - public XMLTextTools(IPreferenceStore store) { - this(store, TOKENS); - } - - /** - * Creates a new XML text tools collection. - */ - public XMLTextTools(IPreferenceStore store, String[] strTokens) { - super(store, strTokens); - - xmlPartitionScanner = new XMLPartitionScanner(false); - phpXMLPartitionScanner = new PHPXMLPartitionScanner(false); - Map tokens = getTokens(); - - xmlTextScanner = new TextScanner(tokens, '&', - IXMLSyntaxConstants.XML_DEFAULT); - - dtdTextScanner = new TextScanner(tokens, '%', - IXMLSyntaxConstants.XML_DEFAULT); - - xmlPIScanner = new SingleTokenScanner(tokens, - IXMLSyntaxConstants.XML_PI); - - xmlCommentScanner = new SingleTokenScanner(tokens, - IXMLSyntaxConstants.XML_COMMENT); - - xmlDeclScanner = new DeclScanner(tokens); - - xmlTagScanner = new XMLTagScanner(tokens); - - xmlAttributeScanner = new TextScanner(tokens, '&', - IXMLSyntaxConstants.XML_ATT_VALUE); - - xmlCDATAScanner = new XMLCDATAScanner(tokens); - } - - /** - * - */ - public IDocumentPartitioner createXMLPartitioner() { - return new /*DefaultPartitioner*/FastPartitioner(xmlPartitionScanner, TYPES); - } - - public IDocumentPartitioner createPHPXMLPartitioner() { - return new /*DefaultPartitioner*/FastPartitioner(phpXMLPartitionScanner, TYPES); - } - - /** - * - */ - // public IPartitionTokenScanner getXMLPartitionScanner() { - // return xmlPartitionScanner; - // } - /** - * Returns a scanner which is configured to scan XML text. - * - * @return an XML text scanner - */ - public RuleBasedScanner getXMLTextScanner() { - return xmlTextScanner; - } - - /** - * Returns a scanner which is configured to scan DTD text. - * - * @return an DTD text scanner - */ - public RuleBasedScanner getDTDTextScanner() { - return dtdTextScanner; - } - - /** - * Returns a scanner which is configured to scan XML tags. - * - * @return an XML tag scanner - */ - public RuleBasedScanner getXMLTagScanner() { - return xmlTagScanner; - } - - /** - * Returns a scanner which is configured to scan XML tag attributes. - * - * @return an XML tag attribute scanner - */ - public RuleBasedScanner getXMLAttributeScanner() { - return xmlAttributeScanner; - } - - /** - * Returns a scanner which is configured to scan XML CDATA sections. - * - * @return an XML CDATA section scanner - */ - public ITokenScanner getXMLCDATAScanner() { - return xmlCDATAScanner; - } - - /** - * Returns a scanner which is configured to scan XML processing - * instructions. - * - * @return an XML processing instruction scanner - */ - public RuleBasedScanner getXMLPIScanner() { - return xmlPIScanner; - } - - /** - * Returns a scanner which is configured to scan XML comments. - * - * @return an XML comment scanner - */ - public RuleBasedScanner getXMLCommentScanner() { - return xmlCommentScanner; - } - - /** - * Returns a scanner which is configured to scan XML declarations. - * - * @return an XML declaration scanner - */ - public RuleBasedScanner getXMLDeclScanner() { - return xmlDeclScanner; - } -} diff --git a/net.sourceforge.phpeclipse.webbrowser/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.webbrowser/META-INF/MANIFEST.MF index 18432bf..d073cda 100644 --- a/net.sourceforge.phpeclipse.webbrowser/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.webbrowser/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse WebBrowser Bundle-SymbolicName: net.sourceforge.phpeclipse.webbrowser; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: webbrowser.jar Bundle-Activator: net.sourceforge.phpeclipse.webbrowser.internal.WebBrowserUIPlugin Bundle-Vendor: PHPEclipse Development Team @@ -14,5 +14,4 @@ Require-Bundle: org.eclipse.core.resources;bundle-version="3.0.0", org.eclipse.core.runtime;bundle-version="3.0.0", org.eclipse.ui;bundle-version="3.0.0", org.eclipse.ui.ide;bundle-version="3.0.0" -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy diff --git a/net.sourceforge.phpeclipse.xdebug.core/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.xdebug.core/META-INF/MANIFEST.MF index d0060f8..a37d26f 100644 --- a/net.sourceforge.phpeclipse.xdebug.core/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.xdebug.core/META-INF/MANIFEST.MF @@ -1,18 +1,18 @@ Manifest-Version: 1.0 Bundle-Name: XDebug Core Plug-in Bundle-SymbolicName: net.sourceforge.phpeclipse.xdebug.core;singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: core.jar Bundle-Activator: net.sourceforge.phpeclipse.xdebug.core.XDebugCorePlugin Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, org.eclipse.debug.core, + org.eclipse.core.resources, net.sourceforge.phpeclipse, net.sourceforge.phpeclipse.externaltools Export-Package: net.sourceforge.phpeclipse.xdebug.core, net.sourceforge.phpeclipse.xdebug.php.launching, net.sourceforge.phpeclipse.xdebug.php.model -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy Bundle-ManifestVersion: 2 Bundle-Vendor: PHPEclipse project team diff --git a/net.sourceforge.phpeclipse.xdebug.feature/feature.xml b/net.sourceforge.phpeclipse.xdebug.feature/feature.xml index 344fed6..26bdce5 100644 --- a/net.sourceforge.phpeclipse.xdebug.feature/feature.xml +++ b/net.sourceforge.phpeclipse.xdebug.feature/feature.xml @@ -2,7 +2,7 @@ @@ -236,12 +236,12 @@ litigation. id="net.sourceforge.phpeclipse.xdebug.ui" download-size="0" install-size="0" - version="0.0.0"/> + version="1.2.10.qualifier"/> + version="1.2.10.qualifier"/> diff --git a/net.sourceforge.phpeclipse.xdebug.ui/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.xdebug.ui/META-INF/MANIFEST.MF index 12722c3..cf9435a 100644 --- a/net.sourceforge.phpeclipse.xdebug.ui/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.xdebug.ui/META-INF/MANIFEST.MF @@ -2,19 +2,21 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: XDebug Ui Plug-in Bundle-SymbolicName: net.sourceforge.phpeclipse.xdebug.ui;singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: ui.jar Bundle-Activator: net.sourceforge.phpeclipse.xdebug.ui.XDebugUIPlugin -Require-Bundle: org.eclipse.core.runtime, +Require-Bundle: org.eclipse.core.resources, + org.eclipse.core.runtime, + org.eclipse.debug.core, org.eclipse.debug.ui, org.eclipse.jface.text, org.eclipse.ui, + org.eclipse.ui.editors, org.eclipse.ui.ide, org.eclipse.ui.workbench.texteditor, + net.sourceforge.phpeclipse, net.sourceforge.phpeclipse.externaltools, net.sourceforge.phpeclipse.xdebug.core, net.sourceforge.phpeclipse.ui Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-Vendor: PHPEclipse project team -Import-Package: net.sourceforge.phpeclipse diff --git a/net.sourceforge.phpeclipse.xml.core/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.xml.core/META-INF/MANIFEST.MF index a1cb201..bf67847 100644 --- a/net.sourceforge.phpeclipse.xml.core/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.xml.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse XML Core Bundle-SymbolicName: net.sourceforge.phpeclipse.xml.core;singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: xmlcore.jar Bundle-Vendor: PHPEclipse project team Bundle-Localization: plugin @@ -14,5 +14,4 @@ Require-Bundle: net.sourceforge.phpeclipse.core, org.eclipse.core.resources, org.eclipse.core.runtime, org.eclipse.text -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy diff --git a/net.sourceforge.phpeclipse.xml.ui/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse.xml.ui/META-INF/MANIFEST.MF index 4c37cb2..1be4db5 100644 --- a/net.sourceforge.phpeclipse.xml.ui/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse.xml.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: PHPEclipse XML UI Bundle-SymbolicName: net.sourceforge.phpeclipse.xml.ui; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: xmlui.jar Bundle-Activator: net.sourceforge.phpeclipse.xml.ui.XMLPlugin Bundle-Vendor: PHPEclipse project team @@ -11,8 +11,8 @@ Export-Package: net.sourceforge.phpeclipse.xml.ui, net.sourceforge.phpeclipse.xml.ui.internal.compare;x-internal:=true, net.sourceforge.phpeclipse.xml.ui.internal.editor;x-internal:=true, net.sourceforge.phpeclipse.xml.ui.internal.outline;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.preferences;x-internal:=true, - net.sourceforge.phpeclipse.xml.ui.internal.text;x-internal:=true, + net.sourceforge.phpeclipse.xml.ui.internal.preferences;x-internal:=false, + net.sourceforge.phpeclipse.xml.ui.internal.text;x-internal:=false, net.sourceforge.phpeclipse.xml.ui.text Require-Bundle: net.sourceforge.phpeclipse.core, net.sourceforge.phpeclipse.xml.core, @@ -26,5 +26,4 @@ Require-Bundle: net.sourceforge.phpeclipse.core, org.eclipse.ui.ide, org.eclipse.ui.views, org.eclipse.ui.workbench.texteditor -Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-ActivationPolicy: lazy diff --git a/net.sourceforge.phpeclipse/.settings/org.eclipse.jdt.core.prefs b/net.sourceforge.phpeclipse/.settings/org.eclipse.jdt.core.prefs index 1db5bb9..7b36b8c 100644 --- a/net.sourceforge.phpeclipse/.settings/org.eclipse.jdt.core.prefs +++ b/net.sourceforge.phpeclipse/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,12 @@ -#Fri Sep 07 14:46:22 PDT 2007 +#Tue Jan 17 21:12:31 CET 2012 eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/net.sourceforge.phpeclipse/META-INF/MANIFEST.MF b/net.sourceforge.phpeclipse/META-INF/MANIFEST.MF index e32a817..d8705c2 100644 --- a/net.sourceforge.phpeclipse/META-INF/MANIFEST.MF +++ b/net.sourceforge.phpeclipse/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: net.sourceforge.phpeclipse; singleton:=true -Bundle-Version: 0.0.0 +Bundle-Version: 1.2.10.qualifier Bundle-ClassPath: compatibility.jar, phpeclipse.jar Bundle-Activator: net.sourceforge.phpeclipse.PHPeclipsePlugin @@ -33,25 +33,77 @@ Export-Package: net.sourceforge.phpdt.core, net.sourceforge.phpdt.internal.core.jdom;x-internal:=true, net.sourceforge.phpdt.internal.core.util;x-internal:=true, net.sourceforge.phpdt.internal.corext;x-internal:=true, - net.sourceforge.phpdt.internal.corext.phpdoc, + net.sourceforge.phpdt.internal.corext.codemanipulation;x-internal:=true, + net.sourceforge.phpdt.internal.corext.phpdoc;x-internal:=true, + net.sourceforge.phpdt.internal.corext.refactoring.util;x-internal:=true, net.sourceforge.phpdt.internal.corext.template;x-internal:=true, net.sourceforge.phpdt.internal.corext.template.php;x-internal:=true, - net.sourceforge.phpdt.internal.corext.textmanipulation;x-internal:=true, net.sourceforge.phpdt.internal.corext.util;x-internal:=true, net.sourceforge.phpdt.internal.formatter;x-internal:=true, net.sourceforge.phpdt.internal.formatter.impl;x-internal:=true, + net.sourceforge.phpdt.internal.ui;x-internal:=true, + net.sourceforge.phpdt.internal.ui.actions;x-internal:=true, + net.sourceforge.phpdt.internal.ui.dialogs;x-internal:=true, + net.sourceforge.phpdt.internal.ui.dnd;x-internal:=true, + net.sourceforge.phpdt.internal.ui.filters;x-internal:=true, + net.sourceforge.phpdt.internal.ui.phpdocexport;x-internal:=true, + net.sourceforge.phpdt.internal.ui.preferences;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.comment;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.folding;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.java;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.java.hover;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.link;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.phpdoc;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.spelling;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.spelling.engine;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.template;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.template.contentassist;x-internal:=true, + net.sourceforge.phpdt.internal.ui.text.template.preferences;x-internal:=true, + net.sourceforge.phpdt.internal.ui.util;x-internal:=true, + net.sourceforge.phpdt.internal.ui.viewsupport;x-internal:=true, + net.sourceforge.phpdt.internal.ui.wizards;x-internal:=true, + net.sourceforge.phpdt.internal.ui.wizards.dialogfields;x-internal:=true, net.sourceforge.phpdt.ltk.core, + net.sourceforge.phpdt.ltk.ui, + net.sourceforge.phpdt.ltk.ui.actions, + net.sourceforge.phpdt.ltk.ui.wizards, + net.sourceforge.phpdt.ui, + net.sourceforge.phpdt.ui.actions, + net.sourceforge.phpdt.ui.text, + net.sourceforge.phpdt.ui.text.folding, + net.sourceforge.phpdt.ui.text.java.hover, + net.sourceforge.phpdt.ui.wizards, net.sourceforge.phpeclipse, + net.sourceforge.phpeclipse.actions, net.sourceforge.phpeclipse.builder, + net.sourceforge.phpeclipse.obfuscator, + net.sourceforge.phpeclipse.obfuscator.export, + net.sourceforge.phpeclipse.phpeditor, + net.sourceforge.phpeclipse.phpeditor.actions, + net.sourceforge.phpeclipse.phpeditor.php, + net.sourceforge.phpeclipse.phpeditor.util, net.sourceforge.phpeclipse.preferences, - net.sourceforge.phpeclipse.wizards + net.sourceforge.phpeclipse.wizards, + net.sourceforge.phpeclipse.wizards.html Require-Bundle: org.eclipse.core.runtime, + org.eclipse.ui, + org.eclipse.ui.console, org.eclipse.core.resources, + org.eclipse.search, + org.eclipse.debug.ui, + org.eclipse.jface.text, + org.eclipse.ui.workbench.texteditor, + org.eclipse.ui.ide, + org.eclipse.ui.views, + org.eclipse.ui.editors, + org.eclipse.team.core, + org.eclipse.search, + net.sourceforge.phpeclipse.webbrowser, + net.sourceforge.phpeclipse.externaltools, + net.sourceforge.phpeclipse.ui, + net.sourceforge.phpeclipse.xml.ui, org.eclipse.ltk.core.refactoring, - org.eclipse.text;bundle-version="3.4.0", - org.eclipse.swt, - org.eclipse.ui.ide + org.eclipse.ltk.ui.refactoring Bundle-ActivationPolicy: lazy -Bundle-RequiredExecutionEnvironment: J2SE-1.4 -Import-Package: net.sourceforge.phpdt.internal.core.util, - org.eclipse.core.filebuffers +Import-Package: net.sourceforge.phpeclipse.phpeditor diff --git a/net.sourceforge.phpeclipse/icons/clcl16/add_exc.gif b/net.sourceforge.phpeclipse/icons/clcl16/add_exc.gif new file mode 100644 index 0000000..a321874 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/add_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/alphab_sort_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/alphab_sort_co.gif new file mode 100644 index 0000000..6d77244 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/alphab_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/class_obj.gif b/net.sourceforge.phpeclipse/icons/clcl16/class_obj.gif new file mode 100644 index 0000000..10baaac Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/class_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/clear_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/clear_co.gif new file mode 100644 index 0000000..2558326 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/clear_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/collapseall.gif b/net.sourceforge.phpeclipse/icons/clcl16/collapseall.gif new file mode 100644 index 0000000..0bae56c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/collapseall.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/default_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/default_co.gif new file mode 100644 index 0000000..19d27de Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/default_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/definingtype_sort_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/definingtype_sort_co.gif new file mode 100644 index 0000000..b32f336 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/definingtype_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/exc_catch.gif b/net.sourceforge.phpeclipse/icons/clcl16/exc_catch.gif new file mode 100644 index 0000000..e6cb8b1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/exc_catch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/fields_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/fields_co.gif new file mode 100644 index 0000000..e14ce56 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/fields_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/filter_ps.gif b/net.sourceforge.phpeclipse/icons/clcl16/filter_ps.gif new file mode 100644 index 0000000..1492b4e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/filter_ps.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/final_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/final_co.gif new file mode 100644 index 0000000..9528145 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/final_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/flatLayout.gif b/net.sourceforge.phpeclipse/icons/clcl16/flatLayout.gif new file mode 100644 index 0000000..b84df08 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/flatLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/gointo_toplevel_type.gif b/net.sourceforge.phpeclipse/icons/clcl16/gointo_toplevel_type.gif new file mode 100644 index 0000000..0533fc2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/gointo_toplevel_type.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/hexad_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/hexad_co.gif new file mode 100644 index 0000000..ec7455b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/hexad_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/hierarchicalLayout.gif b/net.sourceforge.phpeclipse/icons/clcl16/hierarchicalLayout.gif new file mode 100644 index 0000000..e597c3d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/hierarchicalLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/hierarchy_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/hierarchy_co.gif new file mode 100644 index 0000000..59ecde8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/hierarchy_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/history_list.gif b/net.sourceforge.phpeclipse/icons/clcl16/history_list.gif new file mode 100644 index 0000000..0b8d0ed Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/history_list.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/impl_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/impl_co.gif new file mode 100644 index 0000000..5a8c7ea Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/impl_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/inher_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/inher_co.gif new file mode 100644 index 0000000..414fa6a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/inher_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/lock_close.gif b/net.sourceforge.phpeclipse/icons/clcl16/lock_close.gif new file mode 100644 index 0000000..2bcdbf0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/lock_close.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/metharg_obj.gif b/net.sourceforge.phpeclipse/icons/clcl16/metharg_obj.gif new file mode 100644 index 0000000..f300af6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/metharg_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/pack_empty_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/pack_empty_co.gif new file mode 100644 index 0000000..da642a1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/pack_empty_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/private_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/private_co.gif new file mode 100644 index 0000000..b5b8853 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/private_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/protected_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/protected_co.gif new file mode 100644 index 0000000..2b76d36 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/protected_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/public_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/public_co.gif new file mode 100644 index 0000000..18103b1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/public_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/refresh_nav.gif b/net.sourceforge.phpeclipse/icons/clcl16/refresh_nav.gif new file mode 100644 index 0000000..a063c23 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/refresh_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/remove_exc.gif b/net.sourceforge.phpeclipse/icons/clcl16/remove_exc.gif new file mode 100644 index 0000000..12a9167 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/remove_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/removea_exc.gif b/net.sourceforge.phpeclipse/icons/clcl16/removea_exc.gif new file mode 100644 index 0000000..2c069ab Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/removea_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/search_sortmatch.gif b/net.sourceforge.phpeclipse/icons/clcl16/search_sortmatch.gif new file mode 100644 index 0000000..9ed470d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/search_sortmatch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/static_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/static_co.gif new file mode 100644 index 0000000..10d08ae Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/static_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/sub_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/sub_co.gif new file mode 100644 index 0000000..c8f0628 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/sub_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/super_co.gif b/net.sourceforge.phpeclipse/icons/clcl16/super_co.gif new file mode 100644 index 0000000..199d4b7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/super_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/synced.gif b/net.sourceforge.phpeclipse/icons/clcl16/synced.gif new file mode 100644 index 0000000..f865f3a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/synced.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/th_horizontal.gif b/net.sourceforge.phpeclipse/icons/clcl16/th_horizontal.gif new file mode 100644 index 0000000..f4c14a4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/th_horizontal.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/th_showqualified.gif b/net.sourceforge.phpeclipse/icons/clcl16/th_showqualified.gif new file mode 100644 index 0000000..3aa2efa Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/th_showqualified.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/th_single.gif b/net.sourceforge.phpeclipse/icons/clcl16/th_single.gif new file mode 100644 index 0000000..c3a7519 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/th_single.gif differ diff --git a/net.sourceforge.phpeclipse/icons/clcl16/th_vertical.gif b/net.sourceforge.phpeclipse/icons/clcl16/th_vertical.gif new file mode 100644 index 0000000..f685839 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/clcl16/th_vertical.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/comment_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/comment_edit.gif new file mode 100644 index 0000000..9fa43d5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/comment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/disp_sbook.gif b/net.sourceforge.phpeclipse/icons/ctool16/disp_sbook.gif new file mode 100644 index 0000000..f9fb6b0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/disp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/export_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/export_wiz.gif new file mode 100644 index 0000000..5a01b75 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/export_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/exportdir_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/exportdir_wiz.gif new file mode 100644 index 0000000..168c6ee Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/exportdir_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/exportjar_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/exportjar_wiz.gif new file mode 100644 index 0000000..6388d79 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/exportjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/format_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/format_edit.gif new file mode 100644 index 0000000..b924a33 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/format_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/import_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/import_wiz.gif new file mode 100644 index 0000000..6152fd7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/import_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/importjar_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/importjar_wiz.gif new file mode 100644 index 0000000..870aeab Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/importjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/insp_sbook.gif b/net.sourceforge.phpeclipse/icons/ctool16/insp_sbook.gif new file mode 100644 index 0000000..2b645a8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/insp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/java_app.gif b/net.sourceforge.phpeclipse/icons/ctool16/java_app.gif new file mode 100644 index 0000000..6c14675 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/java_app.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/java_attach.gif b/net.sourceforge.phpeclipse/icons/ctool16/java_attach.gif new file mode 100644 index 0000000..b33f4a0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/java_attach.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/javadoc.gif b/net.sourceforge.phpeclipse/icons/ctool16/javadoc.gif new file mode 100644 index 0000000..e2bbdf6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/javadoc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/jdoc_hover_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/jdoc_hover_edit.gif new file mode 100644 index 0000000..afbeba3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/jdoc_hover_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newfield_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newfield_wiz.gif new file mode 100644 index 0000000..33a542b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newfield_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newint_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newint_wiz.gif new file mode 100644 index 0000000..3b703cd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newint_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newjprj_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newjprj_wiz.gif new file mode 100644 index 0000000..c533510 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newjprj_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newjworkingSet_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newjworkingSet_wiz.gif new file mode 100644 index 0000000..6c14675 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newjworkingSet_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newpack_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newpack_wiz.gif new file mode 100644 index 0000000..415063f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newpack_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newpackfolder_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newpackfolder_wiz.gif new file mode 100644 index 0000000..9da3670 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newpackfolder_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/newsbook_wiz.gif b/net.sourceforge.phpeclipse/icons/ctool16/newsbook_wiz.gif new file mode 100644 index 0000000..2590cf5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/newsbook_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/next_error_nav.gif b/net.sourceforge.phpeclipse/icons/ctool16/next_error_nav.gif new file mode 100644 index 0000000..775842e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/next_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/opentype.gif b/net.sourceforge.phpeclipse/icons/ctool16/opentype.gif new file mode 100644 index 0000000..40d2bc9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/opentype.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/pack_sbook.gif b/net.sourceforge.phpeclipse/icons/ctool16/pack_sbook.gif new file mode 100644 index 0000000..3aa2efa Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/pack_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/php.gif b/net.sourceforge.phpeclipse/icons/ctool16/php.gif new file mode 100644 index 0000000..3694fbe Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/php.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/php_page.gif b/net.sourceforge.phpeclipse/icons/ctool16/php_page.gif new file mode 100644 index 0000000..dc6de60 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/php_page.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/prev_error_nav.gif b/net.sourceforge.phpeclipse/icons/ctool16/prev_error_nav.gif new file mode 100644 index 0000000..3b1bb7c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/prev_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/run_sbook.gif b/net.sourceforge.phpeclipse/icons/ctool16/run_sbook.gif new file mode 100644 index 0000000..95d53e4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/run_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/segment_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/segment_edit.gif new file mode 100644 index 0000000..be9eb92 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/segment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/shift_l_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/shift_l_edit.gif new file mode 100644 index 0000000..2700d54 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/shift_l_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/shift_r_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/shift_r_edit.gif new file mode 100644 index 0000000..fed1373 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/shift_r_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/term_sbook.gif b/net.sourceforge.phpeclipse/icons/ctool16/term_sbook.gif new file mode 100644 index 0000000..d47876f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/term_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ctool16/uncomment_edit.gif b/net.sourceforge.phpeclipse/icons/ctool16/uncomment_edit.gif new file mode 100644 index 0000000..4b3d884 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ctool16/uncomment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/browse_persp.gif b/net.sourceforge.phpeclipse/icons/cview16/browse_persp.gif new file mode 100644 index 0000000..857ad49 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/browse_persp.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/class_hi.gif b/net.sourceforge.phpeclipse/icons/cview16/class_hi.gif new file mode 100644 index 0000000..3ffaf4c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/class_hi.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/classfilegeneration_tab.gif b/net.sourceforge.phpeclipse/icons/cview16/classfilegeneration_tab.gif new file mode 100644 index 0000000..83cbb07 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/classfilegeneration_tab.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/errorwarning_tab.gif b/net.sourceforge.phpeclipse/icons/cview16/errorwarning_tab.gif new file mode 100644 index 0000000..f42eefd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/errorwarning_tab.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/hierch_persp.gif b/net.sourceforge.phpeclipse/icons/cview16/hierch_persp.gif new file mode 100644 index 0000000..9277395 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/hierch_persp.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/jdkcompliance_tab.gif b/net.sourceforge.phpeclipse/icons/cview16/jdkcompliance_tab.gif new file mode 100644 index 0000000..3a59b3c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/jdkcompliance_tab.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/jperspective.gif b/net.sourceforge.phpeclipse/icons/cview16/jperspective.gif new file mode 100644 index 0000000..0080b32 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/jperspective.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/members.gif b/net.sourceforge.phpeclipse/icons/cview16/members.gif new file mode 100644 index 0000000..f4fb313 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/members.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/package.gif b/net.sourceforge.phpeclipse/icons/cview16/package.gif new file mode 100644 index 0000000..77b3b80 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/package.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/packages.gif b/net.sourceforge.phpeclipse/icons/cview16/packages.gif new file mode 100644 index 0000000..67ebb3f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/packages.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/projects.gif b/net.sourceforge.phpeclipse/icons/cview16/projects.gif new file mode 100644 index 0000000..06839c0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/projects.gif differ diff --git a/net.sourceforge.phpeclipse/icons/cview16/types.gif b/net.sourceforge.phpeclipse/icons/cview16/types.gif new file mode 100644 index 0000000..6da652d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/cview16/types.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/add_exc.gif b/net.sourceforge.phpeclipse/icons/dlcl16/add_exc.gif new file mode 100644 index 0000000..c5b450a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/add_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/alphab_sort_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/alphab_sort_co.gif new file mode 100644 index 0000000..62a8fdb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/alphab_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/class_obj.gif b/net.sourceforge.phpeclipse/icons/dlcl16/class_obj.gif new file mode 100644 index 0000000..5c10745 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/class_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/clear_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/clear_co.gif new file mode 100644 index 0000000..d873c49 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/clear_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/collapseall.gif b/net.sourceforge.phpeclipse/icons/dlcl16/collapseall.gif new file mode 100644 index 0000000..0bae56c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/collapseall.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/default_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/default_co.gif new file mode 100644 index 0000000..452fb2f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/default_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/definingtype_sort_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/definingtype_sort_co.gif new file mode 100644 index 0000000..23a7291 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/definingtype_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/exc_catch.gif b/net.sourceforge.phpeclipse/icons/dlcl16/exc_catch.gif new file mode 100644 index 0000000..cec357c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/exc_catch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/fields_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/fields_co.gif new file mode 100644 index 0000000..49bf697 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/fields_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/filter_ps.gif b/net.sourceforge.phpeclipse/icons/dlcl16/filter_ps.gif new file mode 100644 index 0000000..2b6285b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/filter_ps.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/final_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/final_co.gif new file mode 100644 index 0000000..d75db8a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/final_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/flatLayout.gif b/net.sourceforge.phpeclipse/icons/dlcl16/flatLayout.gif new file mode 100644 index 0000000..aa0160d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/flatLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/gointo_toplevel_type.gif b/net.sourceforge.phpeclipse/icons/dlcl16/gointo_toplevel_type.gif new file mode 100644 index 0000000..b8e29ff Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/gointo_toplevel_type.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/hexad_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/hexad_co.gif new file mode 100644 index 0000000..44d1b77 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/hexad_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/hierarchicalLayout.gif b/net.sourceforge.phpeclipse/icons/dlcl16/hierarchicalLayout.gif new file mode 100644 index 0000000..76f3360 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/hierarchicalLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/hierarchy_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/hierarchy_co.gif new file mode 100644 index 0000000..a91aa7e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/hierarchy_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/history_list.gif b/net.sourceforge.phpeclipse/icons/dlcl16/history_list.gif new file mode 100644 index 0000000..5a8b119 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/history_list.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/impl_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/impl_co.gif new file mode 100644 index 0000000..d71b1a0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/impl_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/inher_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/inher_co.gif new file mode 100644 index 0000000..a2b3356 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/inher_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/lock_close.gif b/net.sourceforge.phpeclipse/icons/dlcl16/lock_close.gif new file mode 100644 index 0000000..9067936 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/lock_close.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/metharg_obj.gif b/net.sourceforge.phpeclipse/icons/dlcl16/metharg_obj.gif new file mode 100644 index 0000000..b3597e3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/metharg_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/pack_empty_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/pack_empty_co.gif new file mode 100644 index 0000000..1319191 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/pack_empty_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/private_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/private_co.gif new file mode 100644 index 0000000..01891e2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/private_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/protected_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/protected_co.gif new file mode 100644 index 0000000..9d77745 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/protected_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/public_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/public_co.gif new file mode 100644 index 0000000..2733d9c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/public_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/refresh_nav.gif b/net.sourceforge.phpeclipse/icons/dlcl16/refresh_nav.gif new file mode 100644 index 0000000..b2281b4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/refresh_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/remove_exc.gif b/net.sourceforge.phpeclipse/icons/dlcl16/remove_exc.gif new file mode 100644 index 0000000..7e0ad4a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/remove_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/removea_exc.gif b/net.sourceforge.phpeclipse/icons/dlcl16/removea_exc.gif new file mode 100644 index 0000000..7ace43e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/removea_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/search_sortmatch.gif b/net.sourceforge.phpeclipse/icons/dlcl16/search_sortmatch.gif new file mode 100644 index 0000000..8a47d61 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/search_sortmatch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/static_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/static_co.gif new file mode 100644 index 0000000..7c78e8c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/static_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/sub_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/sub_co.gif new file mode 100644 index 0000000..eb77439 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/sub_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/super_co.gif b/net.sourceforge.phpeclipse/icons/dlcl16/super_co.gif new file mode 100644 index 0000000..c30f0e2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/super_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/synced.gif b/net.sourceforge.phpeclipse/icons/dlcl16/synced.gif new file mode 100644 index 0000000..ae5d548 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/synced.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/th_horizontal.gif b/net.sourceforge.phpeclipse/icons/dlcl16/th_horizontal.gif new file mode 100644 index 0000000..02e35a4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/th_horizontal.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/th_showqualified.gif b/net.sourceforge.phpeclipse/icons/dlcl16/th_showqualified.gif new file mode 100644 index 0000000..3aa2efa Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/th_showqualified.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/th_single.gif b/net.sourceforge.phpeclipse/icons/dlcl16/th_single.gif new file mode 100644 index 0000000..1419ba5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/th_single.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dlcl16/th_vertical.gif b/net.sourceforge.phpeclipse/icons/dlcl16/th_vertical.gif new file mode 100644 index 0000000..e548d11 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dlcl16/th_vertical.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/comment_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/comment_edit.gif new file mode 100644 index 0000000..1197d0c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/comment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/disp_sbook.gif b/net.sourceforge.phpeclipse/icons/dtool16/disp_sbook.gif new file mode 100644 index 0000000..d2d6592 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/disp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/export_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/export_wiz.gif new file mode 100644 index 0000000..13959f3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/export_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/exportjar_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/exportjar_wiz.gif new file mode 100644 index 0000000..c829da3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/exportjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/format_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/format_edit.gif new file mode 100644 index 0000000..fb2cd70 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/format_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/import_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/import_wiz.gif new file mode 100644 index 0000000..a3934cb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/import_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/importjar_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/importjar_wiz.gif new file mode 100644 index 0000000..1776c73 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/importjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/insp_sbook.gif b/net.sourceforge.phpeclipse/icons/dtool16/insp_sbook.gif new file mode 100644 index 0000000..27b96a7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/insp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/java_app.gif b/net.sourceforge.phpeclipse/icons/dtool16/java_app.gif new file mode 100644 index 0000000..36536c6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/java_app.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/java_attach.gif b/net.sourceforge.phpeclipse/icons/dtool16/java_attach.gif new file mode 100644 index 0000000..8a4369e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/java_attach.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/javadoc.gif b/net.sourceforge.phpeclipse/icons/dtool16/javadoc.gif new file mode 100644 index 0000000..66ea5a2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/javadoc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/jdoc_hover_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/jdoc_hover_edit.gif new file mode 100644 index 0000000..f352844 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/jdoc_hover_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newclass_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newclass_wiz.gif new file mode 100644 index 0000000..859df29 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newclass_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newfield_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newfield_wiz.gif new file mode 100644 index 0000000..c679d44 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newfield_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newint_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newint_wiz.gif new file mode 100644 index 0000000..c4c09a0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newint_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newjprj_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newjprj_wiz.gif new file mode 100644 index 0000000..17404dd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newjprj_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newjworkingSet_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newjworkingSet_wiz.gif new file mode 100644 index 0000000..36536c6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newjworkingSet_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newpack_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newpack_wiz.gif new file mode 100644 index 0000000..981ea97 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newpack_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newpackfolder_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newpackfolder_wiz.gif new file mode 100644 index 0000000..edd8a08 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newpackfolder_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/newsbook_wiz.gif b/net.sourceforge.phpeclipse/icons/dtool16/newsbook_wiz.gif new file mode 100644 index 0000000..2705628 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/newsbook_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/next_error_nav.gif b/net.sourceforge.phpeclipse/icons/dtool16/next_error_nav.gif new file mode 100644 index 0000000..874bf69 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/next_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/opentype.gif b/net.sourceforge.phpeclipse/icons/dtool16/opentype.gif new file mode 100644 index 0000000..09c754c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/opentype.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/pack_sbook.gif b/net.sourceforge.phpeclipse/icons/dtool16/pack_sbook.gif new file mode 100644 index 0000000..1319191 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/pack_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/prev_error_nav.gif b/net.sourceforge.phpeclipse/icons/dtool16/prev_error_nav.gif new file mode 100644 index 0000000..4c32376 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/prev_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/run_sbook.gif b/net.sourceforge.phpeclipse/icons/dtool16/run_sbook.gif new file mode 100644 index 0000000..a38e4ad Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/run_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/segment_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/segment_edit.gif new file mode 100644 index 0000000..6844777 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/segment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/shift_l_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/shift_l_edit.gif new file mode 100644 index 0000000..a93966e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/shift_l_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/shift_r_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/shift_r_edit.gif new file mode 100644 index 0000000..c1254af Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/shift_r_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/term_sbook.gif b/net.sourceforge.phpeclipse/icons/dtool16/term_sbook.gif new file mode 100644 index 0000000..bf15460 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/term_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/dtool16/uncomment_edit.gif b/net.sourceforge.phpeclipse/icons/dtool16/uncomment_edit.gif new file mode 100644 index 0000000..dcad7bc Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/dtool16/uncomment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/add_exc.gif b/net.sourceforge.phpeclipse/icons/elcl16/add_exc.gif new file mode 100644 index 0000000..3eb5d12 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/add_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/alphab_sort_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/alphab_sort_co.gif new file mode 100644 index 0000000..9d38f6d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/alphab_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/class_obj.gif b/net.sourceforge.phpeclipse/icons/elcl16/class_obj.gif new file mode 100644 index 0000000..3a5283a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/class_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/clear_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/clear_co.gif new file mode 100644 index 0000000..6faf8d6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/clear_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/collapseall.gif b/net.sourceforge.phpeclipse/icons/elcl16/collapseall.gif new file mode 100644 index 0000000..3409b11 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/collapseall.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/default_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/default_co.gif new file mode 100644 index 0000000..d8e1506 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/default_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/definingtype_sort_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/definingtype_sort_co.gif new file mode 100644 index 0000000..3a308c5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/definingtype_sort_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/exc_catch.gif b/net.sourceforge.phpeclipse/icons/elcl16/exc_catch.gif new file mode 100644 index 0000000..3a63aae Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/exc_catch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/fields_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/fields_co.gif new file mode 100644 index 0000000..ac9f965 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/fields_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/filter_ps.gif b/net.sourceforge.phpeclipse/icons/elcl16/filter_ps.gif new file mode 100644 index 0000000..5372656 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/filter_ps.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/final_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/final_co.gif new file mode 100644 index 0000000..fdf0285 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/final_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/flatLayout.gif b/net.sourceforge.phpeclipse/icons/elcl16/flatLayout.gif new file mode 100644 index 0000000..9f9ca48 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/flatLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/gointo_toplevel_type.gif b/net.sourceforge.phpeclipse/icons/elcl16/gointo_toplevel_type.gif new file mode 100644 index 0000000..b920e33 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/gointo_toplevel_type.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/hexad_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/hexad_co.gif new file mode 100644 index 0000000..c046c42 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/hexad_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/hierarchicalLayout.gif b/net.sourceforge.phpeclipse/icons/elcl16/hierarchicalLayout.gif new file mode 100644 index 0000000..b50b2c3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/hierarchicalLayout.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/hierarchy_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/hierarchy_co.gif new file mode 100644 index 0000000..fdf4104 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/hierarchy_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/history_list.gif b/net.sourceforge.phpeclipse/icons/elcl16/history_list.gif new file mode 100644 index 0000000..fce22c1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/history_list.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/impl_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/impl_co.gif new file mode 100644 index 0000000..bfab85c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/impl_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/inher_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/inher_co.gif new file mode 100644 index 0000000..6b422e7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/inher_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/lock_close.gif b/net.sourceforge.phpeclipse/icons/elcl16/lock_close.gif new file mode 100644 index 0000000..d0dea1c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/lock_close.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/metharg_obj.gif b/net.sourceforge.phpeclipse/icons/elcl16/metharg_obj.gif new file mode 100644 index 0000000..e43f9ee Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/metharg_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/pack_empty_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/pack_empty_co.gif new file mode 100644 index 0000000..ad9d74b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/pack_empty_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/private_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/private_co.gif new file mode 100644 index 0000000..fb94c77 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/private_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/protected_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/protected_co.gif new file mode 100644 index 0000000..270bdac Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/protected_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/public_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/public_co.gif new file mode 100644 index 0000000..662f345 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/public_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/refresh_nav.gif b/net.sourceforge.phpeclipse/icons/elcl16/refresh_nav.gif new file mode 100644 index 0000000..919423d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/refresh_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/remove_exc.gif b/net.sourceforge.phpeclipse/icons/elcl16/remove_exc.gif new file mode 100644 index 0000000..310510e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/remove_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/removea_exc.gif b/net.sourceforge.phpeclipse/icons/elcl16/removea_exc.gif new file mode 100644 index 0000000..33908b1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/removea_exc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/search_sortmatch.gif b/net.sourceforge.phpeclipse/icons/elcl16/search_sortmatch.gif new file mode 100644 index 0000000..336c0ec Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/search_sortmatch.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/static_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/static_co.gif new file mode 100644 index 0000000..9330990 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/static_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/sub_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/sub_co.gif new file mode 100644 index 0000000..cd768de Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/sub_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/super_co.gif b/net.sourceforge.phpeclipse/icons/elcl16/super_co.gif new file mode 100644 index 0000000..4ea1f3c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/super_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/synced.gif b/net.sourceforge.phpeclipse/icons/elcl16/synced.gif new file mode 100644 index 0000000..ae5d548 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/synced.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/th_horizontal.gif b/net.sourceforge.phpeclipse/icons/elcl16/th_horizontal.gif new file mode 100644 index 0000000..a1b054f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/th_horizontal.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/th_showqualified.gif b/net.sourceforge.phpeclipse/icons/elcl16/th_showqualified.gif new file mode 100644 index 0000000..3aa2efa Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/th_showqualified.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/th_single.gif b/net.sourceforge.phpeclipse/icons/elcl16/th_single.gif new file mode 100644 index 0000000..d6f1cdf Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/th_single.gif differ diff --git a/net.sourceforge.phpeclipse/icons/elcl16/th_vertical.gif b/net.sourceforge.phpeclipse/icons/elcl16/th_vertical.gif new file mode 100644 index 0000000..1795443 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/elcl16/th_vertical.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/comment_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/comment_edit.gif new file mode 100644 index 0000000..ac4a4f3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/comment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/disp_sbook.gif b/net.sourceforge.phpeclipse/icons/etool16/disp_sbook.gif new file mode 100644 index 0000000..3bcafea Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/disp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/export_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/export_wiz.gif new file mode 100644 index 0000000..dc6292d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/export_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/exportjar_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/exportjar_wiz.gif new file mode 100644 index 0000000..a50e16b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/exportjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/format_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/format_edit.gif new file mode 100644 index 0000000..f247efc Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/format_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/import_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/import_wiz.gif new file mode 100644 index 0000000..74dc174 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/import_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/importjar_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/importjar_wiz.gif new file mode 100644 index 0000000..51fa044 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/importjar_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/insp_sbook.gif b/net.sourceforge.phpeclipse/icons/etool16/insp_sbook.gif new file mode 100644 index 0000000..bcd5f22 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/insp_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/java_app.gif b/net.sourceforge.phpeclipse/icons/etool16/java_app.gif new file mode 100644 index 0000000..09d704e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/java_app.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/java_attach.gif b/net.sourceforge.phpeclipse/icons/etool16/java_attach.gif new file mode 100644 index 0000000..ee81236 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/java_attach.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/java_workingset_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/java_workingset_wiz.gif new file mode 100644 index 0000000..af26e1e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/java_workingset_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/javadoc.gif b/net.sourceforge.phpeclipse/icons/etool16/javadoc.gif new file mode 100644 index 0000000..7d04c37 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/javadoc.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/jdoc_hover_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/jdoc_hover_edit.gif new file mode 100644 index 0000000..96420e3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/jdoc_hover_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newclass_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newclass_wiz.gif new file mode 100644 index 0000000..a34cb30 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newclass_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newfield_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newfield_wiz.gif new file mode 100644 index 0000000..2b2157a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newfield_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newint_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newint_wiz.gif new file mode 100644 index 0000000..00bc0d0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newint_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newjprj_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newjprj_wiz.gif new file mode 100644 index 0000000..1cf466b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newjprj_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newjworkingSet_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newjworkingSet_wiz.gif new file mode 100644 index 0000000..09d704e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newjworkingSet_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newpack_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newpack_wiz.gif new file mode 100644 index 0000000..bbe2eba Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newpack_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newpackfolder_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newpackfolder_wiz.gif new file mode 100644 index 0000000..daf9f59 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newpackfolder_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/newsbook_wiz.gif b/net.sourceforge.phpeclipse/icons/etool16/newsbook_wiz.gif new file mode 100644 index 0000000..4f371de Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/newsbook_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/next_error_nav.gif b/net.sourceforge.phpeclipse/icons/etool16/next_error_nav.gif new file mode 100644 index 0000000..6a8e019 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/next_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/opentype.gif b/net.sourceforge.phpeclipse/icons/etool16/opentype.gif new file mode 100644 index 0000000..c945ea9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/opentype.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/pack_sbook.gif b/net.sourceforge.phpeclipse/icons/etool16/pack_sbook.gif new file mode 100644 index 0000000..1211fcd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/pack_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/prev_error_nav.gif b/net.sourceforge.phpeclipse/icons/etool16/prev_error_nav.gif new file mode 100644 index 0000000..2cba4b1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/prev_error_nav.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/run_sbook.gif b/net.sourceforge.phpeclipse/icons/etool16/run_sbook.gif new file mode 100644 index 0000000..924a2cc Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/run_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/shift_l_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/shift_l_edit.gif new file mode 100644 index 0000000..fe7b311 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/shift_l_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/shift_r_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/shift_r_edit.gif new file mode 100644 index 0000000..e0f2a56 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/shift_r_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/term_sbook.gif b/net.sourceforge.phpeclipse/icons/etool16/term_sbook.gif new file mode 100644 index 0000000..37f8d22 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/term_sbook.gif differ diff --git a/net.sourceforge.phpeclipse/icons/etool16/uncomment_edit.gif b/net.sourceforge.phpeclipse/icons/etool16/uncomment_edit.gif new file mode 100644 index 0000000..7b3c966 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/etool16/uncomment_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/browse_persp.gif b/net.sourceforge.phpeclipse/icons/eview16/browse_persp.gif new file mode 100644 index 0000000..32ef186 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/browse_persp.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/class_hi.gif b/net.sourceforge.phpeclipse/icons/eview16/class_hi.gif new file mode 100644 index 0000000..481e5d0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/class_hi.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/hierch_persp.gif b/net.sourceforge.phpeclipse/icons/eview16/hierch_persp.gif new file mode 100644 index 0000000..6e01dc0 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/hierch_persp.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/jperspective.gif b/net.sourceforge.phpeclipse/icons/eview16/jperspective.gif new file mode 100644 index 0000000..1642d8c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/jperspective.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/members.gif b/net.sourceforge.phpeclipse/icons/eview16/members.gif new file mode 100644 index 0000000..8d09d00 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/members.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/package.gif b/net.sourceforge.phpeclipse/icons/eview16/package.gif new file mode 100644 index 0000000..1228d12 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/package.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/packages.gif b/net.sourceforge.phpeclipse/icons/eview16/packages.gif new file mode 100644 index 0000000..80fef75 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/packages.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/projects.gif b/net.sourceforge.phpeclipse/icons/eview16/projects.gif new file mode 100644 index 0000000..2357c93 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/projects.gif differ diff --git a/net.sourceforge.phpeclipse/icons/eview16/types.gif b/net.sourceforge.phpeclipse/icons/eview16/types.gif new file mode 100644 index 0000000..12b9e70 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/eview16/types.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/brkpi_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/brkpi_obj.gif new file mode 100644 index 0000000..afcf4b8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/brkpi_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/builtin_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/builtin_obj.gif new file mode 100644 index 0000000..190e86d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/builtin_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/change.gif b/net.sourceforge.phpeclipse/icons/obj16/change.gif new file mode 100644 index 0000000..5bef5e7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/change.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/class_default_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/class_default_obj.gif new file mode 100644 index 0000000..5f2a62e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/class_default_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/classf_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/classf_obj.gif new file mode 100644 index 0000000..cfb37c4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/classf_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/classfo_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/classfo_obj.gif new file mode 100644 index 0000000..9dc7490 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/classfo_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/clear.gif b/net.sourceforge.phpeclipse/icons/obj16/clear.gif new file mode 100644 index 0000000..5cdb88f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/clear.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/column_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/column_obj.gif new file mode 100644 index 0000000..1c1e2d4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/column_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/compare_field.gif b/net.sourceforge.phpeclipse/icons/obj16/compare_field.gif new file mode 100644 index 0000000..db8bb07 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/compare_field.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/compare_method.gif b/net.sourceforge.phpeclipse/icons/obj16/compare_method.gif new file mode 100644 index 0000000..502b835 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/compare_method.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/composite_change.gif b/net.sourceforge.phpeclipse/icons/obj16/composite_change.gif new file mode 100644 index 0000000..661a2cf Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/composite_change.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/correction_change.gif b/net.sourceforge.phpeclipse/icons/obj16/correction_change.gif new file mode 100644 index 0000000..09d776f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/correction_change.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/correction_delete_import.gif b/net.sourceforge.phpeclipse/icons/obj16/correction_delete_import.gif new file mode 100644 index 0000000..118f677 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/correction_delete_import.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/correction_move.gif b/net.sourceforge.phpeclipse/icons/obj16/correction_move.gif new file mode 100644 index 0000000..80b1146 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/correction_move.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/correction_rename.gif b/net.sourceforge.phpeclipse/icons/obj16/correction_rename.gif new file mode 100644 index 0000000..09d776f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/correction_rename.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/cp_order_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/cp_order_obj.gif new file mode 100644 index 0000000..98ec3b3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/cp_order_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/cu_change.gif b/net.sourceforge.phpeclipse/icons/obj16/cu_change.gif new file mode 100644 index 0000000..02fad7f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/cu_change.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/cu_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/cu_obj.gif new file mode 100644 index 0000000..aba55e9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/cu_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/define_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/define_obj.gif new file mode 100644 index 0000000..31a924f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/define_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/empty_logical_package_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/empty_logical_package_obj.gif new file mode 100644 index 0000000..d0f64fc Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/empty_logical_package_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/empty_pack_fldr_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/empty_pack_fldr_obj.gif new file mode 100644 index 0000000..adc730f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/empty_pack_fldr_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/empty_pack_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/empty_pack_obj.gif new file mode 100644 index 0000000..8067752 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/empty_pack_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/envvar_nonexist_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/envvar_nonexist_obj.gif new file mode 100644 index 0000000..19cf3f3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/envvar_nonexist_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/envvar_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/envvar_obj.gif new file mode 100644 index 0000000..d079ebb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/envvar_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/exclusion_filter_attrib.gif b/net.sourceforge.phpeclipse/icons/obj16/exclusion_filter_attrib.gif new file mode 100644 index 0000000..3d83fd6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/exclusion_filter_attrib.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/fatalerror_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/fatalerror_obj.gif new file mode 100644 index 0000000..d85b98b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/fatalerror_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/field_default_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/field_default_obj.gif new file mode 100644 index 0000000..51e02b3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/field_default_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/field_private_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/field_private_obj.gif new file mode 100644 index 0000000..0e29242 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/field_private_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/field_protected_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/field_protected_obj.gif new file mode 100644 index 0000000..222116b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/field_protected_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/field_public_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/field_public_obj.gif new file mode 100644 index 0000000..630b286 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/field_public_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/file_change.gif b/net.sourceforge.phpeclipse/icons/obj16/file_change.gif new file mode 100644 index 0000000..df822a9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/file_change.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/file_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/file_obj.gif new file mode 100644 index 0000000..6b86d07 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/file_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/fun_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/fun_obj.gif new file mode 100644 index 0000000..b512915 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/fun_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/html.gif b/net.sourceforge.phpeclipse/icons/obj16/html.gif new file mode 100644 index 0000000..35eccbe Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/html.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/html_tag_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/html_tag_obj.gif new file mode 100644 index 0000000..f10ccee Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/html_tag_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/htmledit.gif b/net.sourceforge.phpeclipse/icons/obj16/htmledit.gif new file mode 100644 index 0000000..5dae869 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/htmledit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/imp_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/imp_obj.gif new file mode 100644 index 0000000..dea2e92 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/imp_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif new file mode 100644 index 0000000..ea94702 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerclass_default_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerclass_default_obj.gif new file mode 100644 index 0000000..5f2a62e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerclass_default_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerclass_private_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerclass_private_obj.gif new file mode 100644 index 0000000..dfdcce1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerclass_private_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerclass_protected_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerclass_protected_obj.gif new file mode 100644 index 0000000..039d129 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerclass_protected_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerclass_public_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerclass_public_obj.gif new file mode 100644 index 0000000..15cfc6d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerclass_public_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerinterface_default_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_default_obj.gif new file mode 100644 index 0000000..6ce3038 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_default_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerinterface_private_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_private_obj.gif new file mode 100644 index 0000000..447c2b4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_private_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerinterface_protected_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_protected_obj.gif new file mode 100644 index 0000000..98b6c63 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_protected_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/innerinterface_public_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_public_obj.gif new file mode 100644 index 0000000..13c9570 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/innerinterface_public_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/int_default_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/int_default_obj.gif new file mode 100644 index 0000000..6ce3038 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/int_default_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/intf_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/intf_obj.gif new file mode 100644 index 0000000..85069e1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/intf_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_desc_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_desc_obj.gif new file mode 100644 index 0000000..0b99965 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_desc_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_l_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_l_obj.gif new file mode 100644 index 0000000..11e04e2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_l_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_lsrc_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_lsrc_obj.gif new file mode 100644 index 0000000..bb78fff Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_lsrc_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_nonexist_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_nonexist_obj.gif new file mode 100644 index 0000000..e56ec31 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_nonexist_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_obj.gif new file mode 100644 index 0000000..61f34f2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jar_src_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jar_src_obj.gif new file mode 100644 index 0000000..a515124 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jar_src_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/java_model_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/java_model_obj.gif new file mode 100644 index 0000000..7b2b633 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/java_model_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/javadoc_location_attrib.gif b/net.sourceforge.phpeclipse/icons/obj16/javadoc_location_attrib.gif new file mode 100644 index 0000000..2612d34 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/javadoc_location_attrib.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jcu_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jcu_obj.gif new file mode 100644 index 0000000..4cecec9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jcu_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jcu_resource_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jcu_resource_obj.gif new file mode 100644 index 0000000..819ec34 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jcu_resource_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jdoc_tag_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jdoc_tag_obj.gif new file mode 100644 index 0000000..4e343b9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jdoc_tag_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jexception_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jexception_obj.gif new file mode 100644 index 0000000..4522b44 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jexception_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jexceptiond_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jexceptiond_obj.gif new file mode 100644 index 0000000..0e981e3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jexceptiond_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jrtexception_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jrtexception_obj.gif new file mode 100644 index 0000000..9f5a027 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jrtexception_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jsbook_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jsbook_obj.gif new file mode 100644 index 0000000..a162c17 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jsbook_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jsbook_run_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jsbook_run_obj.gif new file mode 100644 index 0000000..5bbd272 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jsbook_run_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jsearch_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jsearch_obj.gif new file mode 100644 index 0000000..ee75bdb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jsearch_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/jworkingSet_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/jworkingSet_obj.gif new file mode 100644 index 0000000..e369ff8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/jworkingSet_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/library_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/library_obj.gif new file mode 100644 index 0000000..f966fc3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/library_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/localvariable_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/localvariable_obj.gif new file mode 100644 index 0000000..bf0a368 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/localvariable_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/logical_package_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/logical_package_obj.gif new file mode 100644 index 0000000..7656618 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/logical_package_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/methdef_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/methdef_obj.gif new file mode 100644 index 0000000..fde860a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/methdef_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/methpri_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/methpri_obj.gif new file mode 100644 index 0000000..96f464d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/methpri_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/methpro_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/methpro_obj.gif new file mode 100644 index 0000000..d524944 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/methpro_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/methpub_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/methpub_obj.gif new file mode 100644 index 0000000..b512915 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/methpub_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/never_translate.gif b/net.sourceforge.phpeclipse/icons/obj16/never_translate.gif new file mode 100644 index 0000000..d20d298 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/never_translate.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/nls_search_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/nls_search_obj.gif new file mode 100644 index 0000000..4d1bda1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/nls_search_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/occ_match.gif b/net.sourceforge.phpeclipse/icons/obj16/occ_match.gif new file mode 100644 index 0000000..6e8e08d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/occ_match.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/occ_read.gif b/net.sourceforge.phpeclipse/icons/obj16/occ_read.gif new file mode 100644 index 0000000..704e3c4 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/occ_read.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/occ_write.gif b/net.sourceforge.phpeclipse/icons/obj16/occ_write.gif new file mode 100644 index 0000000..b834948 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/occ_write.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/output_folder_attrib.gif b/net.sourceforge.phpeclipse/icons/obj16/output_folder_attrib.gif new file mode 100644 index 0000000..07b0883 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/output_folder_attrib.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/package_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/package_obj.gif new file mode 100644 index 0000000..64622ef Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/package_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/packagefolder_nonexist_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/packagefolder_nonexist_obj.gif new file mode 100644 index 0000000..db9749b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/packagefolder_nonexist_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/packagefolder_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/packagefolder_obj.gif new file mode 100644 index 0000000..387781b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/packagefolder_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/packd_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/packd_obj.gif new file mode 100644 index 0000000..3aa2efa Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/packd_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/php.gif b/net.sourceforge.phpeclipse/icons/obj16/php.gif new file mode 100644 index 0000000..3694fbe Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/php.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/php.png b/net.sourceforge.phpeclipse/icons/obj16/php.png new file mode 100644 index 0000000..d56545c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/php.png differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/phpedit.gif b/net.sourceforge.phpeclipse/icons/obj16/phpedit.gif new file mode 100644 index 0000000..ad9c49e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/phpedit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/phpedit.png b/net.sourceforge.phpeclipse/icons/obj16/phpedit.png new file mode 100644 index 0000000..a129420 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/phpedit.png differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/phpedit2.gif b/net.sourceforge.phpeclipse/icons/obj16/phpedit2.gif new file mode 100644 index 0000000..50558f2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/phpedit2.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/prjct_nonexist_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/prjct_nonexist_obj.gif new file mode 100644 index 0000000..5fce4d6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/prjct_nonexist_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/profield_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/profield_obj.gif new file mode 100644 index 0000000..3932f61 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/profield_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/pubfield_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/pubfield_obj.gif new file mode 100644 index 0000000..e5fd09b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/pubfield_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/quickfix_error_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/quickfix_error_obj.gif new file mode 100644 index 0000000..d6427e8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/quickfix_error_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/quickfix_warning_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/quickfix_warning_obj.gif new file mode 100644 index 0000000..b34d85f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/quickfix_warning_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/search_decl_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/search_decl_obj.gif new file mode 100644 index 0000000..3eddefd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/search_decl_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/search_ref_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/search_ref_obj.gif new file mode 100644 index 0000000..1b0c43b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/search_ref_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/searchm_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/searchm_obj.gif new file mode 100644 index 0000000..7b1efa5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/searchm_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/skip.gif b/net.sourceforge.phpeclipse/icons/obj16/skip.gif new file mode 100644 index 0000000..5d50ae2 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/skip.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/source_attach_attrib.gif b/net.sourceforge.phpeclipse/icons/obj16/source_attach_attrib.gif new file mode 100644 index 0000000..3976f8f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/source_attach_attrib.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/table_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/table_obj.gif new file mode 100644 index 0000000..f4056f6 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/table_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/template_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/template_obj.gif new file mode 100644 index 0000000..65c2632 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/template_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/text_edit.gif b/net.sourceforge.phpeclipse/icons/obj16/text_edit.gif new file mode 100644 index 0000000..c639f65 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/text_edit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/translate.gif b/net.sourceforge.phpeclipse/icons/obj16/translate.gif new file mode 100644 index 0000000..00da14e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/translate.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/unknown_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/unknown_obj.gif new file mode 100644 index 0000000..c0058f7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/unknown_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/var_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/var_obj.gif new file mode 100644 index 0000000..0104955 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/var_obj.gif differ diff --git a/net.sourceforge.phpeclipse/icons/obj16/xmledit.gif b/net.sourceforge.phpeclipse/icons/obj16/xmledit.gif new file mode 100644 index 0000000..c5d5e95 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/obj16/xmledit.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/abstract_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/abstract_co.gif new file mode 100644 index 0000000..3e8c061 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/abstract_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/constr_ovr.gif b/net.sourceforge.phpeclipse/icons/ovr16/constr_ovr.gif new file mode 100644 index 0000000..3bfa12b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/constr_ovr.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/error_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/error_co.gif new file mode 100644 index 0000000..8612eaf Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/error_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/final_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/final_co.gif new file mode 100644 index 0000000..d734b3d Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/final_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/focus_ovr.gif b/net.sourceforge.phpeclipse/icons/ovr16/focus_ovr.gif new file mode 100644 index 0000000..e96d53b Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/focus_ovr.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/implm_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/implm_co.gif new file mode 100644 index 0000000..16c78d7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/implm_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/java_ovr.gif b/net.sourceforge.phpeclipse/icons/ovr16/java_ovr.gif new file mode 100644 index 0000000..3d1362f Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/java_ovr.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/native_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/native_co.gif new file mode 100644 index 0000000..77613cd Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/native_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/over_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/over_co.gif new file mode 100644 index 0000000..c5f5d95 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/over_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/php_ovr.gif b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr.gif new file mode 100644 index 0000000..8f25ef8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/php_ovr2.gif b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr2.gif new file mode 100644 index 0000000..ffa7c3c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr2.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/php_ovr3.gif b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr3.gif new file mode 100644 index 0000000..956d33a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/php_ovr3.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/run_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/run_co.gif new file mode 100644 index 0000000..e179837 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/run_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/static_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/static_co.gif new file mode 100644 index 0000000..08438a5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/static_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/synch_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/synch_co.gif new file mode 100644 index 0000000..ff0ddb8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/synch_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/typeinfocus_underlay.gif b/net.sourceforge.phpeclipse/icons/ovr16/typeinfocus_underlay.gif new file mode 100644 index 0000000..ec7807c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/typeinfocus_underlay.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/volatile_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/volatile_co.gif new file mode 100644 index 0000000..8ddf0be Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/volatile_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/ovr16/warning_co.gif b/net.sourceforge.phpeclipse/icons/ovr16/warning_co.gif new file mode 100644 index 0000000..3af228c Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/ovr16/warning_co.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/addlibrary_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/addlibrary_wiz.gif new file mode 100644 index 0000000..e0eea42 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/addlibrary_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/coderefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/coderefact_wiz.gif new file mode 100644 index 0000000..10e80d9 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/coderefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/compunitrefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/compunitrefact_wiz.gif new file mode 100644 index 0000000..310ee8a Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/compunitrefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif new file mode 100644 index 0000000..2ab1adb Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/editelem_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/export_javadoc_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/export_javadoc_wiz.gif new file mode 100644 index 0000000..62aa7ba Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/export_javadoc_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/extstr_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/extstr_wiz.gif new file mode 100644 index 0000000..111b284 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/extstr_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/fieldrefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/fieldrefact_wiz.gif new file mode 100644 index 0000000..2e0d346 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/fieldrefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/jar_pack_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/jar_pack_wiz.gif new file mode 100644 index 0000000..0de3582 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/jar_pack_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/java_app_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/java_app_wiz.gif new file mode 100644 index 0000000..8d425d5 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/java_app_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/java_attach_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/java_attach_wiz.gif new file mode 100644 index 0000000..544efda Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/java_attach_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/java_workingset_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/java_workingset_wiz.gif new file mode 100644 index 0000000..31c69f8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/java_workingset_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/methrefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/methrefact_wiz.gif new file mode 100644 index 0000000..3ea2af7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/methrefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newfield_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newfield_wiz.gif new file mode 100644 index 0000000..478cfe3 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newfield_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newint_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newint_wiz.gif new file mode 100644 index 0000000..385d0b8 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newint_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newjprj_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newjprj_wiz.gif new file mode 100644 index 0000000..3172ab1 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newjprj_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newmeth_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newmeth_wiz.gif new file mode 100644 index 0000000..a17c735 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newmeth_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newpack_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newpack_wiz.gif new file mode 100644 index 0000000..ba81b8e Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newpack_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newsbook_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newsbook_wiz.gif new file mode 100644 index 0000000..ba31651 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newsbook_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/newsrcfldr_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/newsrcfldr_wiz.gif new file mode 100644 index 0000000..4b1ad56 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/newsrcfldr_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/packrefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/packrefact_wiz.gif new file mode 100644 index 0000000..72b4eff Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/packrefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/pullup_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/pullup_wiz.gif new file mode 100644 index 0000000..0ae1083 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/pullup_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/refactor_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/refactor_wiz.gif new file mode 100644 index 0000000..af125c7 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/refactor_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/icons/wizban/typerefact_wiz.gif b/net.sourceforge.phpeclipse/icons/wizban/typerefact_wiz.gif new file mode 100644 index 0000000..90e2d45 Binary files /dev/null and b/net.sourceforge.phpeclipse/icons/wizban/typerefact_wiz.gif differ diff --git a/net.sourceforge.phpeclipse/plugin.properties b/net.sourceforge.phpeclipse/plugin.properties index e9f17d5..0a78bab 100644 --- a/net.sourceforge.phpeclipse/plugin.properties +++ b/net.sourceforge.phpeclipse/plugin.properties @@ -16,16 +16,36 @@ phpEditorTextHoversName=PHP Editor Text Hovers perspectiveHTML.name=HTML viewPHPResources.name=PHP Resources +newWizardCategory.name=PHP +newWizardPHPProject.name=PHP Project +newWizardPHPFile.name=PHP File +newWizardHTMLFile.name=HTML file NewPHPClass.label= Class NewPHPClass.description=Create a PHP class +OpenActionSet.label=Open Declaration/Include OpenActionSet.description=Open a PHP Declaration or Include +OpenDeclaration=Open Declaration/Include +ExportWizards.Obfuscator = Obfuscate PHP Project to File system +ExportWizards.ObfuscatorDescription = Obfuscate PHP resources to the local file system propertyPagePHPProject.name=PHP Project Properties +compilerPageName=PHP Parser +todoPageName=PHP Task Tags + +compilerOptionsPrefName= PHP Parser +todoTaskPrefName= Task Tags +templatePageName= Templates +spellingPrefName= Spelling +codeAssistPageName= Code Assist +editorPageName= Editor +editorMarkOccurrencesPage= Mark Occurrences + # # Extension point names # +phpEditorName=PHP Editor phpConsoleView=PHP Console phpFileExtension=php php3FileExtension=php3 @@ -39,6 +59,13 @@ htmFileExtension=htm xmlFileExtension=xml tplFileExtension=tpl +javaDocumentFactory=PHP Document Factory +javaDocumentSetupParticipant=PHP Document Setup Participant + +sourceHover= Source +sourceHoverDescription= Shows the source of the selected element. +javadocHover= PHPdoc +javadocHoverDescription= Shows the PHPdoc of the selected element. sequentialHover= Best Match sequentialHoverDescription= Shows the hover which fits best for the selected element and the current context. annotationHover= Annotation @@ -135,6 +162,12 @@ problemHoverDescription= Shows the description of the selected problem. # Action Definitions ########################################################################## +category.source.name=PHP Source +category.source.description= PHP Source Actions + +context.editingPHPSource.name= Editing PHP Source +context.editingPHPSource.description= Editing PHP Source Context + scope.javaEditor.name=PHP Editor ########################################################################## diff --git a/net.sourceforge.phpeclipse/plugin.xml b/net.sourceforge.phpeclipse/plugin.xml index 9a2e5b5..419b36c 100644 --- a/net.sourceforge.phpeclipse/plugin.xml +++ b/net.sourceforge.phpeclipse/plugin.xml @@ -58,6 +58,46 @@ + + + + %ProblemsLabelDecorator.description + + + + + + + + + + + + + %OverrideIndicatorLabelDecorator.description + + + + + + + @@ -82,6 +122,746 @@ file-extensions="php,phpc,php3,php4,php5,phtml,inc,module,phpt,ctp"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + Create a new PHP project. + + + + + + Create a basic PHP file. + + + + + Create a basic HTML file. + + + + + + %ExportWizards.ObfuscatorDescription + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + %phpEditorFontDefintion.description + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -90,4 +870,284 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java index 45b0f41..e7ec0d5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaConventions.java @@ -14,6 +14,7 @@ package net.sourceforge.phpdt.core; //import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; //import net.sourceforge.phpdt.internal.core.ClasspathEntry; @@ -94,16 +95,16 @@ public final class JavaConventions { } try { SCANNER.setSource(id.toCharArray()); - int token = SCANNER.getNextToken(); + TokenName token = SCANNER.getNextToken(); char[] currentIdentifier; try { currentIdentifier = SCANNER.getCurrentIdentifierSource(); } catch (ArrayIndexOutOfBoundsException e) { return null; } - int nextToken = SCANNER.getNextToken(); - if (token == ITerminalSymbols.TokenNameIdentifier - && nextToken == ITerminalSymbols.TokenNameEOF + TokenName nextToken = SCANNER.getNextToken(); + if (token == ITerminalSymbols.TokenName.IDENTIFIER + && nextToken == ITerminalSymbols.TokenName.EOF && SCANNER.startPosition == SCANNER.source.length) { // to // handle // case diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java index f3c6ff6..b06f048 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IScanner.java @@ -11,6 +11,8 @@ package net.sourceforge.phpdt.core.compiler; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; + /** * Definition of a Java scanner, as returned by the ToolFactory. * The scanner is responsible for tokenizing a given source, providing @@ -123,7 +125,7 @@ public interface IScanner { * in case a lexical error was detected while reading the * current token */ - int getNextToken() throws InvalidInputException; + TokenName getNextToken() throws InvalidInputException; /** * Answers the original source being processed (not a copy of it). diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java index ae1db34..117ee33 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java @@ -13,346 +13,177 @@ package net.sourceforge.phpdt.core.compiler; /** * Maps each terminal symbol in the php-grammar into a unique integer. This * integer is used to represent the terminal when computing a parsing action. - * + * * @see IScanner * @since 2.0 */ + public interface ITerminalSymbols { public final static String[] PHP_TYPES = { "array", "string", "object", "bool", "boolean", "real", "double", "float", "int", "integer", }; - // "array", - public final static int TokenNameWHITESPACE = 900, - TokenNameCOMMENT_LINE = 901, TokenNameCOMMENT_BLOCK = 902, - TokenNameCOMMENT_PHPDOC = 903; - - // TokenNameHTML = 904; - final static int TokenNameEOF = 0; - - final static int TokenNameERROR = 1; - - final static int TokenNameINLINE_HTML = 2; - - final static int TokenNameREMAINDER = 30; - - final static int TokenNameNOT = 31; - - final static int TokenNameDOT = 32; - - final static int TokenNameXOR = 33; - - final static int TokenNameDIVIDE = 34; - - final static int TokenNameMULTIPLY = 35; - - final static int TokenNameMINUS = 36; - - final static int TokenNamePLUS = 37; - - final static int TokenNameEQUAL_EQUAL = 38; - - final static int TokenNameNOT_EQUAL = 39; - - final static int TokenNameGREATER = 40; - - final static int TokenNameGREATER_EQUAL = 41; - - final static int TokenNameLESS = 42; - - final static int TokenNameLESS_EQUAL = 43; - - final static int TokenNameAND_AND = 44; - - final static int TokenNameOR_OR = 45; - - final static int TokenNameCOLON = 47; - - final static int TokenNameDOT_EQUAL = 48; - - final static int TokenNameEQUAL = 49; - - final static int TokenNameMINUS_GREATER = 50; // -> - - final static int TokenNameEQUAL_GREATER = 51; // => (for each operator) - - final static int TokenNameAND = 52; - - final static int TokenNameTWIDDLE = 54; - - final static int TokenNameTWIDDLE_EQUAL = 55; - - final static int TokenNameREMAINDER_EQUAL = 56; - - final static int TokenNameXOR_EQUAL = 57; - - final static int TokenNameRIGHT_SHIFT_EQUAL = 58; - - final static int TokenNameLEFT_SHIFT_EQUAL = 59; - - final static int TokenNameAND_EQUAL = 60; - - final static int TokenNameOR_EQUAL = 61; - - final static int TokenNameQUESTION = 62; - - final static int TokenNamePAAMAYIM_NEKUDOTAYIM = 63; - - final static int TokenNameAT = 64; - - final static int TokenNameand = 65; - - final static int TokenNameor = 66; - - final static int TokenNamexor = 67; - - final static int TokenNameDOLLAR = 126; - - final static int TokenNameDOLLAR_LBRACE = 127; - - final static int TokenNameLPAREN = 128; - - final static int TokenNameRPAREN = 129; - - final static int TokenNameLBRACE = 130; - - final static int TokenNameRBRACE = 131; - - final static int TokenNameLBRACKET = 132; - - final static int TokenNameRBRACKET = 133; - - final static int TokenNameCOMMA = 134; - - final static int TokenNameStringDoubleQuote = 136; - - final static int TokenNameIdentifier = 138; - - final static int TokenNameSEMICOLON = 140; - - final static int TokenNameMINUS_MINUS = 144; - - final static int TokenNamePLUS_PLUS = 145; - - final static int TokenNamePLUS_EQUAL = 146; - - final static int TokenNameDIVIDE_EQUAL = 147; - - final static int TokenNameMINUS_EQUAL = 148; - - final static int TokenNameMULTIPLY_EQUAL = 149; - - final static int TokenNameVariable = 150; - - final static int TokenNameIntegerLiteral = 151; - - final static int TokenNameDoubleLiteral = 152; - - final static int TokenNameStringInterpolated = 153; - - final static int TokenNameStringSingleQuote = 154; - - final static int TokenNameLEFT_SHIFT = 155; - - final static int TokenNameRIGHT_SHIFT = 156; - - final static int TokenNameEQUAL_EQUAL_EQUAL = 157; - - final static int TokenNameNOT_EQUAL_EQUAL = 158; - - final static int TokenNameOR = 160; - - final static int TokenNameHEREDOC = 161; - - final static int TokenNameintCAST = 174; - - final static int TokenNameboolCAST = 175; - - final static int TokenNamedoubleCAST = 176; - - final static int TokenNamestringCAST = 177; - - final static int TokenNamearrayCAST = 178; - - final static int TokenNameobjectCAST = 179; - - final static int TokenNameunsetCAST = 180; - - // � - final static int TokenNameEncapsedString0 = 190; - - // ' - // final static int TokenNameEncapsedString1 = 191; - // " - // final static int TokenNameEncapsedString2 = 192; - - final static int TokenNameSTRING = 193; - - final static int TokenNameLBRACE_DOLLAR = 194; - - // start SQL token - the SQL tokens are only used in the - // PHPCompletionprocessor: - public final static int TokenNameSQLselect = 901; - - public final static int TokenNameSQLupdate = 902; - - public final static int TokenNameSQLinsert = 903; - - public final static int TokenNameSQLwhere = 904; - - public final static int TokenNameSQLfrom = 905; - - public final static int TokenNameSQLinto = 906; - - public final static int TokenNameSQLset = 907; - - public final static int TokenNameSQLvalues = 908; - - // stop SQL token - - /** - * Special 0-length token for php short tag syntax; Detected directly after - * <?= - */ - public final static int TokenNameECHO_INVISIBLE = 990; - - public final static int TokenNameKEYWORD = 1000; - - public final static int TokenNameif = 1001; - - public final static int TokenNameelseif = 1002; - - public final static int TokenNameelse = 1003; - - public final static int TokenNameendif = 1004; - - public final static int TokenNamefor = 1005; - - public final static int TokenNameendfor = 1006; - - public final static int TokenNamewhile = 1007; - - public final static int TokenNameendwhile = 1008; - - public final static int TokenNameswitch = 1009; - - public final static int TokenNamecase = 10010; - - public final static int TokenNameendswitch = 1011; - - public final static int TokenNamebreak = 1012; - - public final static int TokenNamecontinue = 1013; - - public final static int TokenNamereturn = 1014; - - // public final static int TokenNamedefine = 1015; - public final static int TokenNameinclude = 1016; - - public final static int TokenNameinclude_once = 1017; - - public final static int TokenNamerequire = 1018; - - public final static int TokenNamerequire_once = 1019; - - public final static int TokenNamefunction = 1020; - - public final static int TokenNameclass = 1021; - - public final static int TokenNamenew = 1022; - - public final static int TokenNamedo = 1023; - - public final static int TokenNameold_function = 1024; - - public final static int TokenNamedefault = 1025; - - public final static int TokenNameglobal = 1026; - - public final static int TokenNamestatic = 1027; - - public final static int TokenNameforeach = 1028; - - public final static int TokenNameendforeach = 1029; - - public final static int TokenNameextends = 1030; - - public final static int TokenNameempty = 1031; - - public final static int TokenNamearray = 1032; - - public final static int TokenNameecho = 1033; - - public final static int TokenNamevar = 1034; - - public final static int TokenNameas = 1035; - - public final static int TokenNameprint = 1036; - - public final static int TokenNameunset = 1037; - - public final static int TokenNameexit = 1038; - - // public final static int TokenNamedie = 1039; - // public final static int TokenNameand = 1040; - // public final static int TokenNameor = 1041; - // public final static int TokenNamexor = 1042; - public final static int TokenNamelist = 1043; - - // public final static int TokenNamenull = 1044; - // public final static int TokenNamefalse = 1045; - // public final static int TokenNametrue = 1046; - // public final static int TokenNamethis = 1047; - // - public final static int TokenNameabstract = 1050; - - public final static int TokenNamecatch = 1051; - - public final static int TokenNamefinally = 1052; - - public final static int TokenNametry = 1053; - - public final static int TokenNameprivate = 1054; - - public final static int TokenNameprotected = 1055; - - public final static int TokenNamepublic = 1056; - - public final static int TokenNameinterface = 1057; - - public final static int TokenNameimplements = 1058; - - public final static int TokenNameinstanceof = 1059; - - public final static int TokenNamesuper = 1060; - - public final static int TokenNamethrow = 1061; - - public final static int TokenNameconst = 1062; - - public final static int TokenNameclone = 1063; - - public final static int TokenNamedeclare = 1064; - - public final static int TokenNameenddeclare = 1065; - - public final static int TokenNameeval = 1066; - - public final static int TokenNameuse = 1067; - - public final static int TokenNameisset = 1068; - - public final static int TokenNamefinal = 1069; - - public final static int TokenNameLINE = 1070; - - public final static int TokenNameFILE = 1071; - - public final static int TokenNameCLASS_C = 1072; - - public final static int TokenNameMETHOD_C = 1073; - - public final static int TokenNameFUNC_C = 1074; - - // special tokens not normally used in the parser - public final static int TokenNamethis_PHP_COMPLETION = 2000; + public enum TokenName { + NONE_INDENT_BLOCK, + NONE, // Pseudo token name; means no token yet available + EOF, + WHITESPACE, + COMMENT_LINE, + COMMENT_BLOCK, + COMMENT_PHPDOC, + // HTML = 904, + ERROR, + INLINE_HTML, + REMAINDER, + NOT, + DOT, + DIVIDE, + MULTIPLY, + MINUS, + PLUS, + OP_AT, + OP_AND_OLD, + OP_OR_OLD, + OP_XOR_OLD, + OP_XOR, + OP_AND, + OP_OR, + AND_AND, + OR_OR, + EQUAL_EQUAL, + NOT_EQUAL, + GREATER, + GREATER_EQUAL, + LESS, + LESS_EQUAL, + COLON, + DOT_EQUAL, + EQUAL, + MINUS_GREATER, + EQUAL_GREATER, + TWIDDLE, + TWIDDLE_EQUAL, + REMAINDER_EQUAL, + RIGHT_SHIFT_EQUAL, + LEFT_SHIFT_EQUAL, + XOR_EQUAL, + AND_EQUAL, + OR_EQUAL, + QUESTION, + PAAMAYIM_NEKUDOTAYIM, + DOLLAR, + DOLLAR_LBRACE, + LPAREN, + RPAREN, + LBRACE, + RBRACE, + LBRACKET, + RBRACKET, + COMMA, + BACKSLASH, + STRINGDOUBLEQUOTE, + IDENTIFIER, + SEMICOLON, + MINUS_MINUS, + PLUS_PLUS, + PLUS_EQUAL, + DIVIDE_EQUAL, + MINUS_EQUAL, + MULTIPLY_EQUAL, + VARIABLE, + INTEGERLITERAL, + DOUBLELITERAL, + STRINGINTERPOLATED, + STRINGSINGLEQUOTE, + LEFT_SHIFT, + RIGHT_SHIFT, + EQUAL_EQUAL_EQUAL, + NOT_EQUAL_EQUAL, + HEREDOC, + INTCAST, + BOOLCAST, + DOUBLECAST, + STRINGCAST, + ARRAYCAST, + OBJECTCAST, + UNSETCAST, + ENCAPSEDSTRING0, + STRING, + LBRACE_DOLLAR, + SQLSELECT, + SQLUPDATE, + SQLINSERT, + SQLWHERE, + SQLFROM, + SQLINTO, + SQLSET, + SQLVALUES, + ECHO_INVISIBLE, + KEYWORD, // Here the PHP keywords start + ABSTRACT, + ARRAY, + AS, + BREAK, + CASE, + CATCH, + CLASS, + CLASS_C, + CLONE, + CONST, + CONTINUE, + DECLARE, + DEFAULT, + DO, + ECHO, + ELSE, + ELSEIF, + EMPTY, + ENDDECLARE, + ENDFOR, + ENDFOREACH, + ENDIF, + ENDSWITCH, + ENDWHILE, + EVAL, + EXIT, + EXTENDS, + FILE, + FINAL, + FINALLY, + FOR, + FOREACH, + FUNCTION, + FUNC_C, + GLOBAL, + GOTO, + IF, + IMPLEMENTS, + INCLUDE, + INCLUDE_ONCE, + INSTANCEOF, + INTERFACE, + ISSET, + LINE, + LIST, + METHOD_C, + NAMESPACE, + NEW, + OLD_FUNCTION, + PRINT, + PRIVATE, + PROTECTED, + PUBLIC, + REQUIRE, + REQUIRE_ONCE, + RETURN, + STATIC, + SUPER, + SWITCH, + THROW, + TRY, + UNSET, + USE, + VAR, + WHILE, + THIS_PHP_COMPLETION; // special tokens not normally used in the parser + }; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java index 4efd729..f4dfc69 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/AND_AND_Expression.java @@ -10,6 +10,7 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.flow.FlowContext; import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java index 8a264bc..4f8e580 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/BinaryExpression.java @@ -10,6 +10,7 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.flow.FlowContext; import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; @@ -25,7 +26,6 @@ public class BinaryExpression extends OperatorExpression { public Constant optimizedBooleanConstant; public BinaryExpression(Expression left, Expression right, int operator) { - this.left = left; this.right = right; this.bits |= operator << OperatorSHIFT; // encode operator diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java index df31b10..477ee09 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/Block.java @@ -17,13 +17,11 @@ import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; public class Block extends Statement { - - public Statement[] statements; + public Statement[] statements; // The array of statements found with this block public int explicitDeclarations; - // the number of explicit declaration , used to create scope - public BlockScope scope; + public BlockScope scope; // The number of explicit declaration , used to create scope public static final Block None = new Block(0); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java index 7109c76..be26c14 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/EqualExpression.java @@ -10,6 +10,7 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.flow.FlowContext; import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; @@ -24,7 +25,7 @@ import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; public class EqualExpression extends BinaryExpression { public EqualExpression(Expression left, Expression right, int operator) { - super(left, right, operator); + super (left, right, operator); } public FlowInfo analyseCode(BlockScope currentScope, diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java index 9dee180..d498ca5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/ast/OR_OR_Expression.java @@ -10,6 +10,7 @@ *******************************************************************************/ package net.sourceforge.phpdt.internal.compiler.ast; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.internal.compiler.ASTVisitor; import net.sourceforge.phpdt.internal.compiler.flow.FlowContext; import net.sourceforge.phpdt.internal.compiler.flow.FlowInfo; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java index 08636d5..0bf383c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/AbstractCommentParser.java @@ -15,6 +15,7 @@ import java.util.List; import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; /** @@ -87,7 +88,7 @@ public abstract class AbstractCommentParser { protected int[] lineEnds; // Private fields - private int currentTokenType = -1; + private TokenName currentTokenType = ITerminalSymbols.TokenName.NONE; // Line pointers private int linePtr, lastLinePtr; @@ -151,7 +152,7 @@ public abstract class AbstractCommentParser { // Init local variables this.astLengthPtr = -1; this.astPtr = -1; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; this.inlineTagStarted = false; this.inlineTagStart = -1; this.lineStarted = false; @@ -179,16 +180,16 @@ public abstract class AbstractCommentParser { } // Read next char only if token was consumed - if (this.currentTokenType < 0) { + if (this.currentTokenType.compareTo (ITerminalSymbols.TokenName.NONE) <= 0) { nextCharacter = readChar(); // consider unicodes } else { previousPosition = this.scanner .getCurrentTokenStartPosition(); switch (this.currentTokenType) { - case ITerminalSymbols.TokenNameRBRACE: + case RBRACE: nextCharacter = '}'; break; - case ITerminalSymbols.TokenNameMULTIPLY: + case MULTIPLY: nextCharacter = '*'; break; default: @@ -241,10 +242,10 @@ public abstract class AbstractCommentParser { pushText(this.textStart, invalidTagLineEnd); } this.scanner.resetTo(this.index, this.endComment); - this.currentTokenType = -1; // flush token cache at line + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // flush token cache at line // begin try { - int token = readTokenAndConsume(); + TokenName token = readTokenAndConsume(); this.tagSourceStart = this.scanner .getCurrentTokenStartPosition(); this.tagSourceEnd = this.scanner @@ -261,10 +262,10 @@ public abstract class AbstractCommentParser { // than java identifier // (see bug // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660) - int tk = token; + TokenName tk = token; int le = this.lineEnd; char pc = peekChar(); - tagNameToken: while (tk != ITerminalSymbols.TokenNameEOF) { + tagNameToken: while (tk != ITerminalSymbols.TokenName.EOF) { this.tagSourceEnd = this.scanner .getCurrentTokenEndPosition(); token = tk; @@ -306,7 +307,7 @@ public abstract class AbstractCommentParser { this.lineEnd = le; } switch (token) { - case ITerminalSymbols.TokenNameIdentifier: + case IDENTIFIER: if (CharOperation.equals(tag, TAG_DEPRECATED)) { this.deprecated = true; if (this.kind == DOM_PARSER) { @@ -381,7 +382,7 @@ public abstract class AbstractCommentParser { valid = parseTag(); } break; - case ITerminalSymbols.TokenNamereturn: + case RETURN: valid = parseReturn(); // verify characters after return tag (we're // expecting text description) @@ -397,70 +398,70 @@ public abstract class AbstractCommentParser { } } break; - // case ITerminalSymbols.TokenNamethrows : + // case ITerminalSymbols.TokenName.throws : // valid = parseThrows(true); // break; default: if (this.kind == DOM_PARSER) { switch (token) { - case ITerminalSymbols.TokenNameabstract: + case ABSTRACT: // case - // ITerminalSymbols.TokenNameassert: + // ITerminalSymbols.TokenName.assert: // case - // ITerminalSymbols.TokenNameboolean: - case ITerminalSymbols.TokenNamebreak: - // case ITerminalSymbols.TokenNamebyte: - case ITerminalSymbols.TokenNamecase: - case ITerminalSymbols.TokenNamecatch: - // case ITerminalSymbols.TokenNamechar: - case ITerminalSymbols.TokenNameclass: - case ITerminalSymbols.TokenNamecontinue: - case ITerminalSymbols.TokenNamedefault: - case ITerminalSymbols.TokenNamedo: + // ITerminalSymbols.TokenName.boolean: + case BREAK: + // case byte: + case CASE: + case CATCH: + // case char: + case CLASS: + case CONTINUE: + case DEFAULT: + case DO: // case - // ITerminalSymbols.TokenNamedouble: - case ITerminalSymbols.TokenNameelse: - case ITerminalSymbols.TokenNameextends: - // case ITerminalSymbols.TokenNamefalse: - case ITerminalSymbols.TokenNamefinal: - case ITerminalSymbols.TokenNamefinally: - // case ITerminalSymbols.TokenNamefloat: - case ITerminalSymbols.TokenNamefor: - case ITerminalSymbols.TokenNameif: - case ITerminalSymbols.TokenNameimplements: + // double: + case ELSE: + case EXTENDS: + // case false: + case FINAL: + case FINALLY: + // case float: + case FOR: + case IF: + case IMPLEMENTS: // case - // ITerminalSymbols.TokenNameimport: - case ITerminalSymbols.TokenNameinstanceof: - // case ITerminalSymbols.TokenNameint: - case ITerminalSymbols.TokenNameinterface: - // case ITerminalSymbols.TokenNamelong: + // import: + case INSTANCEOF: + // case int: + case INTERFACE: + // case long: // case - // ITerminalSymbols.TokenNamenative: - case ITerminalSymbols.TokenNamenew: - // case ITerminalSymbols.TokenNamenull: + // native: + case NEW: + // case null: // case - // ITerminalSymbols.TokenNamepackage: - case ITerminalSymbols.TokenNameprivate: - case ITerminalSymbols.TokenNameprotected: - case ITerminalSymbols.TokenNamepublic: - // case ITerminalSymbols.TokenNameshort: - case ITerminalSymbols.TokenNamestatic: + // package: + case PRIVATE: + case PROTECTED: + case PUBLIC: + // case short: + case STATIC: // case - // ITerminalSymbols.TokenNamestrictfp: - case ITerminalSymbols.TokenNamesuper: - case ITerminalSymbols.TokenNameswitch: + // strictfp: + case SUPER: + case SWITCH: // case - // ITerminalSymbols.TokenNamesynchronized: - // case ITerminalSymbols.TokenNamethis: - case ITerminalSymbols.TokenNamethrow: + // synchronized: + // case this: + case THROW: // case - // ITerminalSymbols.TokenNametransient: - // case ITerminalSymbols.TokenNametrue: - case ITerminalSymbols.TokenNametry: - // case ITerminalSymbols.TokenNamevoid: + // transient: + // case true: + case TRY: + // case void: // case - // ITerminalSymbols.TokenNamevolatile: - case ITerminalSymbols.TokenNamewhile: + // volatile: + case WHILE: valid = parseTag(); break; } @@ -585,7 +586,7 @@ public abstract class AbstractCommentParser { } private void consumeToken() { - this.currentTokenType = -1; // flush token cache + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // flush token cache updateLineEnd(); } @@ -699,7 +700,7 @@ public abstract class AbstractCommentParser { } if (typeRef == null) { if (firstArg - && this.currentTokenType == ITerminalSymbols.TokenNameRPAREN) { + && this.currentTokenType == ITerminalSymbols.TokenName.RPAREN) { // verify characters after arguments declaration (expecting // white space or end comment) if (!verifySpaceOrEndComment()) { @@ -723,11 +724,11 @@ public abstract class AbstractCommentParser { int dim = 0; long[] dimPositions = new long[20]; // assume that there won't be // more than 20 dimensions... - if (readToken() == ITerminalSymbols.TokenNameLBRACKET) { + if (readToken() == ITerminalSymbols.TokenName.LBRACKET) { int dimStart = this.scanner.getCurrentTokenStartPosition(); - while (readToken() == ITerminalSymbols.TokenNameLBRACKET) { + while (readToken() == ITerminalSymbols.TokenName.LBRACKET) { consumeToken(); - if (readToken() != ITerminalSymbols.TokenNameRBRACKET) { + if (readToken() != ITerminalSymbols.TokenName.RBRACKET) { break nextArg; } consumeToken(); @@ -738,7 +739,7 @@ public abstract class AbstractCommentParser { // Read argument name long argNamePos = -1; - if (readToken() == ITerminalSymbols.TokenNameIdentifier) { + if (readToken() == ITerminalSymbols.TokenName.IDENTIFIER) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) @@ -772,16 +773,16 @@ public abstract class AbstractCommentParser { } // Read separator or end arguments declaration - int token = readToken(); + TokenName token = readToken(); char[] name = argName == null ? new char[0] : argName; - if (token == ITerminalSymbols.TokenNameCOMMA) { + if (token == ITerminalSymbols.TokenName.COMMA) { // Create new argument Object argument = createArgumentReference(name, dim, typeRef, dimPositions, argNamePos); arguments.add(argument); consumeToken(); iToken++; - } else if (token == ITerminalSymbols.TokenNameRPAREN) { + } else if (token == ITerminalSymbols.TokenName.RPAREN) { // verify characters after arguments declaration (expecting // white space or end comment) if (!verifySpaceOrEndComment()) { @@ -818,37 +819,37 @@ public abstract class AbstractCommentParser { int start = this.scanner.getCurrentTokenStartPosition(); if (Character.toLowerCase(readChar()) == 'a') { this.scanner.currentPosition = this.index; - if (readToken() == ITerminalSymbols.TokenNameIdentifier) { - this.currentTokenType = -1; // do not update line end + if (readToken() == ITerminalSymbols.TokenName.IDENTIFIER) { + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // do not update line end try { if (CharOperation.equals(this.scanner .getCurrentIdentifierSource(), new char[] { 'h', 'r', 'e', 'f' }, false) - && readToken() == ITerminalSymbols.TokenNameEQUAL) { - this.currentTokenType = -1; // do not update line end - if (readToken() == ITerminalSymbols.TokenNameStringDoubleQuote - || readToken() == ITerminalSymbols.TokenNameStringSingleQuote) { - this.currentTokenType = -1; // do not update line + && readToken() == ITerminalSymbols.TokenName.EQUAL) { + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // do not update line end + if (readToken() == ITerminalSymbols.TokenName.STRINGDOUBLEQUOTE + || readToken() == ITerminalSymbols.TokenName.STRINGSINGLEQUOTE) { + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // do not update line // end // Skip all characters after string literal until // closing '>' (see bug 68726) while (this.index <= this.lineEnd - && readToken() != ITerminalSymbols.TokenNameGREATER) { - this.currentTokenType = -1; // do not update + && readToken() != ITerminalSymbols.TokenName.GREATER) { + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // do not update // line end } - if (this.currentTokenType == ITerminalSymbols.TokenNameGREATER) { + if (this.currentTokenType == ITerminalSymbols.TokenName.GREATER) { consumeToken(); // update line end as new lines // are allowed in URL // description - while (readToken() != ITerminalSymbols.TokenNameLESS) { + while (readToken() != ITerminalSymbols.TokenName.LESS) { if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@') { // Reset position: we want to rescan // last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // Signal syntax error if (this.sourceParser != null) this.sourceParser @@ -859,7 +860,7 @@ public abstract class AbstractCommentParser { } consumeToken(); } - this.currentTokenType = -1; // do not update + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // do not update // line end if (readChar() == '/') { if (Character.toLowerCase(readChar()) == 'a') { @@ -880,7 +881,7 @@ public abstract class AbstractCommentParser { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // Signal syntax error if (this.sourceParser != null) this.sourceParser.problemReporter().javadocInvalidSeeUrlReference( @@ -901,13 +902,13 @@ public abstract class AbstractCommentParser { this.memberStart = start; // Get member identifier - if (readToken() == ITerminalSymbols.TokenNameIdentifier) { + if (readToken() == ITerminalSymbols.TokenName.IDENTIFIER) { consumeToken(); pushIdentifier(true); // Look for next token to know whether it's a field or method // reference int previousPosition = this.index; - if (readToken() == ITerminalSymbols.TokenNameLPAREN) { + if (readToken() == ITerminalSymbols.TokenName.LPAREN) { consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); try { @@ -927,7 +928,7 @@ public abstract class AbstractCommentParser { // Reset position: we want to rescan last token this.index = previousPosition; this.scanner.currentPosition = previousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // Verify character(s) after identifier (expecting space or end // comment) @@ -951,7 +952,7 @@ public abstract class AbstractCommentParser { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; return null; } @@ -966,12 +967,12 @@ public abstract class AbstractCommentParser { try { // Push identifier next - int token = readToken(); + TokenName token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameIdentifier: + case IDENTIFIER: consumeToken(); return pushParamName(); - case ITerminalSymbols.TokenNameEOF: + case EOF: break; default: start = this.scanner.getCurrentTokenStartPosition(); @@ -987,7 +988,7 @@ public abstract class AbstractCommentParser { // Reset position to avoid missing tokens when new line was encountered this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // Report problem if (this.sourceParser != null) @@ -1011,9 +1012,9 @@ public abstract class AbstractCommentParser { // Scan tokens int primitiveToken = -1; nextToken: for (int iToken = 0;; iToken++) { - int token = readToken(); + TokenName token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameIdentifier: + case IDENTIFIER: if (((iToken % 2) > 0)) { // identifiers must be odd tokens break nextToken; } @@ -1021,22 +1022,22 @@ public abstract class AbstractCommentParser { consumeToken(); break; - case ITerminalSymbols.TokenNameDOT: + case DOT: if ((iToken % 2) == 0) { // dots must be even tokens throw new InvalidInputException(); } consumeToken(); break; - // case ITerminalSymbols.TokenNamevoid : - // case ITerminalSymbols.TokenNameboolean : - // case ITerminalSymbols.TokenNamebyte : - // case ITerminalSymbols.TokenNamechar : - // case ITerminalSymbols.TokenNamedouble : - // case ITerminalSymbols.TokenNamefloat : - // case ITerminalSymbols.TokenNameint : - // case ITerminalSymbols.TokenNamelong : - // case ITerminalSymbols.TokenNameshort : + // case ITerminalSymbols.TokenName.void : + // case ITerminalSymbols.TokenName.boolean : + // case ITerminalSymbols.TokenName.byte : + // case ITerminalSymbols.TokenName.char : + // case ITerminalSymbols.TokenName.double : + // case ITerminalSymbols.TokenName.float : + // case ITerminalSymbols.TokenName.int : + // case ITerminalSymbols.TokenName.long : + // case ITerminalSymbols.TokenName.short : // if (iToken > 0) { // throw new InvalidInputException(); // } @@ -1051,10 +1052,10 @@ public abstract class AbstractCommentParser { } if ((iToken % 2) == 0) { // cannot leave on a dot // Reset position: we want to rescan last token - if (this.kind == DOM_PARSER && this.currentTokenType != -1) { + if (this.kind == DOM_PARSER && this.currentTokenType.compareTo (ITerminalSymbols.TokenName.NONE) > 0) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; } throw new InvalidInputException(); } @@ -1062,10 +1063,10 @@ public abstract class AbstractCommentParser { } } // Reset position: we want to rescan last token - if (this.currentTokenType != -1) { + if (this.currentTokenType.compareTo (ITerminalSymbols.TokenName.NONE) > 0) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; } this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; return createTypeReference(primitiveToken); @@ -1084,10 +1085,10 @@ public abstract class AbstractCommentParser { int typeRefStartPosition = -1; nextToken: while (this.index < this.scanner.eofPosition) { previousPosition = this.index; - int token = readToken(); + TokenName token = readToken(); switch (token) { - case ITerminalSymbols.TokenNameStringDoubleQuote: // @see "string" - case ITerminalSymbols.TokenNameStringSingleQuote: + case STRINGDOUBLEQUOTE: // @see "string" + case STRINGSINGLEQUOTE: int start = this.scanner.getCurrentTokenStartPosition(); consumeToken(); // If typeRef != null we may raise a warning here to let user @@ -1107,8 +1108,7 @@ public abstract class AbstractCommentParser { this.sourceParser.problemReporter() .javadocInvalidSeeReference(start, this.lineEnd); return false; - case ITerminalSymbols.TokenNameLESS: // @see "label + case LESS: // @see "label consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); if (parseHref()) { @@ -1132,7 +1132,7 @@ public abstract class AbstractCommentParser { .javadocInvalidSeeReference(start, this.lineEnd); } return false; - case ITerminalSymbols.TokenNameERROR: + case ERROR: if (this.scanner.currentCharacter == '#') { // @see ...#member consumeToken(); reference = parseMember(typeRef); @@ -1142,7 +1142,7 @@ public abstract class AbstractCommentParser { return false; } break nextToken; - case ITerminalSymbols.TokenNameIdentifier: + case IDENTIFIER: if (typeRef == null) { typeRefStartPosition = this.scanner .getCurrentTokenStartPosition(); @@ -1161,7 +1161,7 @@ public abstract class AbstractCommentParser { if (reference == null) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; if (this.sourceParser != null) this.sourceParser.problemReporter().javadocMissingSeeReference( this.tagSourceStart, this.tagSourceEnd); @@ -1171,7 +1171,7 @@ public abstract class AbstractCommentParser { // Reset position at the end of type reference this.index = this.lastIdentifierEndPosition + 1; this.scanner.currentPosition = this.index; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; // Verify that line end does not start with an open parenthese (which // could be a constructor reference wrongly written...) @@ -1188,7 +1188,7 @@ public abstract class AbstractCommentParser { if (!verifySpaceOrEndComment()) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end] == '\n') @@ -1226,7 +1226,7 @@ public abstract class AbstractCommentParser { // Reset position to avoid missing tokens when new line was encountered this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; - this.currentTokenType = -1; + this.currentTokenType = ITerminalSymbols.TokenName.NONE; return false; } @@ -1398,8 +1398,8 @@ public abstract class AbstractCommentParser { /* * Read token only if previous was consumed */ - private int readToken() throws InvalidInputException { - if (this.currentTokenType < 0) { + private TokenName readToken() throws InvalidInputException { + if (this.currentTokenType.compareTo (ITerminalSymbols.TokenName.NONE) <= 0) { this.tokenPreviousPosition = this.scanner.currentPosition; this.currentTokenType = this.scanner.getNextToken(); if (this.scanner.currentPosition > (this.lineEnd + 1)) { // be @@ -1416,7 +1416,7 @@ public abstract class AbstractCommentParser { // same // line) this.lineStarted = false; - while (this.currentTokenType == ITerminalSymbols.TokenNameMULTIPLY) { + while (this.currentTokenType == ITerminalSymbols.TokenName.MULTIPLY) { this.currentTokenType = this.scanner.getNextToken(); } } @@ -1427,8 +1427,8 @@ public abstract class AbstractCommentParser { return this.currentTokenType; } - private int readTokenAndConsume() throws InvalidInputException { - int token = readToken(); + private TokenName readTokenAndConsume() throws InvalidInputException { + TokenName token = readToken(); consumeToken(); return token; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java index 08ba9c4..70a2d12 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java @@ -14,6 +14,7 @@ import java.util.HashSet; import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.internal.compiler.ast.AND_AND_Expression; import net.sourceforge.phpdt.internal.compiler.ast.ASTNode; import net.sourceforge.phpdt.internal.compiler.ast.AbstractMethodDeclaration; @@ -65,7 +66,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // protected int[] stack = new int[StackIncrement]; - public int firstToken; // handle for multiple parsing goals + public TokenName firstToken; // handle for multiple parsing goals public int lastAct; // handle for multiple parsing goals @@ -80,7 +81,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, */ public Scanner scanner; - int token; + TokenName token; protected int modifiers; @@ -89,18 +90,18 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, protected Parser(ProblemReporter problemReporter) { this.problemReporter = problemReporter; this.options = problemReporter.options; - this.token = TokenNameEOF; + this.token = TokenName.EOF; this.initializeScanner(); } // public void setFileToParse(IFile fileToParse) { -// this.token = TokenNameEOF; +// this.token = TokenName.EOF; // this.initializeScanner(); // } /** * ClassDeclaration Constructor. - * + * * @param s * @param sess * Description of Parameter @@ -118,7 +119,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // this.phpList = null; // this.includesList = null; // // this.str = ""; -// this.token = TokenNameEOF; +// this.token = TokenName.EOF; // // this.chIndx = 0; // // this.rowCount = 1; // // this.columnCount = 0; @@ -146,7 +147,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * This method will throw the SyntaxError. It will add the good lines and * columns to the Error - * + * * @param error * the error message * @throws SyntaxError @@ -170,7 +171,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * This method will throw the SyntaxError. It will add the good lines and * columns to the Error - * + * * @param error * the error message * @throws SyntaxError @@ -214,21 +215,20 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } /** - * gets the next token from input + * Read the next token from input */ private void getNextToken() { try { token = scanner.getNextToken(); if (Scanner.DEBUG) { - int currentEndPosition = scanner.getCurrentTokenEndPosition(); - int currentStartPosition = scanner - .getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," - + currentEndPosition + ": "); + int currentEndPosition = scanner.getCurrentTokenEndPosition(); + int currentStartPosition = scanner.getCurrentTokenStartPosition(); + + System.out.print ("getNextToken: from " + currentStartPosition + " to " + currentEndPosition + ": "); System.out.println(scanner.toStringAction(token)); } } catch (InvalidInputException e) { - token = TokenNameERROR; + token = TokenName.ERROR; String detailedMessage = e.getMessage(); if (detailedMessage == Scanner.UNTERMINATED_STRING) { @@ -242,7 +242,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, public void init(String s) { // this.str = s; - this.token = TokenNameEOF; + this.token = TokenName.EOF; this.includesList = new ArrayList(); // this.chIndx = 0; // this.rowCount = 1; @@ -266,7 +266,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, this.includesList = new ArrayList(); // this.indexManager = indexManager; // this.str = ""; - this.token = TokenNameEOF; + this.token = TokenName.EOF; // this.chIndx = 0; // this.rowCount = 1; // this.columnCount = 0; @@ -298,6 +298,8 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * Parses a string with php tags i.e. '<body> <?php phpinfo() ?> * </body>' + * + * The main entry point when parsing a file */ protected void parse() { if (scanner.compilationUnit != null) { @@ -307,36 +309,50 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, consumePackageDeclarationName((IFile) resource); } } + getNextToken(); + do { try { - if (token != TokenNameEOF && token != TokenNameERROR) { - statementList(); + if (token != TokenName.EOF && // If we are not at the end of file + token != TokenName.ERROR) { // and have no error + statementList(); // build the statement list for the entire file } - if (token != TokenNameEOF) { - if (token == TokenNameERROR) { - throwSyntaxError("Scanner error (Found unknown token: " - + scanner.toStringAction(token) + ")"); - } - if (token == TokenNameRPAREN) { - throwSyntaxError("Too many closing ')'; end-of-file not reached."); - } - if (token == TokenNameRBRACE) { - throwSyntaxError("Too many closing '}'; end-of-file not reached."); - } - if (token == TokenNameRBRACKET) { - throwSyntaxError("Too many closing ']'; end-of-file not reached."); - } - if (token == TokenNameLPAREN) { - throwSyntaxError("Read character '('; end-of-file not reached."); - } - if (token == TokenNameLBRACE) { - throwSyntaxError("Read character '{'; end-of-file not reached."); - } - if (token == TokenNameLBRACKET) { - throwSyntaxError("Read character '['; end-of-file not reached."); + + if (token != TokenName.EOF) { + switch (token) { + case ERROR: + throwSyntaxError("Scanner error (Found unknown token: " + scanner.toStringAction(token) + ")"); + break; + + case RPAREN: + throwSyntaxError("Too many closing ')'; end-of-file not reached."); + break; + + case RBRACE: + throwSyntaxError("Too many closing '}'; end-of-file not reached."); + break; + + case RBRACKET: + throwSyntaxError("Too many closing ']'; end-of-file not reached."); + break; + + case LPAREN: + throwSyntaxError("Read character '('; end-of-file not reached."); + break; + + case LBRACE: + throwSyntaxError("Read character '{'; end-of-file not reached."); + break; + + case LBRACKET: + throwSyntaxError("Read character '['; end-of-file not reached."); + break; + + default: + throwSyntaxError("End-of-file not reached."); + break; } - throwSyntaxError("End-of-file not reached."); } break; } catch (SyntaxError syntaxError) { @@ -365,7 +381,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, protected void parseFunction(HashMap variables) { getNextToken(); boolean hasModifiers = member_modifiers(); - if (token == TokenNamefunction) { + if (token == TokenName.FUNCTION) { if (!hasModifiers) { checkAndSetModifiers(AccPublic); } @@ -436,111 +452,139 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, return compilationUnit; } + /** + * + * @return A block object which contains all statements from within the current block + */ private Block statementList() { - boolean branchStatement = false; - Statement statement; - int blockStart = scanner.getCurrentTokenStartPosition(); - ArrayList blockStatements = new ArrayList(); + boolean branchStatement = false; + int blockStart = scanner.getCurrentTokenStartPosition(); + ArrayList blockStatements = new ArrayList(); + Statement statement; + do { try { statement = statement(); - blockStatements.add(statement); - if (token == TokenNameEOF) { + + if (statement != null) { + blockStatements.add(statement); + } + + if (token == TokenName.EOF) { return null; } + if (branchStatement && statement != null) { - // reportSyntaxError("Unreachable code", - // statement.sourceStart, - // statement.sourceEnd); + // reportSyntaxError("Unreachable code", statement.sourceStart, statement.sourceEnd); if (!(statement instanceof BreakStatement)) { /* - * don't give an error for break statement following - * return statement Technically it's unreachable code, - * but in switch-case it's recommended to avoid + * Don't give an error for break statement following return statement. + * Technically it's unreachable code, but in switch-case it's recommended to avoid * accidental fall-through later when editing the code */ - problemReporter.unreachableCode(new String(scanner - .getCurrentIdentifierSource()), - statement.sourceStart, statement.sourceEnd, - referenceContext, - compilationUnit.compilationResult); + problemReporter.unreachableCode (new String (scanner.getCurrentIdentifierSource ()), + statement.sourceStart, + statement.sourceEnd, + referenceContext, + compilationUnit.compilationResult); } } - if ((token == TokenNameRBRACE) || (token == TokenNamecase) - || (token == TokenNamedefault) - || (token == TokenNameelse) - || (token == TokenNameelseif) - || (token == TokenNameendif) - || (token == TokenNameendfor) - || (token == TokenNameendforeach) - || (token == TokenNameendwhile) - || (token == TokenNameendswitch) - || (token == TokenNameenddeclare) - || (token == TokenNameEOF) || (token == TokenNameERROR)) { - return createBlock(blockStart, blockStatements); + + switch (token) { + case RBRACE: + case CASE: + case DEFAULT: + case ELSE: + case ELSEIF: + case ENDIF: + case ENDFOR: + case ENDFOREACH: + case ENDWHILE: + case ENDSWITCH: + case ENDDECLARE: + case EOF: + case ERROR: + return createBlock (blockStart, blockStatements); // Create and return a block object (contains all the statements from the current read block) } + branchStatement = checkUnreachableStatements(statement); - } catch (SyntaxError sytaxErr1) { - // if an error occured, - // try to find keywords + } + catch (SyntaxError sytaxErr1) { + // If an error occurred, try to find keywords // to parse the rest of the string boolean tokenize = scanner.tokenizeStrings; + if (!tokenize) { scanner.tokenizeStrings = true; } + try { - while (token != TokenNameEOF) { - if ((token == TokenNameRBRACE) - || (token == TokenNamecase) - || (token == TokenNamedefault) - || (token == TokenNameelse) - || (token == TokenNameelseif) - || (token == TokenNameendif) - || (token == TokenNameendfor) - || (token == TokenNameendforeach) - || (token == TokenNameendwhile) - || (token == TokenNameendswitch) - || (token == TokenNameenddeclare) - || (token == TokenNameEOF) - || (token == TokenNameERROR)) { - return createBlock(blockStart, blockStatements); + boolean bBreakLoop = false; + + while (token != TokenName.EOF) { // As long as we are not at the end of file + switch (token) { // If a block close? + case RBRACE: + case CASE: + case DEFAULT: + case ELSE: + case ELSEIF: + case ENDIF: + case ENDFOR: + case ENDFOREACH: + case ENDWHILE: + case ENDSWITCH: + case ENDDECLARE: + case EOF: + case ERROR: + return createBlock (blockStart, blockStatements); // Create and return a block object (contains all the statements from the current read block) + } + + switch (token) { + case IF: + case SWITCH: + case FOR: + case WHILE: + case DO: + case FOREACH: + case CONTINUE: + case BREAK: + case RETURN: + case EXIT: + case ECHO: + case NAMESPACE: + case ECHO_INVISIBLE: + case GLOBAL: + case STATIC: + case UNSET: + case FUNCTION: + case DECLARE: + case TRY: + case CATCH: + case THROW: + case FINAL: + case ABSTRACT: + case CLASS: + case INTERFACE: + bBreakLoop = true; + break; } - if (token == TokenNameif || token == TokenNameswitch - || token == TokenNamefor - || token == TokenNamewhile - || token == TokenNamedo - || token == TokenNameforeach - || token == TokenNamecontinue - || token == TokenNamebreak - || token == TokenNamereturn - || token == TokenNameexit - || token == TokenNameecho - || token == TokenNameECHO_INVISIBLE - || token == TokenNameglobal - || token == TokenNamestatic - || token == TokenNameunset - || token == TokenNamefunction - || token == TokenNamedeclare - || token == TokenNametry - || token == TokenNamecatch - || token == TokenNamethrow - || token == TokenNamefinal - || token == TokenNameabstract - || token == TokenNameclass - || token == TokenNameinterface) { + + if (bBreakLoop) { break; } + // System.out.println(scanner.toStringAction(token)); getNextToken(); // System.out.println(scanner.toStringAction(token)); } - if (token == TokenNameEOF) { + + if (token == TokenName.EOF) { throw sytaxErr1; } } finally { scanner.tokenizeStrings = tokenize; } - } + } // catch } while (true); } @@ -549,9 +593,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, * @return */ private boolean checkUnreachableStatements(Statement statement) { - if (statement instanceof ReturnStatement - || statement instanceof ContinueStatement - || statement instanceof BreakStatement) { + if (statement instanceof ReturnStatement || + statement instanceof ContinueStatement || + statement instanceof BreakStatement) { return true; } else if (statement instanceof IfStatement && ((IfStatement) statement).checkUnreachable) { @@ -565,26 +609,30 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, * @param blockStatements * @return */ - private Block createBlock(int blockStart, ArrayList blockStatements) { - int blockEnd = scanner.getCurrentTokenEndPosition(); - Block b = Block.EmptyWith(blockStart, blockEnd); + private Block createBlock (int blockStart, ArrayList blockStatements) { + int blockEnd = scanner.getCurrentTokenEndPosition (); + Block b = Block.EmptyWith (blockStart, blockEnd); + b.statements = new Statement[blockStatements.size()]; - blockStatements.toArray(b.statements); + blockStatements.toArray (b.statements); + return b; } private void functionBody(MethodDeclaration methodDecl) { // '{' [statement-list] '}' - if (token == TokenNameLBRACE) { + if (token == TokenName.LBRACE) { getNextToken(); } else { methodDecl.sourceEnd = scanner.getCurrentTokenStartPosition() - 1; throwSyntaxError("'{' expected in compound-statement."); } - if (token != TokenNameRBRACE) { + + if (token != TokenName.RBRACE) { statementList(); } - if (token == TokenNameRBRACE) { + + if (token == TokenName.RBRACE) { methodDecl.sourceEnd = scanner.getCurrentTokenEndPosition(); getNextToken(); } else { @@ -593,441 +641,524 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } + /** + * Try to create an statement reading from the current token position + * + * @return Returns a found statement or empty statement + */ private Statement statement() { - Statement statement = null; - Expression expression; - int sourceStart = scanner.getCurrentTokenStartPosition(); - int sourceEnd; - if (token == TokenNameif) { - // T_IF '(' expr ')' statement elseif_list else_single - // T_IF '(' expr ')' ':' inner_statement_list new_elseif_list - // new_else_single T_ENDIF ';' - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - } else { - throwSyntaxError("'(' expected after 'if' keyword."); - } - expression = expr(); - if (token == TokenNameRPAREN) { - getNextToken(); - } else { - throwSyntaxError("')' expected after 'if' condition."); - } - // create basic IfStatement - IfStatement ifStatement = new IfStatement(expression, null, null, - sourceStart, -1); - if (token == TokenNameCOLON) { - getNextToken(); - ifStatementColon(ifStatement); - } else { - ifStatement(ifStatement); - } - return ifStatement; - } else if (token == TokenNameswitch) { - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - } else { - throwSyntaxError("'(' expected after 'switch' keyword."); - } - expr(); - if (token == TokenNameRPAREN) { - getNextToken(); - } else { - throwSyntaxError("')' expected after 'switch' condition."); - } - switchStatement(); - return statement; - } else if (token == TokenNamefor) { - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - } else { - throwSyntaxError("'(' expected after 'for' keyword."); - } - if (token == TokenNameSEMICOLON) { + Statement statement = null; + Expression expression; + int sourceStart = scanner.getCurrentTokenStartPosition(); + int sourceEnd; + + switch (token) { + case IF: + // T_IF '(' expr ')' statement elseif_list else_single + // T_IF '(' expr ')' ':' inner_statement_list new_elseif_list + // new_else_single T_ENDIF ';' getNextToken(); - } else { - expressionList(); - if (token == TokenNameSEMICOLON) { + if (token == TokenName.LPAREN) { getNextToken(); } else { - throwSyntaxError("';' expected after 'for'."); + throwSyntaxError("'(' expected after 'if' keyword."); } - } - if (token == TokenNameSEMICOLON) { - getNextToken(); - } else { - expressionList(); - if (token == TokenNameSEMICOLON) { + + expression = expr(); + + if (token == TokenName.RPAREN) { getNextToken(); } else { - throwSyntaxError("';' expected after 'for'."); + throwSyntaxError("')' expected after 'if' condition."); } - } - if (token == TokenNameRPAREN) { - getNextToken(); - } else { - expressionList(); - if (token == TokenNameRPAREN) { + // create basic IfStatement + IfStatement ifStatement = new IfStatement(expression, null, null, sourceStart, -1); + + if (token == TokenName.COLON) { getNextToken(); + ifStatementColon(ifStatement); } else { - throwSyntaxError("')' expected after 'for'."); + ifStatement(ifStatement); } - } - forStatement(); - return statement; - } else if (token == TokenNamewhile) { - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - } else { - throwSyntaxError("'(' expected after 'while' keyword."); - } - expr(); - if (token == TokenNameRPAREN) { + return ifStatement; + + case SWITCH: getNextToken(); - } else { - throwSyntaxError("')' expected after 'while' condition."); - } - whileStatement(); - return statement; - } else if (token == TokenNamedo) { - getNextToken(); - if (token == TokenNameLBRACE) { + if (token == TokenName.LPAREN) { + getNextToken(); + } else { + throwSyntaxError("'(' expected after 'switch' keyword."); + } + expr(); + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + throwSyntaxError("')' expected after 'switch' condition."); + } + switchStatement(); + return statement; + + case FOR: getNextToken(); - if (token != TokenNameRBRACE) { - statementList(); + if (token == TokenName.LPAREN) { + getNextToken(); + } else { + throwSyntaxError("'(' expected after 'for' keyword."); } - if (token == TokenNameRBRACE) { + if (token == TokenName.SEMICOLON) { getNextToken(); } else { - throwSyntaxError("'}' expected after 'do' keyword."); + expressionList(); + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + throwSyntaxError("';' expected after 'for'."); + } } - } else { - statement(); - } - if (token == TokenNamewhile) { + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + expressionList(); + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + throwSyntaxError("';' expected after 'for'."); + } + } + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + expressionList(); + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + throwSyntaxError("')' expected after 'for'."); + } + } + forStatement(); + return statement; + + case WHILE: getNextToken(); - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); } else { throwSyntaxError("'(' expected after 'while' keyword."); } expr(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); } else { throwSyntaxError("')' expected after 'while' condition."); } - } else { - throwSyntaxError("'while' expected after 'do' keyword."); - } - if (token == TokenNameSEMICOLON) { + whileStatement(); + return statement; + + case DO: getNextToken(); - } else { - if (token != TokenNameINLINE_HTML) { - throwSyntaxError("';' expected after do-while statement."); + if (token == TokenName.LBRACE) { + getNextToken(); + if (token != TokenName.RBRACE) { + statementList(); + } + if (token == TokenName.RBRACE) { + getNextToken(); + } else { + throwSyntaxError("'}' expected after 'do' keyword."); + } + } else { + statement(); } + if (token == TokenName.WHILE) { + getNextToken(); + if (token == TokenName.LPAREN) { + getNextToken(); + } else { + throwSyntaxError("'(' expected after 'while' keyword."); + } + expr(); + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + throwSyntaxError("')' expected after 'while' condition."); + } + } else { + throwSyntaxError("'while' expected after 'do' keyword."); + } + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after do-while statement."); + } + getNextToken(); + } + return statement; + + case FOREACH: getNextToken(); - } - return statement; - } else if (token == TokenNameforeach) { - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - } else { - throwSyntaxError("'(' expected after 'foreach' keyword."); - } - expr(); - if (token == TokenNameas) { + if (token == TokenName.LPAREN) { + getNextToken(); + } else { + throwSyntaxError("'(' expected after 'foreach' keyword."); + } + expr(); + if (token == TokenName.AS) { + getNextToken(); + } else { + throwSyntaxError("'as' expected after 'foreach' exxpression."); + } + // variable(); + foreach_variable(); + foreach_optional_arg(); + if (token == TokenName.EQUAL_GREATER) { + getNextToken(); + variable(false, false); + } + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + throwSyntaxError("')' expected after 'foreach' expression."); + } + foreachStatement(); + return statement; + + case BREAK: + expression = null; getNextToken(); - } else { - throwSyntaxError("'as' expected after 'foreach' exxpression."); - } - // variable(); - foreach_variable(); - foreach_optional_arg(); - if (token == TokenNameEQUAL_GREATER) { + if (token != TokenName.SEMICOLON) { + expression = expr(); + } + if (token == TokenName.SEMICOLON) { + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after 'break'."); + } + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } + return new BreakStatement(null, sourceStart, sourceEnd); + + case CONTINUE: + expression = null; getNextToken(); - variable(false, false); - } - if (token == TokenNameRPAREN) { + if (token != TokenName.SEMICOLON) { + expression = expr(); + } + if (token == TokenName.SEMICOLON) { + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after 'continue'."); + } + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } + return new ContinueStatement(null, sourceStart, sourceEnd); + + case RETURN: + expression = null; getNextToken(); - } else { - throwSyntaxError("')' expected after 'foreach' expression."); - } - foreachStatement(); - return statement; - } else if (token == TokenNamebreak) { - expression = null; - getNextToken(); - if (token != TokenNameSEMICOLON) { - expression = expr(); - } - if (token == TokenNameSEMICOLON) { - sourceEnd = scanner.getCurrentTokenEndPosition(); + if (token != TokenName.SEMICOLON) { + expression = expr(); + } + if (token == TokenName.SEMICOLON) { + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after 'return'."); + } + sourceEnd = scanner.getCurrentTokenEndPosition(); + getNextToken(); + } + return new ReturnStatement(expression, sourceStart, sourceEnd); + + case ECHO: + getNextToken(); // Read the token after 'echo' + expressionList(); // Read everything after 'echo' + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after 'echo' statement."); + } + getNextToken(); + } + return statement; // return null statement + + case ECHO_INVISIBLE: + // 0-length token directly after PHP short tag <?= getNextToken(); - } else { - if (token != TokenNameINLINE_HTML) { - throwSyntaxError("';' expected after 'break'."); + expressionList(); + if (token == TokenName.SEMICOLON) { + getNextToken(); + // if (token != TokenName.INLINE_HTML) { + // // TODO should this become a configurable warning? + // reportSyntaxError("Probably '?>' expected after PHP short tag + // expression (only the first expression will be echoed)."); + // } + } else { + if (token != TokenName.INLINE_HTML) { + throwSyntaxError("';' expected after PHP short tag ' sourceEnd) { + sourceEnd = methodDecl.declarationSourceStart + 1; + } + methodDecl.declarationSourceEnd = sourceEnd; + methodDecl.sourceEnd = sourceEnd; } - sourceEnd = scanner.getCurrentTokenEndPosition(); + return statement; + + case DECLARE: + // T_DECLARE '(' declare_list ')' declare_statement getNextToken(); - } - return new ReturnStatement(expression, sourceStart, sourceEnd); - } else if (token == TokenNameecho) { - getNextToken(); - expressionList(); - if (token == TokenNameSEMICOLON) { + if (token != TokenName.LPAREN) { + throwSyntaxError("'(' expected in 'declare' statement."); + } getNextToken(); - } else { - if (token != TokenNameINLINE_HTML) { - throwSyntaxError("';' expected after 'echo' statement."); + declare_list(); + if (token != TokenName.RPAREN) { + throwSyntaxError("')' expected in 'declare' statement."); } getNextToken(); - } - return statement; - } else if (token == TokenNameECHO_INVISIBLE) { - // 0-length token directly after PHP short tag <?= - getNextToken(); - expressionList(); - if (token == TokenNameSEMICOLON) { + declare_statement(); + return statement; + + case TRY: getNextToken(); - // if (token != TokenNameINLINE_HTML) { - // // TODO should this become a configurable warning? - // reportSyntaxError("Probably '?>' expected after PHP short tag - // expression (only the first expression will be echoed)."); - // } - } else { - if (token != TokenNameINLINE_HTML) { - throwSyntaxError("';' expected after PHP short tag ' sourceEnd) { - sourceEnd = methodDecl.declarationSourceStart + 1; + expr(); + if (token == TokenName.SEMICOLON) { + getNextToken(); + } else { + throwSyntaxError("';' expected after 'throw' exxpression."); } - methodDecl.declarationSourceEnd = sourceEnd; - methodDecl.sourceEnd = sourceEnd; - } - return statement; - } else if (token == TokenNamedeclare) { - // T_DECLARE '(' declare_list ')' declare_statement - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected in 'declare' statement."); - } - getNextToken(); - declare_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected in 'declare' statement."); - } - getNextToken(); - declare_statement(); - return statement; - } else if (token == TokenNametry) { - getNextToken(); - if (token != TokenNameLBRACE) { - throwSyntaxError("'{' expected in 'try' statement."); - } - getNextToken(); - statementList(); - if (token != TokenNameRBRACE) { - throwSyntaxError("'}' expected in 'try' statement."); - } - getNextToken(); - return statement; - } else if (token == TokenNamecatch) { - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected in 'catch' statement."); - } - getNextToken(); - fully_qualified_class_name(); - if (token != TokenNameVariable) { - throwSyntaxError("Variable expected in 'catch' statement."); - } - addVariableSet(); - getNextToken(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected in 'catch' statement."); - } - getNextToken(); - if (token != TokenNameLBRACE) { - throwSyntaxError("'{' expected in 'catch' statement."); - } - getNextToken(); - if (token != TokenNameRBRACE) { - statementList(); - if (token != TokenNameRBRACE) { - throwSyntaxError("'}' expected in 'catch' statement."); + return statement; + + case FINAL: + case ABSTRACT: + case CLASS: + case INTERFACE: + try { + TypeDeclaration typeDecl = new TypeDeclaration( + this.compilationUnit.compilationResult); + typeDecl.declarationSourceStart = scanner + .getCurrentTokenStartPosition(); + typeDecl.declarationSourceEnd = scanner + .getCurrentTokenEndPosition(); + typeDecl.name = new char[] { ' ' }; + // default super class + typeDecl.superclass = new SingleTypeReference( + TypeConstants.OBJECT, 0); + compilationUnit.types.add(typeDecl); + pushOnAstStack(typeDecl); + unticked_class_declaration_statement(typeDecl); + } finally { + // reduce stack: + astPtr--; + astLengthPtr--; } - } - getNextToken(); - additional_catches(); - return statement; - } else if (token == TokenNamethrow) { - getNextToken(); - expr(); - if (token == TokenNameSEMICOLON) { - getNextToken(); - } else { - throwSyntaxError("';' expected after 'throw' exxpression."); - } - return statement; - } else if (token == TokenNamefinal || token == TokenNameabstract - || token == TokenNameclass || token == TokenNameinterface) { - try { - TypeDeclaration typeDecl = new TypeDeclaration( - this.compilationUnit.compilationResult); - typeDecl.declarationSourceStart = scanner - .getCurrentTokenStartPosition(); - typeDecl.declarationSourceEnd = scanner - .getCurrentTokenEndPosition(); - typeDecl.name = new char[] { ' ' }; - // default super class - typeDecl.superclass = new SingleTypeReference( - TypeConstants.OBJECT, 0); - compilationUnit.types.add(typeDecl); - pushOnAstStack(typeDecl); - unticked_class_declaration_statement(typeDecl); - } finally { - // reduce stack: - astPtr--; - astLengthPtr--; - } - return statement; - // } else { - // throwSyntaxError("Unexpected keyword '" + keyword + "'"); - } else if (token == TokenNameLBRACE) { - getNextToken(); - if (token != TokenNameRBRACE) { - statement = statementList(); - } - if (token == TokenNameRBRACE) { - getNextToken(); return statement; - } else { - throwSyntaxError("'}' expected."); - } - } else { - if (token != TokenNameSEMICOLON) { - expr(); - } - if (token == TokenNameSEMICOLON) { + case LBRACE: getNextToken(); - return statement; - } else { - if (token == TokenNameRBRACE) { - reportSyntaxError("';' expected after expression (Found token: " - + scanner.toStringAction(token) + ")"); + if (token != TokenName.RBRACE) { + statement = statementList(); + } + if (token == TokenName.RBRACE) { + getNextToken(); + return statement; } else { - if (token != TokenNameINLINE_HTML && token != TokenNameEOF) { - throwSyntaxError("';' expected after expression (Found token: " + throwSyntaxError("'}' expected."); + } + break; + + default: + if (token != TokenName.SEMICOLON) { + expr(); + } + + if (token == TokenName.SEMICOLON) { + getNextToken(); + return statement; + } + else if (token == TokenName.COLON) { // Colon after Label identifier + getNextToken(); + return statement; + } + else { + if (token == TokenName.RBRACE) { + reportSyntaxError("';' expected after expression (Found token: " + scanner.toStringAction(token) + ")"); } - getNextToken(); + else { + if (token != TokenName.INLINE_HTML && token != TokenName.EOF) { + throwSyntaxError("';' expected after expression (Found token: " + + scanner.toStringAction(token) + ")"); + } + getNextToken(); + } } - } + break; } // may be null return statement; @@ -1037,15 +1168,15 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // statement // | ':' inner_statement_list T_ENDDECLARE ';' // ; - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); // TODO: implement inner_statement_list(); statementList(); - if (token != TokenNameenddeclare) { + if (token != TokenName.ENDDECLARE) { throwSyntaxError("'enddeclare' expected in 'declare' statement."); } getNextToken(); - if (token != TokenNameSEMICOLON) { + if (token != TokenName.SEMICOLON) { throwSyntaxError("';' expected after 'enddeclare' keyword."); } getNextToken(); @@ -1058,16 +1189,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // T_STRING '=' static_scalar // | declare_list ',' T_STRING '=' static_scalar while (true) { - if (token != TokenNameIdentifier) { + if (token != TokenName.IDENTIFIER) { throwSyntaxError("Identifier expected in 'declare' list."); } getNextToken(); - if (token != TokenNameEQUAL) { + if (token != TokenName.EQUAL) { throwSyntaxError("'=' expected in 'declare' list."); } getNextToken(); static_scalar(); - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -1075,30 +1206,30 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } private void additional_catches() { - while (token == TokenNamecatch) { + while (token == TokenName.CATCH) { getNextToken(); - if (token != TokenNameLPAREN) { + if (token != TokenName.LPAREN) { throwSyntaxError("'(' expected in 'catch' statement."); } getNextToken(); fully_qualified_class_name(); - if (token != TokenNameVariable) { + if (token != TokenName.VARIABLE) { throwSyntaxError("Variable expected in 'catch' statement."); } addVariableSet(); getNextToken(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected in 'catch' statement."); } getNextToken(); - if (token != TokenNameLBRACE) { + if (token != TokenName.LBRACE) { throwSyntaxError("'{' expected in 'catch' statement."); } getNextToken(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { statementList(); } - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in 'catch' statement."); } getNextToken(); @@ -1108,7 +1239,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void foreach_variable() { // w_variable // | '&' w_variable - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); } w_variable(true); @@ -1117,7 +1248,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void foreach_optional_arg() { // /* empty */ // | T_DOUBLE_ARROW foreach_variable - if (token == TokenNameEQUAL_GREATER) { + if (token == TokenName.EQUAL_GREATER) { getNextToken(); foreach_variable(); } @@ -1130,7 +1261,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, HashSet set = peekVariableSet(); while (true) { global_var(set); - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -1142,7 +1273,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // T_VARIABLE // | '$' r_variable // | '$' '{' expr '}' - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { if (fMethodVariables != null) { VariableInfo info = new VariableInfo(scanner .getCurrentTokenStartPosition(), @@ -1152,12 +1283,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } addVariableSet(set); getNextToken(); - } else if (token == TokenNameDOLLAR) { + } else if (token == TokenName.DOLLAR) { getNextToken(); - if (token == TokenNameLBRACE) { + if (token == TokenName.LBRACE) { getNextToken(); expr(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in global variable."); } getNextToken(); @@ -1175,7 +1306,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | T_VARIABLE '=' static_scalar, HashSet set = peekVariableSet(); while (true) { - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { if (fMethodVariables != null) { VariableInfo info = new VariableInfo(scanner .getCurrentTokenStartPosition(), @@ -1185,11 +1316,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } addVariableSet(set); getNextToken(); - if (token == TokenNameEQUAL) { + if (token == TokenName.EQUAL) { getNextToken(); static_scalar(); } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -1207,7 +1338,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // variable while (true) { variable(false, false); - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -1227,7 +1358,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void unticked_class_declaration_statement(TypeDeclaration typeDecl) { initializeModifiers(); - if (token == TokenNameinterface) { + if (token == TokenName.INTERFACE) { // interface_entry T_STRING // interface_extends_list // '{' class_statement_list '}' @@ -1236,9 +1367,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, typeDecl.modifiers = this.modifiers; typeDecl.sourceStart = scanner.getCurrentTokenStartPosition(); typeDecl.sourceEnd = scanner.getCurrentTokenEndPosition(); - if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { + if (token == TokenName.IDENTIFIER || token.compareTo (TokenName.KEYWORD) > 0) { typeDecl.name = scanner.getCurrentIdentifierSource(); - if (token > TokenNameKEYWORD) { + if (token.compareTo (TokenName.KEYWORD) > 0) { problemReporter.phpKeywordWarning(new String[] { scanner .toStringAction(token) }, scanner .getCurrentTokenStartPosition(), scanner @@ -1268,9 +1399,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, typeDecl.sourceEnd = scanner.getCurrentTokenEndPosition(); // identifier // identifier 'extends' identifier - if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { + if (token == TokenName.IDENTIFIER || token.compareTo (TokenName.KEYWORD) > 0) { typeDecl.name = scanner.getCurrentIdentifierSource(); - if (token > TokenNameKEYWORD) { + if (token.compareTo (TokenName.KEYWORD) > 0) { problemReporter.phpKeywordWarning(new String[] { scanner .toStringAction(token) }, scanner .getCurrentTokenStartPosition(), scanner @@ -1285,10 +1416,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // extends_from: // /* empty */ // | T_EXTENDS fully_qualified_class_name - if (token == TokenNameextends) { + if (token == TokenName.EXTENDS) { class_extends_list(typeDecl); // getNextToken(); - // if (token != TokenNameIdentifier) { + // if (token != TokenName.IDENTIFIER) { // throwSyntaxError("Class name expected after keyword // 'extends'.", // scanner.getCurrentTokenStartPosition(), scanner @@ -1304,9 +1435,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } // '{' class_statement_list '}' - if (token == TokenNameLBRACE) { + if (token == TokenName.LBRACE) { getNextToken(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { ArrayList list = new ArrayList(); class_statement_list(list); typeDecl.fields = new FieldDeclaration[list.size()]; @@ -1314,7 +1445,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, typeDecl.fields[i] = (FieldDeclaration) list.get(i); } } - if (token == TokenNameRBRACE) { + if (token == TokenName.RBRACE) { typeDecl.declarationSourceEnd = scanner .getCurrentTokenEndPosition(); getNextToken(); @@ -1330,19 +1461,19 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // T_CLASS // | T_ABSTRACT T_CLASS // | T_FINAL T_CLASS - if (token == TokenNameclass) { + if (token == TokenName.CLASS) { getNextToken(); - } else if (token == TokenNameabstract) { + } else if (token == TokenName.ABSTRACT) { checkAndSetModifiers(AccAbstract); getNextToken(); - if (token != TokenNameclass) { + if (token != TokenName.CLASS) { throwSyntaxError("Keyword 'class' expected after keyword 'abstract'."); } getNextToken(); - } else if (token == TokenNamefinal) { + } else if (token == TokenName.FINAL) { checkAndSetModifiers(AccFinal); getNextToken(); - if (token != TokenNameclass) { + if (token != TokenName.CLASS) { throwSyntaxError("Keyword 'class' expected after keyword 'final'."); } getNextToken(); @@ -1354,10 +1485,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // private void class_extends(TypeDeclaration typeDecl) { // // /* empty */ // // | T_EXTENDS interface_list - // if (token == TokenNameextends) { + // if (token == TokenName.EXTENDS) { // getNextToken(); // - // if (token == TokenNameIdentifier) { + // if (token == TokenName.IDENTIFIER) { // getNextToken(); // } else { // throwSyntaxError("Class name expected after keyword 'extends'."); @@ -1368,7 +1499,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void interface_extends_list(TypeDeclaration typeDecl) { // /* empty */ // | T_EXTENDS interface_list - if (token == TokenNameextends) { + if (token == TokenName.EXTENDS) { getNextToken(); interface_list(typeDecl); } @@ -1377,7 +1508,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void class_extends_list(TypeDeclaration typeDecl) { // /* empty */ // | T_EXTENDS interface_list - if (token == TokenNameextends) { + if (token == TokenName.EXTENDS) { getNextToken(); class_list(typeDecl); } @@ -1386,7 +1517,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void implements_list(TypeDeclaration typeDecl) { // /* empty */ // | T_IMPLEMENTS interface_list - if (token == TokenNameimplements) { + if (token == TokenName.IMPLEMENTS) { getNextToken(); interface_list(typeDecl); } @@ -1396,7 +1527,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // class_list: // fully_qualified_class_name do { - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { //char[] ident = scanner.getCurrentIdentifierSource(); // TODO make this code working better: // SingleTypeReference ref = @@ -1409,7 +1540,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } else { throwSyntaxError("Classname expected after keyword 'extends'."); } - if (token == TokenNameCOMMA) { + if (token == TokenName.COMMA) { reportSyntaxError("No multiple inheritance allowed. Expected token 'implements' or '{'."); getNextToken(); continue; @@ -1424,12 +1555,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // fully_qualified_class_name // | interface_list ',' fully_qualified_class_name do { - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { getNextToken(); } else { throwSyntaxError("Interfacename expected after keyword 'implements'."); } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { return; } getNextToken(); @@ -1438,12 +1569,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // private void classBody(TypeDeclaration typeDecl) { // //'{' [class-element-list] '}' - // if (token == TokenNameLBRACE) { + // if (token == TokenName.LBRACE) { // getNextToken(); - // if (token != TokenNameRBRACE) { + // if (token != TokenName.RBRACE) { // class_statement_list(); // } - // if (token == TokenNameRBRACE) { + // if (token == TokenName.RBRACE) { // typeDecl.declarationSourceEnd = scanner.getCurrentTokenEndPosition(); // getNextToken(); // } else { @@ -1457,21 +1588,27 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, do { try { class_statement(list); - if (token == TokenNamepublic || token == TokenNameprotected - || token == TokenNameprivate - || token == TokenNamestatic - || token == TokenNameabstract - || token == TokenNamefinal - || token == TokenNamefunction || token == TokenNamevar - || token == TokenNameconst) { + if (token == TokenName.PUBLIC || + token == TokenName.PROTECTED || + token == TokenName.PRIVATE || + token == TokenName.STATIC || + token == TokenName.ABSTRACT || + token == TokenName.FINAL || + token == TokenName.FUNCTION || + token == TokenName.VAR || + token == TokenName.CONST) { continue; } - if (token == TokenNameRBRACE) { + + if (token == TokenName.RBRACE) { break; } + throwSyntaxError("'}' at end of class statement."); - } catch (SyntaxError sytaxErr1) { + } + catch (SyntaxError sytaxErr1) { boolean tokenize = scanner.tokenizeStrings; + if (!tokenize) { scanner.tokenizeStrings = true; } @@ -1479,22 +1616,22 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // if an error occured, // try to find keywords // to parse the rest of the string - while (token != TokenNameEOF) { - if (token == TokenNamepublic - || token == TokenNameprotected - || token == TokenNameprivate - || token == TokenNamestatic - || token == TokenNameabstract - || token == TokenNamefinal - || token == TokenNamefunction - || token == TokenNamevar - || token == TokenNameconst) { + while (token != TokenName.EOF) { + if (token == TokenName.PUBLIC || + token == TokenName.PROTECTED || + token == TokenName.PRIVATE || + token == TokenName.STATIC || + token == TokenName.ABSTRACT || + token == TokenName.FINAL || + token == TokenName.FUNCTION || + token == TokenName.VAR || + token == TokenName.CONST) { break; } // System.out.println(scanner.toStringAction(token)); getNextToken(); } - if (token == TokenNameEOF) { + if (token == TokenName.EOF) { throw sytaxErr1; } } finally { @@ -1504,6 +1641,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } while (true); } + /** + * + */ private void class_statement(ArrayList list) { // class_statement: // variable_modifiers class_variable_declaration ';' @@ -1513,7 +1653,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, initializeModifiers(); int declarationSourceStart = scanner.getCurrentTokenStartPosition(); - if (token == TokenNamevar) { + if (token == TokenName.VAR) { checkAndSetModifiers(AccPublic); problemReporter.phpVarDeprecatedWarning(scanner .getCurrentTokenStartPosition(), scanner @@ -1521,16 +1661,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, compilationUnit.compilationResult); getNextToken(); class_variable_declaration(declarationSourceStart, list); - } else if (token == TokenNameconst) { + } else if (token == TokenName.CONST) { checkAndSetModifiers(AccFinal | AccPublic); class_constant_declaration(declarationSourceStart, list); - if (token != TokenNameSEMICOLON) { + if (token != TokenName.SEMICOLON) { throwSyntaxError("';' expected after class const declaration."); } getNextToken(); } else { boolean hasModifiers = member_modifiers(); - if (token == TokenNamefunction) { + if (token == TokenName.FUNCTION) { if (!hasModifiers) { checkAndSetModifiers(AccPublic); } @@ -1565,13 +1705,13 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ArrayList list) { // class_constant_declaration ',' T_STRING '=' static_scalar // | T_CONST T_STRING '=' static_scalar - if (token != TokenNameconst) { + if (token != TokenName.CONST) { throwSyntaxError("'const' keyword expected in class declaration."); } else { getNextToken(); } while (true) { - if (token != TokenNameIdentifier) { + if (token != TokenName.IDENTIFIER) { throwSyntaxError("Identifier expected in class const declaration."); } FieldDeclaration fieldDeclaration = new FieldDeclaration(scanner @@ -1586,12 +1726,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // fieldDeclaration.type list.add(fieldDeclaration); getNextToken(); - if (token != TokenNameEQUAL) { + if (token != TokenName.EQUAL) { throwSyntaxError("'=' expected in class const declaration."); } getNextToken(); static_scalar(); - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; // while(true)-loop } getNextToken(); @@ -1603,7 +1743,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // non_empty_member_modifiers // //| T_VAR // initializeModifiers(); - // if (token == TokenNamevar) { + // if (token == TokenName.var) { // checkAndSetModifiers(AccPublic); // reportSyntaxError( // "Keyword 'var' is deprecated. Please use 'public' 'private' or @@ -1637,27 +1777,27 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | T_FINAL boolean foundToken = false; while (true) { - if (token == TokenNamepublic) { + if (token == TokenName.PUBLIC) { checkAndSetModifiers(AccPublic); getNextToken(); foundToken = true; - } else if (token == TokenNameprotected) { + } else if (token == TokenName.PROTECTED) { checkAndSetModifiers(AccProtected); getNextToken(); foundToken = true; - } else if (token == TokenNameprivate) { + } else if (token == TokenName.PRIVATE) { checkAndSetModifiers(AccPrivate); getNextToken(); foundToken = true; - } else if (token == TokenNamestatic) { + } else if (token == TokenName.STATIC) { checkAndSetModifiers(AccStatic); getNextToken(); foundToken = true; - } else if (token == TokenNameabstract) { + } else if (token == TokenName.ABSTRACT) { checkAndSetModifiers(AccAbstract); getNextToken(); foundToken = true; - } else if (token == TokenNamefinal) { + } else if (token == TokenName.FINAL) { checkAndSetModifiers(AccFinal); getNextToken(); foundToken = true; @@ -1677,7 +1817,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | T_VARIABLE '=' static_scalar char[] classVariable; do { - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { classVariable = scanner.getCurrentIdentifierSource(); // indexManager.addIdentifierInformation('v', classVariable, // buf, -1, @@ -1699,23 +1839,23 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, .getCurrentIdentifierSource()), info); } getNextToken(); - if (token == TokenNameEQUAL) { + if (token == TokenName.EQUAL) { getNextToken(); static_scalar(); } } else { - // if (token == TokenNamethis) { + // if (token == TokenName.THIS) { // throwSyntaxError("'$this' not allowed after keyword 'public' // 'protected' 'private' 'var'."); // } throwSyntaxError("Variable expected after keyword 'public' 'protected' 'private' 'var'."); } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); } while (true); - if (token != TokenNameSEMICOLON) { + if (token != TokenName.SEMICOLON) { throwSyntaxError("';' expected after field declaration."); } getNextToken(); @@ -1754,7 +1894,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, try { pushFunctionVariableSet(); functionDeclarator(methodDecl); - if (token == TokenNameSEMICOLON) { + if (token == TokenName.SEMICOLON) { if (!isAbstract) { methodDecl.sourceEnd = scanner .getCurrentTokenStartPosition() - 1; @@ -1774,38 +1914,63 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void functionDeclarator(MethodDeclaration methodDecl) { // identifier '(' [parameter-list] ')' - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); } + methodDecl.sourceStart = scanner.getCurrentTokenStartPosition(); methodDecl.sourceEnd = scanner.getCurrentTokenEndPosition(); - if (Scanner.isIdentifierOrKeyword(token)) { - methodDecl.selector = scanner.getCurrentIdentifierSource(); - if (token > TokenNameKEYWORD) { - problemReporter.phpKeywordWarning(new String[] { scanner - .toStringAction(token) }, scanner - .getCurrentTokenStartPosition(), scanner - .getCurrentTokenEndPosition(), referenceContext, - compilationUnit.compilationResult); - } - getNextToken(); - if (token == TokenNameLPAREN) { + + if (Scanner.isIdentifierOrKeyword (token) || + token == TokenName.LPAREN) { + + if (token == TokenName.LPAREN) { + methodDecl.selector = scanner.getCurrentIdentifierSource(); + + if (token.compareTo (TokenName.KEYWORD) > 0) { + problemReporter.phpKeywordWarning (new String[] {scanner.toStringAction(token) }, + scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition(), + referenceContext, + compilationUnit.compilationResult); + } + } + else { + methodDecl.selector = scanner.getCurrentIdentifierSource(); + + if (token.compareTo (TokenName.KEYWORD) > 0) { + problemReporter.phpKeywordWarning (new String[] {scanner.toStringAction(token) }, + scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition(), + referenceContext, + compilationUnit.compilationResult); + } + + getNextToken(); + } + + if (token == TokenName.LPAREN) { getNextToken(); - } else { + } + else { methodDecl.sourceEnd = scanner.getCurrentTokenStartPosition() - 1; throwSyntaxError("'(' expected in function declaration."); } - if (token != TokenNameRPAREN) { + + if (token != TokenName.RPAREN) { parameter_list(methodDecl); } - if (token != TokenNameRPAREN) { + + if (token != TokenName.RPAREN) { methodDecl.sourceEnd = scanner.getCurrentTokenStartPosition() - 1; throwSyntaxError("')' expected in function declaration."); - } else { + } + else { methodDecl.bodyStart = scanner.getCurrentTokenEndPosition() + 1; getNextToken(); } - } else { + } + else { methodDecl.selector = "".toCharArray(); methodDecl.sourceEnd = scanner.getCurrentTokenStartPosition() - 1; throwSyntaxError("Function name expected after keyword 'function'."); @@ -1832,20 +1997,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | non_empty_parameter_list ',' optional_class_type T_VARIABLE '=' // static_scalar char[] typeIdentifier = null; - if (token == TokenNameIdentifier || token == TokenNamearray - || token == TokenNameVariable || token == TokenNameAND) { + if (token == TokenName.IDENTIFIER || + token == TokenName.ARRAY || + token == TokenName.VARIABLE || + token == TokenName.OP_AND) { HashSet set = peekVariableSet(); + while (true) { - if (token == TokenNameIdentifier || token == TokenNamearray) {// feature - // req. - // #1254275 + if (token == TokenName.IDENTIFIER || token == TokenName.ARRAY) {// feature req. #1254275 typeIdentifier = scanner.getCurrentIdentifierSource(); getNextToken(); } - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); } - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { if (fMethodVariables != null) { VariableInfo info; if (methodDecl.type == MethodDeclaration.FUNCTION_DEFINITION) { @@ -1863,14 +2029,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } addVariableSet(set); getNextToken(); - if (token == TokenNameEQUAL) { + if (token == TokenName.EQUAL) { getNextToken(); static_scalar(); } } else { throwSyntaxError("Variable expected in parameter list."); } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -1890,7 +2056,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // private void parameterDeclaration() { // //variable // //variable-reference - // if (token == TokenNameAND) { + // if (token == TokenName.AND) { // getNextToken(); // if (isVariable()) { // getNextToken(); @@ -1899,43 +2065,42 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } // } // //variable '=' constant - // if (token == TokenNameVariable) { + // if (token == TokenName.VARIABLE) { // getNextToken(); - // if (token == TokenNameEQUAL) { + // if (token == TokenName.EQUAL) { // getNextToken(); // static_scalar(); // } // return; // } - // // if (token == TokenNamethis) { + // // if (token == TokenName.THIS) { // // throwSyntaxError("Reserved word '$this' not allowed in parameter // // declaration."); // // } // } private void labeledStatementList() { - if (token != TokenNamecase && token != TokenNamedefault) { + if (token != TokenName.CASE && token != TokenName.DEFAULT) { throwSyntaxError("'case' or 'default' expected."); } do { - if (token == TokenNamecase) { + if (token == TokenName.CASE) { getNextToken(); - expr(); // constant(); - if (token == TokenNameCOLON || token == TokenNameSEMICOLON) { + expr_without_variable (true, null, true); // constant(); + if (token == TokenName.COLON || token == TokenName.SEMICOLON) { getNextToken(); - if (token == TokenNameRBRACE) { - // empty case; assumes that the '}' token belongs to the - // wrapping + if (token == TokenName.RBRACE) { + // empty case; assumes that the '}' token belongs to the wrapping // switch statement - #1371992 break; } - if (token == TokenNamecase || token == TokenNamedefault) { + if (token == TokenName.CASE || token == TokenName.DEFAULT) { // empty case statement ? continue; } statementList(); } - // else if (token == TokenNameSEMICOLON) { + // else if (token == TokenName.SEMICOLON) { // setMarker( // "':' expected after 'case' keyword (Found token: " + // scanner.toStringAction(token) + ")", @@ -1943,7 +2108,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // scanner.getCurrentTokenEndPosition(), // INFO); // getNextToken(); - // if (token == TokenNamecase) { // empty case statement ? + // if (token == TokenName.CASE) { // empty case statement ? // continue; // } // statementList(); @@ -1952,24 +2117,23 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, throwSyntaxError("':' character expected after 'case' constant (Found token: " + scanner.toStringAction(token) + ")"); } - } else { // TokenNamedefault + } else { // TokenName.DEFAULT getNextToken(); - if (token == TokenNameCOLON || token == TokenNameSEMICOLON) { + if (token == TokenName.COLON || token == TokenName.SEMICOLON) { getNextToken(); - if (token == TokenNameRBRACE) { - // empty default case; ; assumes that the '}' token - // belongs to the + if (token == TokenName.RBRACE) { + // empty default case; ; assumes that the '}' token belongs to the // wrapping switch statement - #1371992 break; } - if (token != TokenNamecase) { + if (token != TokenName.CASE) { statementList(); } } else { throwSyntaxError("':' character expected after 'default'."); } } - } while (token == TokenNamecase || token == TokenNamedefault); + } while (token == TokenName.CASE || token == TokenName.DEFAULT); } private void ifStatementColon(IfStatement iState) { @@ -1983,7 +2147,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } finally { assignedVariableSet = removeIfVariableSet(); } - if (token == TokenNameelseif) { + if (token == TokenName.ELSEIF) { try { pushIfVariableSet(); new_elseif_list(iState); @@ -2009,11 +2173,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } } - if (token != TokenNameendif) { + if (token != TokenName.ENDIF) { throwSyntaxError("'endif' expected."); } getNextToken(); - if (token != TokenNameSEMICOLON && token != TokenNameINLINE_HTML) { + if (token != TokenName.SEMICOLON && token != TokenName.INLINE_HTML) { reportSyntaxError("';' expected after if-statement."); iState.sourceEnd = scanner.getCurrentTokenStartPosition(); } else { @@ -2034,7 +2198,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, assignedVariableSet = removeIfVariableSet(); } - if (token == TokenNameelseif) { + if (token == TokenName.ELSEIF) { try { pushIfVariableSet(); elseif_list(iState); @@ -2069,16 +2233,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ArrayList statementList = new ArrayList(); Expression e; Statement s; - while (token == TokenNameelseif) { + while (token == TokenName.ELSEIF) { getNextToken(); - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); } else { throwSyntaxError("'(' expected after 'elseif' keyword."); } e = expr(); conditionList.add(e); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); } else { throwSyntaxError("')' expected after 'elseif' condition."); @@ -2100,21 +2264,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, ArrayList statementList = new ArrayList(); Expression e; Block b; - while (token == TokenNameelseif) { + while (token == TokenName.ELSEIF) { getNextToken(); - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); } else { throwSyntaxError("'(' expected after 'elseif' keyword."); } e = expr(); conditionList.add(e); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); } else { throwSyntaxError("')' expected after 'elseif' condition."); } - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); } else { throwSyntaxError("':' expected after 'elseif' keyword."); @@ -2132,7 +2296,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void else_single(IfStatement iState) { // /* empty */ // T_ELSE statement - if (token == TokenNameelse) { + if (token == TokenName.ELSE) { getNextToken(); Statement s = statement(); iState.elseStatement = s; @@ -2146,9 +2310,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void new_else_single(IfStatement iState) { // /* empty */ // | T_ELSE ':' inner_statement_list - if (token == TokenNameelse) { + if (token == TokenName.ELSE) { getNextToken(); - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); } else { throwSyntaxError("':' expected after 'else' keyword."); @@ -2203,23 +2367,23 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // do { // elseifStatement(); // switch (token) { - // case TokenNameelse: + // case TokenName.else: // getNextToken(); - // if (token == TokenNameCOLON) { + // if (token == TokenName.COLON) { // getNextToken(); - // if (token != TokenNameendif) { + // if (token != TokenName.endif) { // statementList(); // } // return; // } else { - // if (token == TokenNameif) { //'else if' + // if (token == TokenName.if) { //'else if' // getNextToken(); // } else { // throwSyntaxError("':' expected after 'else'."); // } // } // break; - // case TokenNameelseif: + // case TokenName.elseif: // getNextToken(); // break; // default: @@ -2229,46 +2393,46 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } // private void elseifStatement() { - // if (token == TokenNameLPAREN) { + // if (token == TokenName.LPAREN) { // getNextToken(); // expr(); - // if (token != TokenNameRPAREN) { + // if (token != TokenName.RPAREN) { // throwSyntaxError("')' expected in else-if-statement."); // } // getNextToken(); - // if (token != TokenNameCOLON) { + // if (token != TokenName.COLON) { // throwSyntaxError("':' expected in else-if-statement."); // } // getNextToken(); - // if (token != TokenNameendif) { + // if (token != TokenName.endif) { // statementList(); // } // } // } private void switchStatement() { - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { // ':' [labeled-statement-list] 'endswitch' ';' getNextToken(); labeledStatementList(); - if (token != TokenNameendswitch) { + if (token != TokenName.ENDSWITCH) { throwSyntaxError("'endswitch' expected."); } getNextToken(); - if (token != TokenNameSEMICOLON && token != TokenNameINLINE_HTML) { + if (token != TokenName.SEMICOLON && token != TokenName.INLINE_HTML) { throwSyntaxError("';' expected after switch-statement."); } getNextToken(); } else { // '{' [labeled-statement-list] '}' - if (token != TokenNameLBRACE) { + if (token != TokenName.LBRACE) { throwSyntaxError("'{' expected in switch statement."); } getNextToken(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { labeledStatementList(); } - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in switch statement."); } getNextToken(); @@ -2276,14 +2440,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } private void forStatement() { - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); statementList(); - if (token != TokenNameendfor) { + if (token != TokenName.ENDFOR) { throwSyntaxError("'endfor' expected."); } getNextToken(); - if (token != TokenNameSEMICOLON && token != TokenNameINLINE_HTML) { + if (token != TokenName.SEMICOLON && token != TokenName.INLINE_HTML) { throwSyntaxError("';' expected after for-statement."); } getNextToken(); @@ -2294,14 +2458,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void whileStatement() { // ':' statement-list 'endwhile' ';' - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); statementList(); - if (token != TokenNameendwhile) { + if (token != TokenName.ENDWHILE) { throwSyntaxError("'endwhile' expected."); } getNextToken(); - if (token != TokenNameSEMICOLON && token != TokenNameINLINE_HTML) { + if (token != TokenName.SEMICOLON && token != TokenName.INLINE_HTML) { throwSyntaxError("';' expected after while-statement."); } getNextToken(); @@ -2311,14 +2475,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } private void foreachStatement() { - if (token == TokenNameCOLON) { + if (token == TokenName.COLON) { getNextToken(); statementList(); - if (token != TokenNameendforeach) { + if (token != TokenName.ENDFOREACH) { throwSyntaxError("'endforeach' expected."); } getNextToken(); - if (token != TokenNameSEMICOLON && token != TokenNameINLINE_HTML) { + if (token != TokenName.SEMICOLON && token != TokenName.INLINE_HTML) { throwSyntaxError("';' expected after foreach-statement."); } getNextToken(); @@ -2328,25 +2492,44 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } // private void exitStatus() { - // if (token == TokenNameLPAREN) { + // if (token == TokenName.LPAREN) { // getNextToken(); // } else { // throwSyntaxError("'(' expected in 'exit-status'."); // } - // if (token != TokenNameRPAREN) { + // if (token != TokenName.RPAREN) { // expression(); // } - // if (token == TokenNameRPAREN) { + // if (token == TokenName.RPAREN) { // getNextToken(); // } else { // throwSyntaxError("')' expected after 'exit-status'."); // } // } + /** + * + */ + private void namespacePath () { + do { + expr_without_variable (true, null, false); + + if (token == TokenName.BACKSLASH) { + getNextToken(); + } else { + break; + } + } while (true); + } + + /** + * + */ private void expressionList() { do { - expr(); - if (token == TokenNameCOMMA) { - getNextToken(); + expr_without_variable (true, null, false); + + if (token == TokenName.COMMA) { // If it's a list of (comma separated) expressions + getNextToken(); // read all in, untill no more found } else { break; } @@ -2354,24 +2537,24 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } private Expression expr() { - // r_variable - // | expr_without_variable - // if (token!=TokenNameEOF) { - if (Scanner.TRACE) { - System.out.println("TRACE: expr()"); - } - return expr_without_variable(true, null); - // } + return expr_without_variable(true, null, false); } - private Expression expr_without_variable(boolean only_variable, - UninitializedVariableHandler initHandler) { - int exprSourceStart = scanner.getCurrentTokenStartPosition(); - int exprSourceEnd = scanner.getCurrentTokenEndPosition(); - Expression expression = new Expression(); + /** + * + * @param only_variable + * @param initHandler + */ + private Expression expr_without_variable (boolean only_variable, + UninitializedVariableHandler initHandler, + boolean bColonAllowed) { + int exprSourceStart = scanner.getCurrentTokenStartPosition(); + int exprSourceEnd = scanner.getCurrentTokenEndPosition(); + Expression expression = new Expression(); + expression.sourceStart = exprSourceStart; - // default, may be overwritten - expression.sourceEnd = exprSourceEnd; + expression.sourceEnd = exprSourceEnd; // default, may be overwritten + try { // internal_functions_in_yacc // | T_CLONE expr @@ -2442,461 +2625,489 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: expr_without_variable() PART 1"); } + switch (token) { - case TokenNameisset: - // T_ISSET '(' isset_variables ')' - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'isset'"); - } - getNextToken(); - isset_variables(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'isset'"); - } - getNextToken(); - break; - case TokenNameempty: - getNextToken(); - if (token != TokenNameLPAREN) { - throwSyntaxError("'(' expected after keyword 'empty'"); - } - getNextToken(); - variable(true, false); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after keyword 'empty'"); - } - getNextToken(); - break; - case TokenNameeval: - case TokenNameinclude: - case TokenNameinclude_once: - case TokenNamerequire: - case TokenNamerequire_once: - internal_functions_in_yacc(); - break; - // | '(' expr ')' - case TokenNameLPAREN: - getNextToken(); - expr(); - if (token == TokenNameRPAREN) { + case ISSET: + // T_ISSET '(' isset_variables ')' getNextToken(); - } else { - throwSyntaxError("')' expected in expression."); - } - break; - // | T_CLONE expr - // | T_PRINT expr - // | '@' expr - // | '+' expr - // | '-' expr - // | '!' expr - // | '~' expr - // | T_INT_CAST expr - // | T_DOUBLE_CAST expr - // | T_STRING_CAST expr - // | T_ARRAY_CAST expr - // | T_OBJECT_CAST expr - // | T_BOOL_CAST expr - // | T_UNSET_CAST expr - case TokenNameclone: - case TokenNameprint: - case TokenNameAT: - case TokenNamePLUS: - case TokenNameMINUS: - case TokenNameNOT: - case TokenNameTWIDDLE: - case TokenNameintCAST: - case TokenNamedoubleCAST: - case TokenNamestringCAST: - case TokenNamearrayCAST: - case TokenNameobjectCAST: - case TokenNameboolCAST: - case TokenNameunsetCAST: - getNextToken(); - expr(); - break; - case TokenNameexit: - getNextToken(); - exit_expr(); - break; - // scalar: - // T_STRING - // | T_STRING_VARNAME - // | class_constant - // | T_START_HEREDOC encaps_list T_END_HEREDOC - // | '`' encaps_list '`' - // | common_scalar - // | '`' encaps_list '`' - // case TokenNameEncapsedString0: - // scanner.encapsedStringStack.push(new Character('`')); - // getNextToken(); - // try { - // if (token == TokenNameEncapsedString0) { - // } else { - // encaps_list(); - // if (token != TokenNameEncapsedString0) { - // throwSyntaxError("\'`\' expected at end of string" + "(Found - // token: " + - // scanner.toStringAction(token) + " )"); - // } - // } - // } finally { - // scanner.encapsedStringStack.pop(); - // getNextToken(); - // } - // break; - // // | '\'' encaps_list '\'' - // case TokenNameEncapsedString1: - // scanner.encapsedStringStack.push(new Character('\'')); - // getNextToken(); - // try { - // exprSourceStart = scanner.getCurrentTokenStartPosition(); - // if (token == TokenNameEncapsedString1) { - // expression = new - // StringLiteralSQ(scanner.getCurrentStringLiteralSource(exprSourceStart), - // exprSourceStart, scanner - // .getCurrentTokenEndPosition()); - // } else { - // encaps_list(); - // if (token != TokenNameEncapsedString1) { - // throwSyntaxError("\'\'\' expected at end of string" + "(Found - // token: " - // + scanner.toStringAction(token) + " )"); - // } else { - // expression = new - // StringLiteralSQ(scanner.getCurrentStringLiteralSource(exprSourceStart), - // exprSourceStart, scanner - // .getCurrentTokenEndPosition()); - // } - // } - // } finally { - // scanner.encapsedStringStack.pop(); - // getNextToken(); - // } - // break; - // //| '"' encaps_list '"' - // case TokenNameEncapsedString2: - // scanner.encapsedStringStack.push(new Character('"')); - // getNextToken(); - // try { - // exprSourceStart = scanner.getCurrentTokenStartPosition(); - // if (token == TokenNameEncapsedString2) { - // expression = new - // StringLiteralDQ(scanner.getCurrentStringLiteralSource(exprSourceStart), - // exprSourceStart, scanner - // .getCurrentTokenEndPosition()); - // } else { - // encaps_list(); - // if (token != TokenNameEncapsedString2) { - // throwSyntaxError("'\"' expected at end of string" + "(Found - // token: " + - // scanner.toStringAction(token) + " )"); - // } else { - // expression = new - // StringLiteralDQ(scanner.getCurrentStringLiteralSource(exprSourceStart), - // exprSourceStart, scanner - // .getCurrentTokenEndPosition()); - // } - // } - // } finally { - // scanner.encapsedStringStack.pop(); - // getNextToken(); - // } - // break; - case TokenNameStringDoubleQuote: - expression = new StringLiteralDQ(scanner - .getCurrentStringLiteralSource(), scanner - .getCurrentTokenStartPosition(), scanner - .getCurrentTokenEndPosition()); - common_scalar(); - break; - case TokenNameStringSingleQuote: - expression = new StringLiteralSQ(scanner - .getCurrentStringLiteralSource(), scanner - .getCurrentTokenStartPosition(), scanner - .getCurrentTokenEndPosition()); - common_scalar(); - break; - case TokenNameIntegerLiteral: - case TokenNameDoubleLiteral: - case TokenNameStringInterpolated: - case TokenNameFILE: - case TokenNameLINE: - case TokenNameCLASS_C: - case TokenNameMETHOD_C: - case TokenNameFUNC_C: - common_scalar(); - break; - case TokenNameHEREDOC: - getNextToken(); - break; - case TokenNamearray: - // T_ARRAY '(' array_pair_list ')' - getNextToken(); - if (token == TokenNameLPAREN) { - getNextToken(); - if (token == TokenNameRPAREN) { - getNextToken(); - break; + if (token != TokenName.LPAREN) { + throwSyntaxError("'(' expected after keyword 'isset'"); } - array_pair_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' or ',' expected after keyword 'array'" - + "(Found token: " - + scanner.toStringAction(token) + ")"); + getNextToken(); + isset_variables(); + if (token != TokenName.RPAREN) { + throwSyntaxError("')' expected after keyword 'isset'"); } getNextToken(); - } else { - throwSyntaxError("'(' expected after keyword 'array'" - + "(Found token: " + scanner.toStringAction(token) - + ")"); - } - break; - case TokenNamelist: - // | T_LIST '(' assignment_list ')' '=' expr - getNextToken(); - if (token == TokenNameLPAREN) { + break; + case EMPTY: getNextToken(); - assignment_list(); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected after 'list' keyword."); + if (token != TokenName.LPAREN) { + throwSyntaxError("'(' expected after keyword 'empty'"); } getNextToken(); - if (token != TokenNameEQUAL) { - throwSyntaxError("'=' expected after 'list' keyword."); + variable(true, false); + if (token != TokenName.RPAREN) { + throwSyntaxError("')' expected after keyword 'empty'"); } getNextToken(); + break; + case EVAL: + case INCLUDE: + case INCLUDE_ONCE: + case REQUIRE: + case REQUIRE_ONCE: + internal_functions_in_yacc(); + break; + + // | '(' expr ')' + case LPAREN: + getNextToken(); expr(); - } else { - throwSyntaxError("'(' expected after 'list' keyword."); - } - break; - case TokenNamenew: - // | T_NEW class_name_reference ctor_arguments - getNextToken(); - Expression typeRef = class_name_reference(); - ctor_arguments(); - if (typeRef != null) { - expression = typeRef; - } - break; - // | T_INC rw_variable - // | T_DEC rw_variable - case TokenNamePLUS_PLUS: - case TokenNameMINUS_MINUS: - getNextToken(); - rw_variable(); - break; - // | variable '=' expr - // | variable '=' '&' variable - // | variable '=' '&' T_NEW class_name_reference ctor_arguments - // | variable T_PLUS_EQUAL expr - // | variable T_MINUS_EQUAL expr - // | variable T_MUL_EQUAL expr - // | variable T_DIV_EQUAL expr - // | variable T_CONCAT_EQUAL expr - // | variable T_MOD_EQUAL expr - // | variable T_AND_EQUAL expr - // | variable T_OR_EQUAL expr - // | variable T_XOR_EQUAL expr - // | variable T_SL_EQUAL expr - // | variable T_SR_EQUAL expr - // | rw_variable T_INC - // | rw_variable T_DEC - case TokenNameIdentifier: - case TokenNameVariable: - case TokenNameDOLLAR: - Expression lhs = null; - boolean rememberedVar = false; - if (token == TokenNameIdentifier) { - lhs = identifier(true, true); - if (lhs != null) { - expression = lhs; + if (token == TokenName.RPAREN) { + getNextToken(); + } else { + throwSyntaxError("')' expected in expression."); } - } else { - lhs = variable(true, true); - if (lhs != null) { - expression = lhs; + break; + // | T_CLONE expr + // | T_PRINT expr + // | '@' expr + // | '+' expr + // | '-' expr + // | '!' expr + // | '~' expr + // | T_INT_CAST expr + // | T_DOUBLE_CAST expr + // | T_STRING_CAST expr + // | T_ARRAY_CAST expr + // | T_OBJECT_CAST expr + // | T_BOOL_CAST expr + // | T_UNSET_CAST expr + case OP_AT: + case CLONE: + case PRINT: + case PLUS: + case MINUS: + case NOT: + case TWIDDLE: + case INTCAST: + case DOUBLECAST: + case STRINGCAST: + case ARRAYCAST: + case OBJECTCAST: + case BOOLCAST: + case UNSETCAST: + getNextToken(); + expr_without_variable (only_variable, initHandler, bColonAllowed); + break; + case EXIT: + getNextToken(); + exit_expr(); + break; + // scalar: + // T_STRING + // | T_STRING_VARNAME + // | class_constant + // | T_START_HEREDOC encaps_list T_END_HEREDOC + // | '`' encaps_list '`' + // | common_scalar + // | '`' encaps_list '`' + // case TokenName.EncapsedString0: + // scanner.encapsedStringStack.push(new Character('`')); + // getNextToken(); + // try { + // if (token == TokenName.EncapsedString0) { + // } else { + // encaps_list(); + // if (token != TokenName.EncapsedString0) { + // throwSyntaxError("\'`\' expected at end of string" + "(Found + // token: " + + // scanner.toStringAction(token) + " )"); + // } + // } + // } finally { + // scanner.encapsedStringStack.pop(); + // getNextToken(); + // } + // break; + // // | '\'' encaps_list '\'' + // case TokenName.EncapsedString1: + // scanner.encapsedStringStack.push(new Character('\'')); + // getNextToken(); + // try { + // exprSourceStart = scanner.getCurrentTokenStartPosition(); + // if (token == TokenName.EncapsedString1) { + // expression = new + // StringLiteralSQ(scanner.getCurrentStringLiteralSource(exprSourceStart), + // exprSourceStart, scanner + // .getCurrentTokenEndPosition()); + // } else { + // encaps_list(); + // if (token != TokenName.EncapsedString1) { + // throwSyntaxError("\'\'\' expected at end of string" + "(Found + // token: " + // + scanner.toStringAction(token) + " )"); + // } else { + // expression = new + // StringLiteralSQ(scanner.getCurrentStringLiteralSource(exprSourceStart), + // exprSourceStart, scanner + // .getCurrentTokenEndPosition()); + // } + // } + // } finally { + // scanner.encapsedStringStack.pop(); + // getNextToken(); + // } + // break; + // //| '"' encaps_list '"' + // case TokenName.EncapsedString2: + // scanner.encapsedStringStack.push(new Character('"')); + // getNextToken(); + // try { + // exprSourceStart = scanner.getCurrentTokenStartPosition(); + // if (token == TokenName.EncapsedString2) { + // expression = new + // StringLiteralDQ(scanner.getCurrentStringLiteralSource(exprSourceStart), + // exprSourceStart, scanner + // .getCurrentTokenEndPosition()); + // } else { + // encaps_list(); + // if (token != TokenName.EncapsedString2) { + // throwSyntaxError("'\"' expected at end of string" + "(Found + // token: " + + // scanner.toStringAction(token) + " )"); + // } else { + // expression = new + // StringLiteralDQ(scanner.getCurrentStringLiteralSource(exprSourceStart), + // exprSourceStart, scanner + // .getCurrentTokenEndPosition()); + // } + // } + // } finally { + // scanner.encapsedStringStack.pop(); + // getNextToken(); + // } + // break; + case STRINGDOUBLEQUOTE: + expression = new StringLiteralDQ (scanner.getCurrentStringLiteralSource(), + scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition()); + common_scalar(); + break; + case STRINGSINGLEQUOTE: + expression = new StringLiteralSQ (scanner.getCurrentStringLiteralSource(), + scanner.getCurrentTokenStartPosition(), + scanner.getCurrentTokenEndPosition()); + common_scalar(); + break; + case INTEGERLITERAL: + case DOUBLELITERAL: + case STRINGINTERPOLATED: + case FILE: + case LINE: + case CLASS_C: + case METHOD_C: + case FUNC_C: + common_scalar(); + break; + case HEREDOC: + getNextToken(); + break; + case ARRAY: + // T_ARRAY '(' array_pair_list ')' + getNextToken(); + if (token == TokenName.LPAREN) { + getNextToken(); + if (token == TokenName.RPAREN) { + getNextToken(); + break; + } + array_pair_list(); + if (token != TokenName.RPAREN) { + throwSyntaxError("')' or ',' expected after keyword 'array'" + + "(Found token: " + + scanner.toStringAction(token) + ")"); + } + getNextToken(); + } else { + throwSyntaxError("'(' expected after keyword 'array'" + + "(Found token: " + scanner.toStringAction(token) + + ")"); } - if (lhs != null && lhs instanceof FieldReference - && token != TokenNameEQUAL - && token != TokenNamePLUS_EQUAL - && token != TokenNameMINUS_EQUAL - && token != TokenNameMULTIPLY_EQUAL - && token != TokenNameDIVIDE_EQUAL - && token != TokenNameDOT_EQUAL - && token != TokenNameREMAINDER_EQUAL - && token != TokenNameAND_EQUAL - && token != TokenNameOR_EQUAL - && token != TokenNameXOR_EQUAL - && token != TokenNameRIGHT_SHIFT_EQUAL - && token != TokenNameLEFT_SHIFT_EQUAL) { - FieldReference ref = (FieldReference) lhs; - if (!containsVariableSet(ref.token)) { - if (null == initHandler - || initHandler.reportError()) { - problemReporter.uninitializedLocalVariable( - new String(ref.token), ref.sourceStart, - ref.sourceEnd, referenceContext, - compilationUnit.compilationResult); - } - addVariableSet(ref.token); + break; + case LIST: + // | T_LIST '(' assignment_list ')' '=' expr + getNextToken(); + if (token == TokenName.LPAREN) { + getNextToken(); + assignment_list(); + if (token != TokenName.RPAREN) { + throwSyntaxError("')' expected after 'list' keyword."); } + getNextToken(); + if (token != TokenName.EQUAL) { + throwSyntaxError("'=' expected after 'list' keyword."); + } + getNextToken(); + expr(); + } else { + throwSyntaxError("'(' expected after 'list' keyword."); } - } - switch (token) { - case TokenNameEQUAL: - if (lhs != null && lhs instanceof FieldReference) { - addVariableSet(((FieldReference) lhs).token); + break; + case NEW: + // | T_NEW class_name_reference ctor_arguments + getNextToken(); + Expression typeRef = class_name_reference(); + ctor_arguments(); + if (typeRef != null) { + expression = typeRef; } + break; + // | T_INC rw_variable + // | T_DEC rw_variable + case PLUS_PLUS: + case MINUS_MINUS: getNextToken(); - if (token == TokenNameAND) { - getNextToken(); - if (token == TokenNamenew) { - // | variable '=' '&' T_NEW class_name_reference - // ctor_arguments - getNextToken(); - SingleTypeReference classRef = class_name_reference(); - ctor_arguments(); - if (classRef != null) { - if (lhs != null - && lhs instanceof FieldReference) { - // example: - // $var = & new Object(); - if (fMethodVariables != null) { - VariableInfo lhsInfo = new VariableInfo( - ((FieldReference) lhs).sourceStart); - lhsInfo.reference = classRef; - lhsInfo.typeIdentifier = classRef.token; - fMethodVariables.put(new String( - ((FieldReference) lhs).token), - lhsInfo); - rememberedVar = true; - } + rw_variable(); + break; + // | variable '=' expr + // | variable '=' '&' variable + // | variable '=' '&' T_NEW class_name_reference ctor_arguments + // | variable T_PLUS_EQUAL expr + // | variable T_MINUS_EQUAL expr + // | variable T_MUL_EQUAL expr + // | variable T_DIV_EQUAL expr + // | variable T_CONCAT_EQUAL expr + // | variable T_MOD_EQUAL expr + // | variable T_AND_EQUAL expr + // | variable T_OR_EQUAL expr + // | variable T_XOR_EQUAL expr + // | variable T_SL_EQUAL expr + // | variable T_SR_EQUAL expr + // | rw_variable T_INC + // | rw_variable T_DEC + case IDENTIFIER: + case VARIABLE: + case DOLLAR: + Expression lhs = null; + boolean rememberedVar = false; + + if (token == TokenName.IDENTIFIER) { + lhs = identifier(true, true, bColonAllowed); + if (lhs != null) { + expression = lhs; + } + } else { + lhs = variable(true, true); + + if (lhs != null) { + expression = lhs; + } + + if (lhs != null && + lhs instanceof FieldReference && + token != TokenName.EQUAL && + token != TokenName.PLUS_EQUAL && + token != TokenName.MINUS_EQUAL && + token != TokenName.MULTIPLY_EQUAL && + token != TokenName.DIVIDE_EQUAL && + token != TokenName.DOT_EQUAL && + token != TokenName.REMAINDER_EQUAL && + token != TokenName.AND_EQUAL && + token != TokenName.OR_EQUAL && + token != TokenName.XOR_EQUAL && + token != TokenName.RIGHT_SHIFT_EQUAL && + token != TokenName.LEFT_SHIFT_EQUAL) { + + FieldReference ref = (FieldReference) lhs; + + if (!containsVariableSet(ref.token)) { + if (null == initHandler || initHandler.reportError()) { + problemReporter.uninitializedLocalVariable( + new String(ref.token), ref.sourceStart, + ref.sourceEnd, referenceContext, + compilationUnit.compilationResult); } + addVariableSet(ref.token); } - } else { - Expression rhs = variable(false, false); - if (rhs != null && rhs instanceof FieldReference - && lhs != null - && lhs instanceof FieldReference) { - // example: - // $var = &$ref; - if (fMethodVariables != null) { - VariableInfo rhsInfo = (VariableInfo) fMethodVariables - .get(((FieldReference) rhs).token); - if (rhsInfo != null - && rhsInfo.reference != null) { - VariableInfo lhsInfo = new VariableInfo( - ((FieldReference) lhs).sourceStart); - lhsInfo.reference = rhsInfo.reference; - lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; - fMethodVariables.put(new String( - ((FieldReference) lhs).token), - lhsInfo); - rememberedVar = true; + } + } + + switch (token) { + case EQUAL: + if (lhs != null && lhs instanceof FieldReference) { + addVariableSet(((FieldReference) lhs).token); + } + getNextToken(); + if (token == TokenName.OP_AND) { + getNextToken(); + if (token == TokenName.NEW) { + // | variable '=' '&' T_NEW class_name_reference + // ctor_arguments + getNextToken(); + SingleTypeReference classRef = class_name_reference(); + ctor_arguments(); + if (classRef != null) { + if (lhs != null + && lhs instanceof FieldReference) { + // example: + // $var = & new Object(); + if (fMethodVariables != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); + lhsInfo.reference = classRef; + lhsInfo.typeIdentifier = classRef.token; + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); + rememberedVar = true; + } + } + } + } else { + Expression rhs = variable(false, false); + if (rhs != null && rhs instanceof FieldReference + && lhs != null + && lhs instanceof FieldReference) { + // example: + // $var = &$ref; + if (fMethodVariables != null) { + VariableInfo rhsInfo = (VariableInfo) fMethodVariables + .get(((FieldReference) rhs).token); + if (rhsInfo != null + && rhsInfo.reference != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); + lhsInfo.reference = rhsInfo.reference; + lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); + rememberedVar = true; + } + } } } - } - } - } else { - Expression rhs = expr(); - if (lhs != null && lhs instanceof FieldReference) { - if (rhs != null && rhs instanceof FieldReference) { - // example: - // $var = $ref; - if (fMethodVariables != null) { - VariableInfo rhsInfo = (VariableInfo) fMethodVariables - .get(((FieldReference) rhs).token); - if (rhsInfo != null - && rhsInfo.reference != null) { - VariableInfo lhsInfo = new VariableInfo( - ((FieldReference) lhs).sourceStart); - lhsInfo.reference = rhsInfo.reference; - lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; - fMethodVariables.put(new String( - ((FieldReference) lhs).token), - lhsInfo); - rememberedVar = true; + } else { + Expression rhs = expr_without_variable (only_variable, initHandler, bColonAllowed); + + if (lhs != null && lhs instanceof FieldReference) { + if (rhs != null && rhs instanceof FieldReference) { + // example: + // $var = $ref; + if (fMethodVariables != null) { + VariableInfo rhsInfo = (VariableInfo) fMethodVariables + .get(((FieldReference) rhs).token); + if (rhsInfo != null + && rhsInfo.reference != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); + lhsInfo.reference = rhsInfo.reference; + lhsInfo.typeIdentifier = rhsInfo.typeIdentifier; + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); + rememberedVar = true; + } + } + } else if (rhs != null + && rhs instanceof SingleTypeReference) { + // example: + // $var = new Object(); + if (fMethodVariables != null) { + VariableInfo lhsInfo = new VariableInfo( + ((FieldReference) lhs).sourceStart); + lhsInfo.reference = (SingleTypeReference) rhs; + lhsInfo.typeIdentifier = ((SingleTypeReference) rhs).token; + fMethodVariables.put(new String( + ((FieldReference) lhs).token), + lhsInfo); + rememberedVar = true; + } } } - } else if (rhs != null - && rhs instanceof SingleTypeReference) { - // example: - // $var = new Object(); + } + if (rememberedVar == false && lhs != null + && lhs instanceof FieldReference) { if (fMethodVariables != null) { VariableInfo lhsInfo = new VariableInfo( ((FieldReference) lhs).sourceStart); - lhsInfo.reference = (SingleTypeReference) rhs; - lhsInfo.typeIdentifier = ((SingleTypeReference) rhs).token; fMethodVariables.put(new String( - ((FieldReference) lhs).token), - lhsInfo); - rememberedVar = true; + ((FieldReference) lhs).token), lhsInfo); } } - } - } - if (rememberedVar == false && lhs != null - && lhs instanceof FieldReference) { - if (fMethodVariables != null) { - VariableInfo lhsInfo = new VariableInfo( - ((FieldReference) lhs).sourceStart); - fMethodVariables.put(new String( - ((FieldReference) lhs).token), lhsInfo); - } - } + break; + case PLUS_EQUAL: + case MINUS_EQUAL: + case MULTIPLY_EQUAL: + case DIVIDE_EQUAL: + case DOT_EQUAL: + case REMAINDER_EQUAL: + case AND_EQUAL: + case OR_EQUAL: + case XOR_EQUAL: + case RIGHT_SHIFT_EQUAL: + case LEFT_SHIFT_EQUAL: + if (lhs != null && lhs instanceof FieldReference) { + addVariableSet(((FieldReference) lhs).token); + } + getNextToken(); + expr_without_variable (only_variable, initHandler, bColonAllowed); + break; + case PLUS_PLUS: + case MINUS_MINUS: + getNextToken(); + break; + default: + if (!only_variable) { + throwSyntaxError("Variable expression not allowed (found token '" + + scanner.toStringAction(token) + "')."); + } + if (lhs != null) { + expression = lhs; + } + } // case DOLLAR, VARIABLE, IDENTIFIER: switch token break; - case TokenNamePLUS_EQUAL: - case TokenNameMINUS_EQUAL: - case TokenNameMULTIPLY_EQUAL: - case TokenNameDIVIDE_EQUAL: - case TokenNameDOT_EQUAL: - case TokenNameREMAINDER_EQUAL: - case TokenNameAND_EQUAL: - case TokenNameOR_EQUAL: - case TokenNameXOR_EQUAL: - case TokenNameRIGHT_SHIFT_EQUAL: - case TokenNameLEFT_SHIFT_EQUAL: - if (lhs != null && lhs instanceof FieldReference) { - addVariableSet(((FieldReference) lhs).token); + + case FUNCTION: + MethodDeclaration methodDecl = new MethodDeclaration (this.compilationUnit.compilationResult); + methodDecl.declarationSourceStart = scanner.getCurrentTokenStartPosition(); + methodDecl.modifiers = AccDefault; + methodDecl.type = MethodDeclaration.FUNCTION_DEFINITION; + try { + getNextToken(); + functionDefinition(methodDecl); + } finally { + int sourceEnd = methodDecl.sourceEnd; + if (sourceEnd <= 0 || methodDecl.declarationSourceStart > sourceEnd) { + sourceEnd = methodDecl.declarationSourceStart + 1; + } + methodDecl.declarationSourceEnd = sourceEnd; + methodDecl.sourceEnd = sourceEnd; } - getNextToken(); - expr(); - break; - case TokenNamePLUS_PLUS: - case TokenNameMINUS_MINUS: - getNextToken(); break; + default: - if (!only_variable) { - throwSyntaxError("Variable expression not allowed (found token '" - + scanner.toStringAction(token) + "')."); - } - if (lhs != null) { - expression = lhs; - } - } - break; - default: - if (token != TokenNameINLINE_HTML) { - if (token > TokenNameKEYWORD) { - getNextToken(); - break; - } else { - // System.out.println(scanner.getCurrentTokenStartPosition()); - // System.out.println(scanner.getCurrentTokenEndPosition()); + if (token != TokenName.INLINE_HTML) { + if (token.compareTo (TokenName.KEYWORD) > 0) { + getNextToken(); + break; + } else { + // System.out.println(scanner.getCurrentTokenStartPosition()); + // System.out.println(scanner.getCurrentTokenEndPosition()); - throwSyntaxError("Error in expression (found token '" - + scanner.toStringAction(token) + "')."); + throwSyntaxError("Error in expression (found token '" + + scanner.toStringAction(token) + "')."); + } } - } - return expression; - } + return expression; + } // switch token + if (Scanner.TRACE) { System.out.println("TRACE: expr_without_variable() PART 2"); } + // | expr T_BOOLEAN_OR expr // | expr T_BOOLEAN_AND expr // | expr T_LOGICAL_OR expr @@ -2923,80 +3134,140 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | expr T_IS_GREATER_OR_EQUAL expr while (true) { switch (token) { - case TokenNameOR_OR: - getNextToken(); - expression = new OR_OR_Expression(expression, expr(), token); - break; - case TokenNameAND_AND: - getNextToken(); - expression = new AND_AND_Expression(expression, expr(), - token); - break; - case TokenNameEQUAL_EQUAL: - getNextToken(); - expression = new EqualExpression(expression, expr(), token); - break; - case TokenNameand: - case TokenNameor: - case TokenNamexor: - case TokenNameAND: - case TokenNameOR: - case TokenNameXOR: - case TokenNameDOT: - case TokenNamePLUS: - case TokenNameMINUS: - case TokenNameMULTIPLY: - case TokenNameDIVIDE: - case TokenNameREMAINDER: - case TokenNameLEFT_SHIFT: - case TokenNameRIGHT_SHIFT: - case TokenNameEQUAL_EQUAL_EQUAL: - case TokenNameNOT_EQUAL_EQUAL: - case TokenNameNOT_EQUAL: - case TokenNameLESS: - case TokenNameLESS_EQUAL: - case TokenNameGREATER: - case TokenNameGREATER_EQUAL: - getNextToken(); - expression = new BinaryExpression(expression, expr(), token); - break; - // | expr T_INSTANCEOF class_name_reference - // | expr '?' expr ':' expr - case TokenNameinstanceof: - getNextToken(); - TypeReference classRef = class_name_reference(); - if (classRef != null) { - expression = new InstanceOfExpression(expression, - classRef, OperatorIds.INSTANCEOF); - expression.sourceStart = exprSourceStart; - expression.sourceEnd = scanner - .getCurrentTokenEndPosition(); - } - break; - case TokenNameQUESTION: - getNextToken(); - Expression valueIfTrue = expr(); - if (token != TokenNameCOLON) { - throwSyntaxError("':' expected in conditional expression."); - } - getNextToken(); - Expression valueIfFalse = expr(); + case OR_OR: + getNextToken(); + expression = new OR_OR_Expression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.OR_OR); + break; + case AND_AND: + getNextToken(); + expression = new AND_AND_Expression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.AND_AND); + break; + case EQUAL_EQUAL: + getNextToken(); + expression = new EqualExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.EQUAL_EQUAL); + break; + case OP_AND: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.AND); + break; + case OP_OR: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.OR); + break; + case OP_XOR: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.XOR); + break; + case OP_AND_OLD: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.AND); + break; + case OP_OR_OLD: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.OR); + break; + case OP_XOR_OLD: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.XOR); + break; + case DOT: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.TWIDDLE); + break; + case PLUS: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.PLUS); + break; + case MINUS: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.MINUS); + break; + case MULTIPLY: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.MULTIPLY); + break; + case DIVIDE: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.DIVIDE); + break; + case REMAINDER: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.REMAINDER); + break; + case LEFT_SHIFT: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.LEFT_SHIFT); + break; + case RIGHT_SHIFT: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.RIGHT_SHIFT); + break; + case EQUAL_EQUAL_EQUAL: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.EQUAL_EQUAL); + break; + case NOT_EQUAL_EQUAL: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.NOT_EQUAL); + break; + case NOT_EQUAL: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.NOT_EQUAL); + break; + case LESS: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.LESS); + break; + case LESS_EQUAL: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.LESS_EQUAL); + break; + case GREATER: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.GREATER); + break; + case GREATER_EQUAL: + getNextToken(); + expression = new BinaryExpression(expression, expr_without_variable (only_variable, initHandler, bColonAllowed), OperatorIds.GREATER_EQUAL); + break; + // | expr T_INSTANCEOF class_name_reference + // | expr '?' expr ':' expr + case INSTANCEOF: + getNextToken(); + TypeReference classRef = class_name_reference(); + + if (classRef != null) { + expression = new InstanceOfExpression (expression, classRef, OperatorIds.INSTANCEOF); + expression.sourceStart = exprSourceStart; + expression.sourceEnd = scanner.getCurrentTokenEndPosition(); + } + break; + case QUESTION: + getNextToken(); + Expression valueIfTrue = expr_without_variable (true, null, true); + if (token != TokenName.COLON) { + throwSyntaxError("':' expected in conditional expression."); + } + getNextToken(); + Expression valueIfFalse = expr(); - expression = new ConditionalExpression(expression, - valueIfTrue, valueIfFalse); - break; - default: - return expression; - } - } + expression = new ConditionalExpression(expression, + valueIfTrue, valueIfFalse); + break; + default: + return expression; + } // switch + } // while (true) } catch (SyntaxError e) { // try to find next token after expression with errors: - if (token == TokenNameSEMICOLON) { + if (token == TokenName.SEMICOLON) { getNextToken(); return expression; } - if (token == TokenNameRBRACE || token == TokenNameRPAREN - || token == TokenNameRBRACKET) { + + if (token == TokenName.RBRACE || + token == TokenName.RPAREN || + token == TokenName.RBRACKET) { getNextToken(); return expression; } @@ -3004,6 +3275,9 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } + /** + * + */ private SingleTypeReference class_name_reference() { // class_name_reference: // T_STRING @@ -3012,15 +3286,15 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: class_name_reference()"); } - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { ref = new SingleTypeReference(scanner.getCurrentIdentifierSource(), scanner.getCurrentTokenStartPosition()); int pos = scanner.currentPosition; getNextToken(); - if (token == TokenNamePAAMAYIM_NEKUDOTAYIM) { + if (token == TokenName.PAAMAYIM_NEKUDOTAYIM) { // Not terminated by T_STRING, reduce to dynamic_class_name_reference scanner.currentPosition = pos; - token = TokenNameIdentifier; + token = TokenName.IDENTIFIER; ref = null; dynamic_class_name_reference(); } @@ -3040,7 +3314,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, System.out.println("TRACE: dynamic_class_name_reference()"); } base_variable(true); - if (token == TokenNameMINUS_GREATER) { + if (token == TokenName.MINUS_GREATER) { getNextToken(); object_property(); dynamic_class_name_variable_properties(); @@ -3056,7 +3330,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, System.out .println("TRACE: dynamic_class_name_variable_properties()"); } - while (token == TokenNameMINUS_GREATER) { + while (token == TokenName.MINUS_GREATER) { dynamic_class_name_variable_property(); } } @@ -3067,7 +3341,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: dynamic_class_name_variable_property()"); } - if (token == TokenNameMINUS_GREATER) { + if (token == TokenName.MINUS_GREATER) { getNextToken(); object_property(); } @@ -3077,14 +3351,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // ctor_arguments: // /* empty */ // | '(' function_call_parameter_list ')' - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); return; } non_empty_function_call_parameter_list(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected in ctor_arguments."); } getNextToken(); @@ -3097,7 +3371,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | assignment_list_element while (true) { assignment_list_element(); - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -3109,19 +3383,19 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // variable // | T_LIST '(' assignment_list ')' // | /* empty */ - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { variable(true, false); - } else if (token == TokenNameDOLLAR) { + } else if (token == TokenName.DOLLAR) { variable(false, false); - } else if (token == TokenNameIdentifier) { - identifier(true, true); + } else if (token == TokenName.IDENTIFIER) { + identifier(true, true, false); } else { - if (token == TokenNamelist) { + if (token == TokenName.LIST) { getNextToken(); - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); assignment_list(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected after 'list' keyword."); } getNextToken(); @@ -3137,7 +3411,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // /* empty */ // | non_empty_array_pair_list possible_comma non_empty_array_pair_list(); - if (token == TokenNameCOMMA) { + if (token == TokenName.COMMA) { getNextToken(); } } @@ -3153,17 +3427,17 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | expr T_DOUBLE_ARROW '&' w_variable // | '&' w_variable while (true) { - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); variable(true, false); } else { expr(); - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); variable(true, false); - } else if (token == TokenNameEQUAL_GREATER) { + } else if (token == TokenName.EQUAL_GREATER) { getNextToken(); - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); variable(true, false); } else { @@ -3171,11 +3445,11 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { return; } getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { return; } } @@ -3184,7 +3458,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // private void variableList() { // do { // variable(); - // if (token == TokenNameCOMMA) { + // if (token == TokenName.COMMA) { // getNextToken(); // } else { // break; @@ -3199,7 +3473,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: variable_without_objects()"); } - while (token == TokenNameDOLLAR) { + while (token == TokenName.DOLLAR) { getNextToken(); } return reference_variable(lefthandside, ignoreVar); @@ -3219,18 +3493,18 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: function_call()"); } - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { ident = scanner.getCurrentIdentifierSource(); defineName = ident; startPos = scanner.getCurrentTokenStartPosition(); endPos = scanner.getCurrentTokenEndPosition(); getNextToken(); switch (token) { - case TokenNamePAAMAYIM_NEKUDOTAYIM: + case PAAMAYIM_NEKUDOTAYIM: // static member: defineName = null; getNextToken(); - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { // class _constant getNextToken(); } else { @@ -3242,26 +3516,33 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } else { ref = variable_without_objects(lefthandside, ignoreVar); } - if (token != TokenNameLPAREN) { + if (token != TokenName.LPAREN) { if (defineName != null) { // does this identifier contain only uppercase characters? if (defineName.length == 3) { - if (defineName[0] == 'd' && defineName[1] == 'i' - && defineName[2] == 'e') { + if (defineName[0] == 'd' && + defineName[1] == 'i' && + defineName[2] == 'e') { defineName = null; } } else if (defineName.length == 4) { - if (defineName[0] == 't' && defineName[1] == 'r' - && defineName[2] == 'u' && defineName[3] == 'e') { + if (defineName[0] == 't' && + defineName[1] == 'r' && + defineName[2] == 'u' && + defineName[3] == 'e') { defineName = null; - } else if (defineName[0] == 'n' && defineName[1] == 'u' - && defineName[2] == 'l' && defineName[3] == 'l') { + } else if (defineName[0] == 'n' && + defineName[1] == 'u' && + defineName[2] == 'l' && + defineName[3] == 'l') { defineName = null; } } else if (defineName.length == 5) { - if (defineName[0] == 'f' && defineName[1] == 'a' - && defineName[2] == 'l' && defineName[3] == 's' - && defineName[4] == 'e') { + if (defineName[0] == 'f' && + defineName[1] == 'a' && + defineName[2] == 'l' && + defineName[3] == 's' && + defineName[4] == 'e') { defineName = null; } } @@ -3278,20 +3559,23 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } else { getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); return ref; } + non_empty_function_call_parameter_list(); - if (token != TokenNameRPAREN) { + + if (token != TokenName.RPAREN) { String functionName; + if (ident == null) { functionName = new String(" "); } else { functionName = new String(ident); } - throwSyntaxError("')' expected in function call (" - + functionName + ")."); + + throwSyntaxError("')' expected in function call (" + functionName + ")."); } getNextToken(); } @@ -3323,19 +3607,19 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, initHandler.setFunctionName(functionName); while (true) { initHandler.incrementArgumentCount(); - if (token == TokenNameAND) { + if (token == TokenName.OP_AND) { getNextToken(); w_variable(true); } else { - // if (token == TokenNameIdentifier || token == - // TokenNameVariable - // || token == TokenNameDOLLAR) { + // if (token == TokenName.Identifier || token == + // TokenName.Variable + // || token == TokenName.DOLLAR) { // variable(); // } else { - expr_without_variable(true, initHandler); + expr_without_variable(true, initHandler, false); // } } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); @@ -3343,7 +3627,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } private void fully_qualified_class_name() { - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { getNextToken(); } else { throwSyntaxError("Class name expected."); @@ -3358,7 +3642,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, System.out.println("TRACE: static_member()"); } fully_qualified_class_name(); - if (token != TokenNamePAAMAYIM_NEKUDOTAYIM) { + if (token != TokenName.PAAMAYIM_NEKUDOTAYIM) { throwSyntaxError("'::' expected after class name (static_member)."); } getNextToken(); @@ -3385,10 +3669,10 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: base_variable()"); } - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { static_member(); } else { - while (token == TokenNameDOLLAR) { + while (token == TokenName.DOLLAR) { getNextToken(); } reference_variable(lefthandside, false); @@ -3413,23 +3697,23 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } ref = compound_variable(lefthandside, ignoreVar); while (true) { - if (token == TokenNameLBRACE) { + if (token == TokenName.LBRACE) { ref = null; getNextToken(); expr(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in reference variable."); } getNextToken(); - } else if (token == TokenNameLBRACKET) { + } else if (token == TokenName.LBRACKET) { // To remove "ref = null;" here, is probably better than the // patch // commented in #1368081 - axelcl getNextToken(); - if (token != TokenNameRBRACKET) { + if (token != TokenName.RBRACKET) { expr(); // dim_offset(); - if (token != TokenNameRBRACKET) { + if (token != TokenName.RBRACKET) { throwSyntaxError("']' expected in reference variable."); } } @@ -3448,7 +3732,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: compound_variable()"); } - if (token == TokenNameVariable) { + if (token == TokenName.VARIABLE) { if (!lefthandside) { if (!containsVariableSet()) { // reportSyntaxError("The local variable " + new @@ -3472,16 +3756,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, return ref; } else { // because of simple_indirect_reference - while (token == TokenNameDOLLAR) { + while (token == TokenName.DOLLAR) { getNextToken(); } - if (token != TokenNameLBRACE) { + if (token != TokenName.LBRACE) { reportSyntaxError("'{' expected after compound variable token '$'."); return null; } getNextToken(); expr(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected after compound variable token '$'."); } getNextToken(); @@ -3499,7 +3783,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: object_property()"); } - if (token == TokenNameVariable || token == TokenNameDOLLAR) { + if (token == TokenName.VARIABLE || token == TokenName.DOLLAR) { variable_without_objects(false, false); } else { object_dim_list(); @@ -3516,21 +3800,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } variable_name(); while (true) { - if (token == TokenNameLBRACE) { + if (token == TokenName.LBRACE) { getNextToken(); expr(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in object_dim_list."); } getNextToken(); - } else if (token == TokenNameLBRACKET) { + } else if (token == TokenName.LBRACKET) { getNextToken(); - if (token == TokenNameRBRACKET) { + if (token == TokenName.RBRACKET) { getNextToken(); continue; } expr(); - if (token != TokenNameRBRACKET) { + if (token != TokenName.RBRACKET) { throwSyntaxError("']' expected in object_dim_list."); } getNextToken(); @@ -3547,18 +3831,18 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: variable_name()"); } - if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { - if (token > TokenNameKEYWORD) { + if (token == TokenName.IDENTIFIER || token.compareTo (TokenName.KEYWORD) > 0) { + if (token.compareTo (TokenName.KEYWORD) > 0) { // TODO show a warning "Keyword used as variable" ? } getNextToken(); } else { - if (token != TokenNameLBRACE) { + if (token != TokenName.LBRACE) { throwSyntaxError("'{' expected in variable name."); } getNextToken(); expr(); - if (token != TokenNameRBRACE) { + if (token != TokenName.RBRACE) { throwSyntaxError("'}' expected in variable name."); } getNextToken(); @@ -3584,7 +3868,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | base_variable_with_function_calls Expression ref = base_variable_with_function_calls(lefthandside, ignoreVar); - if (token == TokenNameMINUS_GREATER) { + if (token == TokenName.MINUS_GREATER) { ref = null; getNextToken(); object_property(); @@ -3598,7 +3882,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // variable_properties: // variable_properties variable_property // | /* empty */ - while (token == TokenNameMINUS_GREATER) { + while (token == TokenName.MINUS_GREATER) { variable_property(); } } @@ -3609,7 +3893,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: variable_property()"); } - if (token == TokenNameMINUS_GREATER) { + if (token == TokenName.MINUS_GREATER) { getNextToken(); object_property(); method_or_not(); @@ -3618,135 +3902,192 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } } - private Expression identifier(boolean lefthandside, boolean ignoreVar) { - // variable: - // base_variable_with_function_calls T_OBJECT_OPERATOR - // object_property method_or_not variable_properties - // | base_variable_with_function_calls - - // Expression ref = function_call(lefthandside, ignoreVar); - - // function_call: - // T_STRING '(' function_call_parameter_list ')' - // | class_constant '(' function_call_parameter_list ')' - // | static_member '(' function_call_parameter_list ')' - // | variable_without_objects '(' function_call_parameter_list ')' + /** + * + * variable: + * base_variable_with_function_calls T_OBJECT_OPERATOR + * object_property method_or_not variable_properties + * | base_variable_with_function_calls + * + * Expression ref = function_call(lefthandside, ignoreVar); + * + * function_call: + * T_STRING '(' function_call_parameter_list ')' + * | class_constant '(' function_call_parameter_list ')' + * | static_member '(' function_call_parameter_list ')' + * | variable_without_objects '(' function_call_parameter_list ')' + * + * @param lefthandside + * @param ignoreVar + * + * @return + */ + private Expression identifier (boolean lefthandside, boolean ignoreVar, boolean bColonAllowed) { char[] defineName = null; - char[] ident = null; - int startPos = 0; - int endPos = 0; - Expression ref = null; + char[] ident = null; + int startPos = 0; + int endPos = 0; + Expression ref = null; + if (Scanner.TRACE) { System.out.println("TRACE: function_call()"); } - if (token == TokenNameIdentifier) { - ident = scanner.getCurrentIdentifierSource(); + + if (token == TokenName.IDENTIFIER) { + ident = scanner.getCurrentIdentifierSource(); defineName = ident; - startPos = scanner.getCurrentTokenStartPosition(); - endPos = scanner.getCurrentTokenEndPosition(); - getNextToken(); + startPos = scanner.getCurrentTokenStartPosition(); + endPos = scanner.getCurrentTokenEndPosition(); - if (token == TokenNameEQUAL || token == TokenNamePLUS_EQUAL - || token == TokenNameMINUS_EQUAL - || token == TokenNameMULTIPLY_EQUAL - || token == TokenNameDIVIDE_EQUAL - || token == TokenNameDOT_EQUAL - || token == TokenNameREMAINDER_EQUAL - || token == TokenNameAND_EQUAL - || token == TokenNameOR_EQUAL - || token == TokenNameXOR_EQUAL - || token == TokenNameRIGHT_SHIFT_EQUAL - || token == TokenNameLEFT_SHIFT_EQUAL) { - String error = "Assignment operator '" - + scanner.toStringAction(token) - + "' not allowed after identifier '" - + new String(ident) - + "' (use 'define(...)' to define constants)."; - reportSyntaxError(error); - } + getNextToken(); // Get the token after the identifier switch (token) { - case TokenNamePAAMAYIM_NEKUDOTAYIM: - // static member: - defineName = null; - getNextToken(); - if (token == TokenNameIdentifier) { - // class _constant - getNextToken(); - } else { - // static member: - variable_without_objects(true, false); - } - break; - } - } else { + case EQUAL: + case PLUS_EQUAL: + case MINUS_EQUAL: + case MULTIPLY_EQUAL: + case DIVIDE_EQUAL: + case DOT_EQUAL: + case REMAINDER_EQUAL: + case AND_EQUAL: + case OR_EQUAL: + case XOR_EQUAL: + case RIGHT_SHIFT_EQUAL: + case LEFT_SHIFT_EQUAL: + String error = "Assignment operator '" + + scanner.toStringAction(token) + + "' not allowed after identifier '" + + new String(ident) + + "' (use 'define(...)' to define constants)."; + reportSyntaxError(error); + break; + } + + if (token == TokenName.COLON) { // If it's a ':', the identifier is a label + return ref; + } + + do { + if (token == TokenName.PAAMAYIM_NEKUDOTAYIM) { // '::' + defineName = null; + + getNextToken (); // Read the identifier + + if (token == TokenName.IDENTIFIER) { // class _constant + getNextToken (); + } + else { // static member: + variable_without_objects (true, false); + } + break; + } + else if (token == TokenName.BACKSLASH) { // '\' namespace path separator + getNextToken (); + + if (token == TokenName.IDENTIFIER) { // If it's an identifier + getNextToken (); // go for the next token + } + else { // It's not an identifiere, something wrong + throwSyntaxError ("an identifier expected after '\\' "); + } + } + else { + break; + } + } while (true); + } + else { // Token is not an identifier ref = variable_without_objects(lefthandside, ignoreVar); } - if (token != TokenNameLPAREN) { - if (defineName != null) { - // does this identifier contain only uppercase characters? - if (defineName.length == 3) { - if (defineName[0] == 'd' && defineName[1] == 'i' - && defineName[2] == 'e') { + + if (token == TokenName.LPAREN) { // If token is '(' + getNextToken(); + + if (token == TokenName.RPAREN) { // If token is ')' + getNextToken(); + ref = null; + } + else { + String functionName; + + if (ident == null) { + functionName = new String(" "); + } else { + functionName = new String(ident); + } + + non_empty_function_call_parameter_list(functionName); // Get the parameter list for the given function name + + if (token != TokenName.RPAREN) { // If token is not a ')', throw error + throwSyntaxError ("')' expected in function call (" + functionName + ")."); + } + + getNextToken(); // Get the token after ')' + } + } + else { // It's not an '(' + if (defineName != null) { // does this identifier contain only uppercase characters? + if (defineName.length == 3) { // If it's a 'die' + if (defineName[0] == 'd' && + defineName[1] == 'i' && + defineName[2] == 'e') { defineName = null; } - } else if (defineName.length == 4) { - if (defineName[0] == 't' && defineName[1] == 'r' - && defineName[2] == 'u' && defineName[3] == 'e') { + } + else if (defineName.length == 4) { // If it's a 'true' + if (defineName[0] == 't' && + defineName[1] == 'r' && + defineName[2] == 'u' && + defineName[3] == 'e') { defineName = null; - } else if (defineName[0] == 'n' && defineName[1] == 'u' - && defineName[2] == 'l' && defineName[3] == 'l') { + } + else if (defineName[0] == 'n' && // If it's a 'null' + defineName[1] == 'u' && + defineName[2] == 'l' && + defineName[3] == 'l') { defineName = null; } - } else if (defineName.length == 5) { - if (defineName[0] == 'f' && defineName[1] == 'a' - && defineName[2] == 'l' && defineName[3] == 's' - && defineName[4] == 'e') { + } + else if (defineName.length == 5) { // If it's a 'false' + if (defineName[0] == 'f' && + defineName[1] == 'a' && + defineName[2] == 'l' && + defineName[3] == 's' && + defineName[4] == 'e') { defineName = null; } } + if (defineName != null) { - for (int i = 0; i < defineName.length; i++) { - if (Character.isLowerCase(defineName[i])) { - problemReporter.phpUppercaseIdentifierWarning( - startPos, endPos, referenceContext, - compilationUnit.compilationResult); - break; - } - } + for (int i = 0; i < defineName.length; i++) { + if (Character.isLowerCase (defineName[i])) { + problemReporter.phpUppercaseIdentifierWarning (startPos, endPos, referenceContext, + compilationUnit.compilationResult); + break; + } + } } } // TODO is this ok ? // return ref; // throwSyntaxError("'(' expected in function call."); - } else { - getNextToken(); - - if (token == TokenNameRPAREN) { - getNextToken(); - ref = null; - } else { - String functionName; - if (ident == null) { - functionName = new String(" "); - } else { - functionName = new String(ident); - } - non_empty_function_call_parameter_list(functionName); - if (token != TokenNameRPAREN) { - throwSyntaxError("')' expected in function call (" - + functionName + ")."); - } - getNextToken(); - } } - if (token == TokenNameMINUS_GREATER) { + + if (token == TokenName.MINUS_GREATER) { ref = null; getNextToken(); object_property(); method_or_not(); variable_properties(); } + + // A colon is only allowed here if it is an expression read after a '?' + + if ((token == TokenName.COLON) && + (!bColonAllowed)) { + throwSyntaxError ("No ':' allowed"); + } + return ref; } @@ -3757,14 +4098,14 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, if (Scanner.TRACE) { System.out.println("TRACE: method_or_not()"); } - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); return; } non_empty_function_call_parameter_list(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected in method_or_not."); } getNextToken(); @@ -3775,16 +4116,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // /* empty */ // | '(' ')' // | '(' expr ')' - if (token != TokenNameLPAREN) { + if (token != TokenName.LPAREN) { return; } getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); return; } expr(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected after keyword 'exit'"); } getNextToken(); @@ -3805,32 +4146,32 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // | /* empty */ // while (true) { // switch (token) { - // case TokenNameSTRING: + // case TokenName.STRING: // getNextToken(); // break; - // case TokenNameLBRACE: + // case TokenName.LBRACE: // // scanner.encapsedStringStack.pop(); // getNextToken(); // break; - // case TokenNameRBRACE: + // case TokenName.RBRACE: // // scanner.encapsedStringStack.pop(); // getNextToken(); // break; - // case TokenNameLBRACKET: + // case TokenName.LBRACKET: // // scanner.encapsedStringStack.pop(); // getNextToken(); // break; - // case TokenNameRBRACKET: + // case TokenName.RBRACKET: // // scanner.encapsedStringStack.pop(); // getNextToken(); // break; - // case TokenNameMINUS_GREATER: + // case TokenName.MINUS_GREATER: // // scanner.encapsedStringStack.pop(); // getNextToken(); // break; - // case TokenNameVariable: - // case TokenNameDOLLAR_LBRACE: - // case TokenNameLBRACE_DOLLAR: + // case TokenName.Variable: + // case TokenName.DOLLAR_LBRACE: + // case TokenName.LBRACE_DOLLAR: // encaps_var(); // break; // default: @@ -3842,22 +4183,22 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // scanner.encapsedStringStack.peek()).charValue(); // switch (encapsedChar) { // case '`': - // if (token == TokenNameEncapsedString0) { + // if (token == TokenName.EncapsedString0) { // return; // } - // token = TokenNameSTRING; + // token = TokenName.STRING; // continue; // case '\'': - // if (token == TokenNameEncapsedString1) { + // if (token == TokenName.EncapsedString1) { // return; // } - // token = TokenNameSTRING; + // token = TokenName.STRING; // continue; // case '"': - // if (token == TokenNameEncapsedString2) { + // if (token == TokenName.EncapsedString2) { // return; // } - // token = TokenNameSTRING; + // token = TokenName.STRING; // continue; // } // } @@ -3874,20 +4215,20 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // | T_DOLLAR_OPEN_CURLY_BRACES T_STRING_VARNAME '[' expr ']' '}' // // | T_CURLY_OPEN variable '}' // switch (token) { - // case TokenNameVariable: + // case TokenName.Variable: // getNextToken(); - // if (token == TokenNameLBRACKET) { + // if (token == TokenName.LBRACKET) { // getNextToken(); // expr(); //encaps_var_offset(); - // if (token != TokenNameRBRACKET) { + // if (token != TokenName.RBRACKET) { // throwSyntaxError("']' expected after variable."); // } // // scanner.encapsedStringStack.pop(); // getNextToken(); // // } - // } else if (token == TokenNameMINUS_GREATER) { + // } else if (token == TokenName.MINUS_GREATER) { // getNextToken(); - // if (token != TokenNameIdentifier) { + // if (token != TokenName.Identifier) { // throwSyntaxError("Identifier expected after '->'."); // } // // scanner.encapsedStringStack.pop(); @@ -3895,32 +4236,32 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } // // else { // // // scanner.encapsedStringStack.pop(); - // // int tempToken = TokenNameSTRING; + // // int tempToken = TokenName.STRING; // // if (!scanner.encapsedStringStack.isEmpty() - // // && (token == TokenNameEncapsedString0 - // // || token == TokenNameEncapsedString1 - // // || token == TokenNameEncapsedString2 || token == - // // TokenNameERROR)) { + // // && (token == TokenName.EncapsedString0 + // // || token == TokenName.EncapsedString1 + // // || token == TokenName.EncapsedString2 || token == + // // TokenName.ERROR)) { // // char encapsedChar = ((Character) // // scanner.encapsedStringStack.peek()) // // .charValue(); // // switch (token) { - // // case TokenNameEncapsedString0 : + // // case TokenName.EncapsedString0 : // // if (encapsedChar == '`') { - // // tempToken = TokenNameEncapsedString0; + // // tempToken = TokenName.EncapsedString0; // // } // // break; - // // case TokenNameEncapsedString1 : + // // case TokenName.EncapsedString1 : // // if (encapsedChar == '\'') { - // // tempToken = TokenNameEncapsedString1; + // // tempToken = TokenName.EncapsedString1; // // } // // break; - // // case TokenNameEncapsedString2 : + // // case TokenName.EncapsedString2 : // // if (encapsedChar == '"') { - // // tempToken = TokenNameEncapsedString2; + // // tempToken = TokenName.EncapsedString2; // // } // // break; - // // case TokenNameERROR : + // // case TokenName.ERROR : // // if (scanner.source[scanner.currentPosition - 1] == '\\') { // // scanner.currentPosition--; // // getNextToken(); @@ -3931,19 +4272,19 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // token = tempToken; // // } // break; - // case TokenNameDOLLAR_LBRACE: + // case TokenName.DOLLAR_LBRACE: // getNextToken(); - // if (token == TokenNameDOLLAR_LBRACE) { + // if (token == TokenName.DOLLAR_LBRACE) { // encaps_var(); - // } else if (token == TokenNameIdentifier) { + // } else if (token == TokenName.Identifier) { // getNextToken(); - // if (token == TokenNameLBRACKET) { + // if (token == TokenName.LBRACKET) { // getNextToken(); - // // if (token == TokenNameRBRACKET) { + // // if (token == TokenName.RBRACKET) { // // getNextToken(); // // } else { // expr(); - // if (token != TokenNameRBRACKET) { + // if (token != TokenName.RBRACKET) { // throwSyntaxError("']' expected after '${'."); // } // getNextToken(); @@ -3952,55 +4293,55 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } else { // expr(); // } - // if (token != TokenNameRBRACE) { + // if (token != TokenName.RBRACE) { // throwSyntaxError("'}' expected."); // } // getNextToken(); // break; - // case TokenNameLBRACE_DOLLAR: + // case TokenName.LBRACE_DOLLAR: // getNextToken(); - // if (token == TokenNameLBRACE_DOLLAR) { + // if (token == TokenName.LBRACE_DOLLAR) { // encaps_var(); - // } else if (token == TokenNameIdentifier || token > TokenNameKEYWORD) { + // } else if (token == TokenName.Identifier || token > TokenName.KEYWORD) { // getNextToken(); - // if (token == TokenNameLBRACKET) { + // if (token == TokenName.LBRACKET) { // getNextToken(); - // // if (token == TokenNameRBRACKET) { + // // if (token == TokenName.RBRACKET) { // // getNextToken(); // // } else { // expr(); - // if (token != TokenNameRBRACKET) { + // if (token != TokenName.RBRACKET) { // throwSyntaxError("']' expected."); // } // getNextToken(); // // } - // } else if (token == TokenNameMINUS_GREATER) { + // } else if (token == TokenName.MINUS_GREATER) { // getNextToken(); - // if (token != TokenNameIdentifier && token != TokenNameVariable) { + // if (token != TokenName.Identifier && token != TokenName.Variable) { // throwSyntaxError("String or Variable token expected."); // } // getNextToken(); - // if (token == TokenNameLBRACKET) { + // if (token == TokenName.LBRACKET) { // getNextToken(); - // // if (token == TokenNameRBRACKET) { + // // if (token == TokenName.RBRACKET) { // // getNextToken(); // // } else { // expr(); - // if (token != TokenNameRBRACKET) { + // if (token != TokenName.RBRACKET) { // throwSyntaxError("']' expected after '${'."); // } // getNextToken(); // // } // } // } - // // if (token != TokenNameRBRACE) { + // // if (token != TokenName.RBRACE) { // // throwSyntaxError("'}' expected after '{$'."); // // } // // // scanner.encapsedStringStack.pop(); // // getNextToken(); // } else { // expr(); - // if (token != TokenNameRBRACE) { + // if (token != TokenName.RBRACE) { // throwSyntaxError("'}' expected."); // } // // scanner.encapsedStringStack.pop(); @@ -4015,16 +4356,16 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // // | T_NUM_STRING // // | T_VARIABLE // switch (token) { - // case TokenNameSTRING: + // case TokenName.STRING: // getNextToken(); // break; - // case TokenNameIntegerLiteral: + // case TokenName.IntegerLiteral: // getNextToken(); // break; - // case TokenNameVariable: + // case TokenName.Variable: // getNextToken(); // break; - // case TokenNameIdentifier: + // case TokenName.Identifier: // getNextToken(); // break; // default: @@ -4033,61 +4374,64 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // } // } + /** + * + */ private void internal_functions_in_yacc() { // int start = 0; switch (token) { - // case TokenNameisset: + // case TokenName.isset: // // T_ISSET '(' isset_variables ')' // getNextToken(); - // if (token != TokenNameLPAREN) { + // if (token != TokenName.LPAREN) { // throwSyntaxError("'(' expected after keyword 'isset'"); // } // getNextToken(); // isset_variables(); - // if (token != TokenNameRPAREN) { + // if (token != TokenName.RPAREN) { // throwSyntaxError("')' expected after keyword 'isset'"); // } // getNextToken(); // break; - // case TokenNameempty: + // case TokenName.empty: // // T_EMPTY '(' variable ')' // getNextToken(); - // if (token != TokenNameLPAREN) { + // if (token != TokenName.LPAREN) { // throwSyntaxError("'(' expected after keyword 'empty'"); // } // getNextToken(); // variable(false); - // if (token != TokenNameRPAREN) { + // if (token != TokenName.RPAREN) { // throwSyntaxError("')' expected after keyword 'empty'"); // } // getNextToken(); // break; - case TokenNameinclude: + case INCLUDE: // T_INCLUDE expr checkFileName(token); break; - case TokenNameinclude_once: + case INCLUDE_ONCE: // T_INCLUDE_ONCE expr checkFileName(token); break; - case TokenNameeval: + case EVAL: // T_EVAL '(' expr ')' getNextToken(); - if (token != TokenNameLPAREN) { + if (token != TokenName.LPAREN) { throwSyntaxError("'(' expected after keyword 'eval'"); } getNextToken(); expr(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' expected after keyword 'eval'"); } getNextToken(); break; - case TokenNamerequire: + case REQUIRE: // T_REQUIRE expr checkFileName(token); break; - case TokenNamerequire_once: + case REQUIRE_ONCE: // T_REQUIRE_ONCE expr checkFileName(token); break; @@ -4096,21 +4440,21 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * Parse and check the include file name - * + * * @param includeToken */ - private void checkFileName(int includeToken) { + private void checkFileName(TokenName includeToken) { // expr int start = scanner.getCurrentTokenStartPosition(); boolean hasLPAREN = false; getNextToken(); - if (token == TokenNameLPAREN) { + if (token == TokenName.LPAREN) { hasLPAREN = true; getNextToken(); } Expression expression = expr(); if (hasLPAREN) { - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); } else { throwSyntaxError("')' expected for keyword '" @@ -4201,12 +4545,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, private void isset_variables() { // variable // | isset_variables ',' - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { throwSyntaxError("Variable expected after keyword 'isset'"); } while (true) { variable(true, false); - if (token == TokenNameCOMMA) { + if (token == TokenName.COMMA) { getNextToken(); } else { break; @@ -4225,34 +4569,34 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | T_METHOD_C // | T_FUNC_C switch (token) { - case TokenNameIntegerLiteral: + case INTEGERLITERAL: getNextToken(); return true; - case TokenNameDoubleLiteral: + case DOUBLELITERAL: getNextToken(); return true; - case TokenNameStringDoubleQuote: + case STRINGDOUBLEQUOTE: getNextToken(); return true; - case TokenNameStringSingleQuote: + case STRINGSINGLEQUOTE: getNextToken(); return true; - case TokenNameStringInterpolated: + case STRINGINTERPOLATED: getNextToken(); return true; - case TokenNameFILE: + case FILE: getNextToken(); return true; - case TokenNameLINE: + case LINE: getNextToken(); return true; - case TokenNameCLASS_C: + case CLASS_C: getNextToken(); return true; - case TokenNameMETHOD_C: + case METHOD_C: getNextToken(); return true; - case TokenNameFUNC_C: + case FUNC_C: getNextToken(); return true; } @@ -4283,20 +4627,20 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, return; } switch (token) { - case TokenNameIdentifier: + case IDENTIFIER: getNextToken(); // static_class_constant: // T_STRING T_PAAMAYIM_NEKUDOTAYIM T_STRING - if (token == TokenNamePAAMAYIM_NEKUDOTAYIM) { + if (token == TokenName.PAAMAYIM_NEKUDOTAYIM) { getNextToken(); - if (token == TokenNameIdentifier) { + if (token == TokenName.IDENTIFIER) { getNextToken(); } else { throwSyntaxError("Identifier expected after '::' operator."); } } break; - case TokenNameEncapsedString0: + case ENCAPSEDSTRING0: try { scanner.currentCharacter = scanner.source[scanner.currentPosition++]; while (scanner.currentCharacter != '`') { @@ -4310,7 +4654,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, throwSyntaxError("'`' expected at end of static string."); } break; - // case TokenNameEncapsedString1: + // case TokenName.EncapsedString1: // try { // scanner.currentCharacter = scanner.source[scanner.currentPosition++]; // while (scanner.currentCharacter != '\'') { @@ -4324,7 +4668,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // throwSyntaxError("'\'' expected at end of static string."); // } // break; - // case TokenNameEncapsedString2: + // case TokenName.EncapsedString2: // try { // scanner.currentCharacter = scanner.source[scanner.currentPosition++]; // while (scanner.currentCharacter != '"') { @@ -4338,43 +4682,43 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // throwSyntaxError("'\"' expected at end of static string."); // } // break; - case TokenNameStringSingleQuote: + case STRINGSINGLEQUOTE: getNextToken(); break; - case TokenNameStringDoubleQuote: + case STRINGDOUBLEQUOTE: getNextToken(); break; - case TokenNamePLUS: + case PLUS: getNextToken(); static_scalar(); break; - case TokenNameMINUS: + case MINUS: getNextToken(); static_scalar(); break; - case TokenNamearray: + case ARRAY: getNextToken(); - if (token != TokenNameLPAREN) { + if (token != TokenName.LPAREN) { throwSyntaxError("'(' expected after keyword 'array'"); } getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { getNextToken(); break; } non_empty_static_array_pair_list(); - if (token != TokenNameRPAREN) { + if (token != TokenName.RPAREN) { throwSyntaxError("')' or ',' expected after keyword 'array'"); } getNextToken(); break; - // case TokenNamenull : + // case TokenName.null : // getNextToken(); // break; - // case TokenNamefalse : + // case TokenName.false : // getNextToken(); // break; - // case TokenNametrue : + // case TokenName.true : // getNextToken(); // break; default: @@ -4391,15 +4735,15 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, // | static_scalar while (true) { static_scalar(); - if (token == TokenNameEQUAL_GREATER) { + if (token == TokenName.EQUAL_GREATER) { getNextToken(); static_scalar(); } - if (token != TokenNameCOMMA) { + if (token != TokenName.COMMA) { break; } getNextToken(); - if (token == TokenNameRPAREN) { + if (token == TokenName.RPAREN) { break; } } @@ -4995,12 +5339,12 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, //String projectPath = ProjectPrefUtil.getDocumentRoot(file.getProject()) // .toString(); //String filePath = file.getFullPath().toString(); - + String ext = file.getFileExtension(); int fileExtensionLength = ext == null ? 0 : ext.length() + 1; ImportReference impt; char[][] tokens; - + /*if (filePath.startsWith(projectPath)) { tokens = CharOperation.splitOn('/', filePath.toCharArray(), projectPath.length() + 1, filePath.length() @@ -5027,7 +5371,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, "$_SERVER" }; /** - * + * */ private void pushFunctionVariableSet() { HashSet set = new HashSet(); @@ -5068,7 +5412,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * add the current identifier source to the set of assigned variables * - * + * * @param set */ private void addVariableSet(HashSet set) { @@ -5080,7 +5424,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * add the current identifier source to the set of assigned variables * - * + * */ private void addVariableSet() { HashSet set = peekVariableSet(); @@ -5092,7 +5436,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, /** * add the current identifier source to the set of assigned variables * - * + * */ private void addVariableSet(char[] token) { HashSet set = peekVariableSet(); @@ -5105,7 +5449,7 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, * check if the current identifier source is in the set of assigned * variables Returns true, if no set is defined for the current scanner * position - * + * */ private boolean containsVariableSet() { return containsVariableSet(scanner.getCurrentTokenSource()); @@ -5126,4 +5470,4 @@ public class Parser implements ITerminalSymbols, CompilerModifiers, } return true; } -} \ No newline at end of file +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java index 4e52fb8..ae73d5f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Scanner.java @@ -42,14 +42,14 @@ public class Scanner implements IScanner, ITerminalSymbols { public boolean phpMode = false; /** - * This token is set to TokenNameecho if a short tag block begins (i.e. + * This token is set to TokenName.echo if a short tag block begins (i.e. * >?= ... ) Directly after the "=" character the - * getNextToken() method returns TokenNameINLINE_HTML In the next call to - * the getNextToken() method the value of fFillerToken (==TokenNameecho) is + * getNextToken() method returns TokenName.INLINE_HTML In the next call to + * the getNextToken() method the value of fFillerToken (==TokenName.echo) is * returned - * + * */ - int fFillerToken = TokenNameEOF; + TokenName fFillerToken = TokenName.EOF; public char currentCharacter; @@ -303,10 +303,10 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * Determines if the specified character is permissible as the first * character in a PHP identifier or variable - * + * * The '$' character for PHP variables is regarded as a correct first * character ! - * + * */ public static boolean isPHPIdentOrVarStart(char ch) { if (ch < MAX_OBVIOUS) { @@ -322,7 +322,7 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * Determines if the specified character is permissible as the first * character in a PHP identifier. - * + * * The '$' character for PHP variables isn't regarded as the first character ! */ public static boolean isPHPIdentifierStart(char ch) { @@ -522,10 +522,10 @@ public class Scanner implements IScanner, ITerminalSymbols { /* * Search the source position corresponding to the end of a given line * number - * + * * Line numbers are 1-based, and relative to the scanner initialPosition. * Character positions are 0-based. - * + * * In case the given line number is inconsistent, answers -1. */ public final int getLineEnd(int lineNumber) { @@ -544,12 +544,12 @@ public class Scanner implements IScanner, ITerminalSymbols { /** * Search the source position corresponding to the beginning of a given line * number - * + * * Line numbers are 1-based, and relative to the scanner initialPosition. * Character positions are 0-based. - * + * * e.g. getLineStart(1) --> 0 i.e. first line starts at character 0. - * + * * In case the given line number is inconsistent, answers -1. */ public final int getLineStart(int lineNumber) { @@ -969,10 +969,10 @@ public class Scanner implements IScanner, ITerminalSymbols { } } - public int getCastOrParen() { + public TokenName getCastOrParen() { int tempPosition = currentPosition; char tempCharacter = currentCharacter; - int tempToken = TokenNameLPAREN; + TokenName tempToken = TokenName.LPAREN; boolean found = false; StringBuffer buf = new StringBuffer(); try { @@ -994,7 +994,7 @@ public class Scanner implements IScanner, ITerminalSymbols { if ((data[index] == 'i') && (data[++index] == 'n') && (data[++index] == 't')) { found = true; - tempToken = TokenNameintCAST; + tempToken = TokenName.INTCAST; } break; case 4: @@ -1002,14 +1002,14 @@ public class Scanner implements IScanner, ITerminalSymbols { if ((data[index] == 'b') && (data[++index] == 'o') && (data[++index] == 'o') && (data[++index] == 'l')) { found = true; - tempToken = TokenNameboolCAST; + tempToken = TokenName.BOOLCAST; } else { index = 0; if ((data[index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'l')) { found = true; - tempToken = TokenNamedoubleCAST; + tempToken = TokenName.DOUBLECAST; } } break; @@ -1019,7 +1019,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'r') && (data[++index] == 'a') && (data[++index] == 'y')) { found = true; - tempToken = TokenNamearrayCAST; + tempToken = TokenName.ARRAYCAST; } else { index = 0; if ((data[index] == 'u') && (data[++index] == 'n') @@ -1027,7 +1027,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'e') && (data[++index] == 't')) { found = true; - tempToken = TokenNameunsetCAST; + tempToken = TokenName.UNSETCAST; } else { index = 0; if ((data[index] == 'f') && (data[++index] == 'l') @@ -1035,7 +1035,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'a') && (data[++index] == 't')) { found = true; - tempToken = TokenNamedoubleCAST; + tempToken = TokenName.DOUBLECAST; } } } @@ -1046,7 +1046,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'j') && (data[++index] == 'e') && (data[++index] == 'c') && (data[++index] == 't')) { found = true; - tempToken = TokenNameobjectCAST; + tempToken = TokenName.OBJECTCAST; } else { index = 0; if ((data[index] == 's') && (data[++index] == 't') @@ -1055,7 +1055,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'n') && (data[++index] == 'g')) { found = true; - tempToken = TokenNamestringCAST; + tempToken = TokenName.STRINGCAST; } else { index = 0; if ((data[index] == 'd') && (data[++index] == 'o') @@ -1064,7 +1064,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'l') && (data[++index] == 'e')) { found = true; - tempToken = TokenNamedoubleCAST; + tempToken = TokenName.DOUBLECAST; } } } @@ -1076,7 +1076,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'n')) { found = true; - tempToken = TokenNameboolCAST; + tempToken = TokenName.BOOLCAST; } else { index = 0; if ((data[index] == 'i') && (data[++index] == 'n') @@ -1086,7 +1086,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'e') && (data[++index] == 'r')) { found = true; - tempToken = TokenNameintCAST; + tempToken = TokenName.INTCAST; } } break; @@ -1104,7 +1104,7 @@ public class Scanner implements IScanner, ITerminalSymbols { } currentCharacter = tempCharacter; currentPosition = tempPosition; - return TokenNameLPAREN; + return TokenName.LPAREN; } public void consumeStringInterpolated() throws InvalidInputException { @@ -1409,23 +1409,23 @@ public class Scanner implements IScanner, ITerminalSymbols { } } - public int getNextToken() throws InvalidInputException { + public TokenName getNextToken() throws InvalidInputException { if (!phpMode) { return getInlinedHTMLToken(currentPosition); } else { - if (fFillerToken != TokenNameEOF) { - int tempToken; + if (fFillerToken != TokenName.EOF) { + TokenName tempToken; startPosition = currentPosition; tempToken = fFillerToken; - fFillerToken = TokenNameEOF; + fFillerToken = TokenName.EOF; return tempToken; } this.wasAcr = false; if (diet) { jumpOverMethodBody(); diet = false; - return currentPosition > source.length ? TokenNameEOF - : TokenNameRBRACE; + return currentPosition > source.length ? TokenName.EOF + : TokenName.RBRACE; } try { while (true) { @@ -1436,11 +1436,10 @@ public class Scanner implements IScanner, ITerminalSymbols { startPosition = currentPosition; currentCharacter = source[currentPosition++]; - while ((currentCharacter == ' ') - || Character.isWhitespace(currentCharacter)) { - if ((currentCharacter == '\r') - || (currentCharacter == '\n')) { + while ((currentCharacter == ' ') || Character.isWhitespace(currentCharacter)) { + if ((currentCharacter == '\r') || (currentCharacter == '\n')) { checkNonExternalizeString(); + if (recordLineSeparator) { pushLineSeparator(); } else { @@ -1450,96 +1449,98 @@ public class Scanner implements IScanner, ITerminalSymbols { startPosition = currentPosition; currentCharacter = source[currentPosition++]; } - if (tokenizeWhiteSpace - && (whiteStart != currentPosition - 1)) { + + if (tokenizeWhiteSpace && (whiteStart != currentPosition - 1)) { // reposition scanner in case we are interested by // spaces as tokens currentPosition--; startPosition = whiteStart; - return TokenNameWHITESPACE; + return TokenName.WHITESPACE; } // little trick to get out in the middle of a source // compuation if (currentPosition > eofPosition) - return TokenNameEOF; + return TokenName.EOF; // ---------Identify the next token------------- switch (currentCharacter) { case '(': return getCastOrParen(); case ')': - return TokenNameRPAREN; + return TokenName.RPAREN; case '{': - return TokenNameLBRACE; + return TokenName.LBRACE; case '}': - return TokenNameRBRACE; + return TokenName.RBRACE; case '[': - return TokenNameLBRACKET; + return TokenName.LBRACKET; case ']': - return TokenNameRBRACKET; + return TokenName.RBRACKET; case ';': - return TokenNameSEMICOLON; + return TokenName.SEMICOLON; case ',': - return TokenNameCOMMA; + return TokenName.COMMA; case '.': if (getNextChar('=')) - return TokenNameDOT_EQUAL; + return TokenName.DOT_EQUAL; if (getNextCharAsDigit()) return scanNumber(true); - return TokenNameDOT; + return TokenName.DOT; + case '\\': + return TokenName.BACKSLASH; case '+': { int test; if ((test = getNextChar('+', '=')) == 0) - return TokenNamePLUS_PLUS; + return TokenName.PLUS_PLUS; if (test > 0) - return TokenNamePLUS_EQUAL; - return TokenNamePLUS; + return TokenName.PLUS_EQUAL; + return TokenName.PLUS; } case '-': { int test; if ((test = getNextChar('-', '=')) == 0) - return TokenNameMINUS_MINUS; + return TokenName.MINUS_MINUS; if (test > 0) - return TokenNameMINUS_EQUAL; + return TokenName.MINUS_EQUAL; if (getNextChar('>')) - return TokenNameMINUS_GREATER; - return TokenNameMINUS; + return TokenName.MINUS_GREATER; + return TokenName.MINUS; } case '~': if (getNextChar('=')) - return TokenNameTWIDDLE_EQUAL; - return TokenNameTWIDDLE; + return TokenName.TWIDDLE_EQUAL; + return TokenName.TWIDDLE; case '!': if (getNextChar('=')) { if (getNextChar('=')) { - return TokenNameNOT_EQUAL_EQUAL; + return TokenName.NOT_EQUAL_EQUAL; } - return TokenNameNOT_EQUAL; + return TokenName.NOT_EQUAL; } - return TokenNameNOT; + return TokenName.NOT; case '*': if (getNextChar('=')) - return TokenNameMULTIPLY_EQUAL; - return TokenNameMULTIPLY; + return TokenName.MULTIPLY_EQUAL; + return TokenName.MULTIPLY; case '%': if (getNextChar('=')) - return TokenNameREMAINDER_EQUAL; - return TokenNameREMAINDER; + return TokenName.REMAINDER_EQUAL; + return TokenName.REMAINDER; case '<': { int oldPosition = currentPosition; try { currentCharacter = source[currentPosition++]; } catch (IndexOutOfBoundsException e) { currentPosition = oldPosition; - return TokenNameLESS; + return TokenName.LESS; } switch (currentCharacter) { case '=': - return TokenNameLESS_EQUAL; + return TokenName.LESS_EQUAL; case '>': - return TokenNameNOT_EQUAL; + return TokenName.NOT_EQUAL; case '<': if (getNextChar('=')) - return TokenNameLEFT_SHIFT_EQUAL; + return TokenName.LEFT_SHIFT_EQUAL; if (getNextChar('<')) { currentCharacter = source[currentPosition++]; while (Character.isWhitespace(currentCharacter)) { @@ -1550,7 +1551,7 @@ public class Scanner implements IScanner, ITerminalSymbols { if (isPHPIdentifierStart(currentCharacter)) { currentCharacter = source[currentPosition++]; } else { - return TokenNameERROR; + return TokenName.ERROR; } while (isPHPIdentifierPart(currentCharacter)) { currentCharacter = source[currentPosition++]; @@ -1584,90 +1585,90 @@ public class Scanner implements IScanner, ITerminalSymbols { } } } while (true); - return TokenNameHEREDOC; + return TokenName.HEREDOC; } - return TokenNameLEFT_SHIFT; + return TokenName.LEFT_SHIFT; } currentPosition = oldPosition; - return TokenNameLESS; + return TokenName.LESS; } case '>': { int test; if ((test = getNextChar('=', '>')) == 0) - return TokenNameGREATER_EQUAL; + return TokenName.GREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) - return TokenNameRIGHT_SHIFT_EQUAL; - return TokenNameRIGHT_SHIFT; + return TokenName.RIGHT_SHIFT_EQUAL; + return TokenName.RIGHT_SHIFT; } - return TokenNameGREATER; + return TokenName.GREATER; } case '=': if (getNextChar('=')) { if (getNextChar('=')) { - return TokenNameEQUAL_EQUAL_EQUAL; + return TokenName.EQUAL_EQUAL_EQUAL; } - return TokenNameEQUAL_EQUAL; + return TokenName.EQUAL_EQUAL; } if (getNextChar('>')) - return TokenNameEQUAL_GREATER; - return TokenNameEQUAL; + return TokenName.EQUAL_GREATER; + return TokenName.EQUAL; case '&': { int test; if ((test = getNextChar('&', '=')) == 0) - return TokenNameAND_AND; + return TokenName.AND_AND; if (test > 0) - return TokenNameAND_EQUAL; - return TokenNameAND; + return TokenName.AND_EQUAL; + return TokenName.OP_AND; } case '|': { int test; if ((test = getNextChar('|', '=')) == 0) - return TokenNameOR_OR; + return TokenName.OR_OR; if (test > 0) - return TokenNameOR_EQUAL; - return TokenNameOR; + return TokenName.OR_EQUAL; + return TokenName.OP_OR; } case '^': if (getNextChar('=')) - return TokenNameXOR_EQUAL; - return TokenNameXOR; + return TokenName.XOR_EQUAL; + return TokenName.OP_XOR; case '?': if (getNextChar('>')) { phpMode = false; if (currentPosition == source.length) { phpMode = true; - return TokenNameINLINE_HTML; + return TokenName.INLINE_HTML; } return getInlinedHTMLToken(currentPosition - 2); } - return TokenNameQUESTION; + return TokenName.QUESTION; case ':': if (getNextChar(':')) - return TokenNamePAAMAYIM_NEKUDOTAYIM; - return TokenNameCOLON; + return TokenName.PAAMAYIM_NEKUDOTAYIM; + return TokenName.COLON; case '@': - return TokenNameAT; + return TokenName.OP_AT; case '\'': consumeStringConstant(); - return TokenNameStringSingleQuote; + return TokenName.STRINGSINGLEQUOTE; case '"': // if (tokenizeStrings) { consumeStringLiteral(); - return TokenNameStringDoubleQuote; + return TokenName.STRINGDOUBLEQUOTE; // } - // return TokenNameEncapsedString2; + // return TokenName.EncapsedString2; case '`': // if (tokenizeStrings) { consumeStringInterpolated(); - return TokenNameStringInterpolated; + return TokenName.STRINGINTERPOLATED; // } - // return TokenNameEncapsedString0; + // return TokenName.EncapsedString0; case '#': case '/': { char startChar = currentCharacter; if (getNextChar('=') && startChar == '/') { - return TokenNameDIVIDE_EQUAL; + return TokenName.DIVIDE_EQUAL; } int test; if ((startChar == '#') @@ -1726,7 +1727,7 @@ public class Scanner implements IScanner, ITerminalSymbols { // ?> breaks line comments startPosition = currentPosition - 2; phpMode = false; - return TokenNameINLINE_HTML; + return TokenName.INLINE_HTML; } } // get the next char @@ -1783,7 +1784,7 @@ public class Scanner implements IScanner, ITerminalSymbols { endPositionForLineComment = currentPosition - 1; } // recordComment(false); - recordComment(TokenNameCOMMENT_LINE); + recordComment(TokenName.COMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); @@ -1805,7 +1806,7 @@ public class Scanner implements IScanner, ITerminalSymbols { currentPosition = endPositionForLineComment; // reset one character behind } - return TokenNameCOMMENT_LINE; + return TokenName.COMMENT_LINE; } } catch (IndexOutOfBoundsException e) { // an eof // will them @@ -1813,7 +1814,7 @@ public class Scanner implements IScanner, ITerminalSymbols { if (tokenizeComments) { currentPosition--; // reset one character behind - return TokenNameCOMMENT_LINE; + return TokenName.COMMENT_LINE; } } break; @@ -1898,15 +1899,15 @@ public class Scanner implements IScanner, ITerminalSymbols { } // recordComment(isJavadoc); if (isJavadoc) { - recordComment(TokenNameCOMMENT_PHPDOC); + recordComment(TokenName.COMMENT_PHPDOC); } else { - recordComment(TokenNameCOMMENT_BLOCK); + recordComment(TokenName.COMMENT_BLOCK); } if (tokenizeComments) { if (isJavadoc) - return TokenNameCOMMENT_PHPDOC; - return TokenNameCOMMENT_BLOCK; + return TokenName.COMMENT_PHPDOC; + return TokenName.COMMENT_BLOCK; } if (this.taskTags != null) { @@ -1921,11 +1922,11 @@ public class Scanner implements IScanner, ITerminalSymbols { } break; } - return TokenNameDIVIDE; + return TokenName.DIVIDE; } case '\u001a': if (atEnd()) - return TokenNameEOF; + return TokenName.EOF; // the atEnd may not be if // source is only some part of a real (external) stream @@ -1939,36 +1940,41 @@ public class Scanner implements IScanner, ITerminalSymbols { return scanIdentifierOrKeyword(true); } else { currentPosition = oldPosition; - return TokenNameDOLLAR; + return TokenName.DOLLAR; } } catch (IndexOutOfBoundsException e) { currentPosition = oldPosition; - return TokenNameDOLLAR; + return TokenName.DOLLAR; } } - if (isPHPIdentifierStart(currentCharacter)) + + if (isPHPIdentifierStart(currentCharacter)) { return scanIdentifierOrKeyword(false); - if (Character.isDigit(currentCharacter)) + } + + if (Character.isDigit(currentCharacter)) { return scanNumber(false); - return TokenNameERROR; + } + + return TokenName.ERROR; } } } // -----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { } } - return TokenNameEOF; + return TokenName.EOF; } /** * @return * @throws InvalidInputException */ - private int getInlinedHTMLToken(int start) throws InvalidInputException { + private TokenName getInlinedHTMLToken(int start) throws InvalidInputException { boolean phpShortTag = false; // true, if source.length) { currentPosition = source.length; - return TokenNameEOF; + return TokenName.EOF; } startPosition = start; try { @@ -1987,12 +1993,12 @@ public class Scanner implements IScanner, ITerminalSymbols { } // = 0) { if (getNextChar('P', 'p') >= 0) { // TokenNameKEYWORD); + public static boolean isIdentifierOrKeyword (TokenName token) { + return (token == TokenName.IDENTIFIER) || (token.compareTo (TokenName.KEYWORD) > 0); } final char[] optimizedCurrentTokenSource1() { @@ -2999,14 +3005,14 @@ public class Scanner implements IScanner, ITerminalSymbols { } } - public void recordComment(int token) { + public void recordComment(TokenName token) { // compute position int stopPosition = this.currentPosition; switch (token) { - case TokenNameCOMMENT_LINE: + case COMMENT_LINE: stopPosition = -this.lastCommentLinePosition; break; - case TokenNameCOMMENT_BLOCK: + case COMMENT_BLOCK: stopPosition = -this.currentPosition; break; } @@ -3171,12 +3177,12 @@ public class Scanner implements IScanner, ITerminalSymbols { // public int scanIdentifierOrKeyword() throws InvalidInputException { // return scanIdentifierOrKeyword( false ); // } - public int scanIdentifierOrKeyword(boolean isVariable) + public TokenName scanIdentifierOrKeyword(boolean isVariable) throws InvalidInputException { // test keywords // first dispatch on the first char. // then the length. If there are several - // keywors with the same length AND the same first char, then do another + // keywords with the same length AND the same first char, then do another // disptach on the second char :-)...cool....but fast ! useAssertAsAnIndentifier = false; while (getNextCharAsJavaIdentifierPart()) { @@ -3184,9 +3190,9 @@ public class Scanner implements IScanner, ITerminalSymbols { ; if (isVariable) { // if (new String(getCurrentTokenSource()).equals("$this")) { - // return TokenNamethis; + // return TokenName.this; // } - return TokenNameVariable; + return TokenName.VARIABLE; } int index, length; char[] data; @@ -3198,7 +3204,7 @@ public class Scanner implements IScanner, ITerminalSymbols { // only one char.... // { if ((length = currentPosition - startPosition) == 1) - return TokenNameIdentifier; + return TokenName.IDENTIFIER; // data = source; data = new char[length]; index = startPosition; @@ -3208,7 +3214,7 @@ public class Scanner implements IScanner, ITerminalSymbols { index = 0; // } else { // if ((length = withoutUnicodePtr) == 1) - // return TokenNameIdentifier; + // return TokenName.Identifier; // // data = withoutUnicodeBuffer; // data = new char[withoutUnicodeBuffer.length]; // for (int i = 0; i < withoutUnicodeBuffer.length; i++) { @@ -3226,13 +3232,13 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'i') && (data[++index] == 'l') && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == '_')) - return TokenNameFILE; + return TokenName.FILE; index = 0; // __LINE__ if ((data[++index] == '_') && (data[++index] == 'l') && (data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == '_')) - return TokenNameLINE; + return TokenName.LINE; break; case 9: // __CLASS__ @@ -3240,7 +3246,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 's') && (data[++index] == 's') && (data[++index] == '_') && (data[++index] == '_')) - return TokenNameCLASS_C; + return TokenName.CLASS_C; break; case 11: // __METHOD__ @@ -3249,7 +3255,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'h') && (data[++index] == 'o') && (data[++index] == 'd') && (data[++index] == '_') && (data[++index] == '_')) - return TokenNameMETHOD_C; + return TokenName.METHOD_C; break; case 12: // __FUNCTION__ @@ -3259,173 +3265,173 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'i') && (data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == '_') && (data[++index] == '_')) - return TokenNameFUNC_C; + return TokenName.FUNC_C; break; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'a': // as and array abstract switch (length) { case 2: // as if ((data[++index] == 's')) { - return TokenNameas; + return TokenName.AS; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 3: // and if ((data[++index] == 'n') && (data[++index] == 'd')) { - return TokenNameand; + return TokenName.OP_AND_OLD; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 5: // array if ((data[++index] == 'r') && (data[++index] == 'r') && (data[++index] == 'a') && (data[++index] == 'y')) - return TokenNamearray; - return TokenNameIdentifier; + return TokenName.ARRAY; + return TokenName.IDENTIFIER; case 8: if ((data[++index] == 'b') && (data[++index] == 's') && (data[++index] == 't') && (data[++index] == 'r') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 't')) - return TokenNameabstract; - return TokenNameIdentifier; + return TokenName.ABSTRACT; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'b': // break switch (length) { case 5: if ((data[++index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'k')) - return TokenNamebreak; - return TokenNameIdentifier; + return TokenName.BREAK; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'c': // case catch class clone const continue switch (length) { case 4: if ((data[++index] == 'a') && (data[++index] == 's') && (data[++index] == 'e')) - return TokenNamecase; - return TokenNameIdentifier; + return TokenName.CASE; + return TokenName.IDENTIFIER; case 5: if ((data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) - return TokenNamecatch; + return TokenName.CATCH; index = 0; if ((data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 's') && (data[++index] == 's')) - return TokenNameclass; + return TokenName.CLASS; index = 0; if ((data[++index] == 'l') && (data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 'e')) - return TokenNameclone; + return TokenName.CLONE; index = 0; if ((data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 't')) - return TokenNameconst; - return TokenNameIdentifier; + return TokenName.CONST; + return TokenName.IDENTIFIER; case 8: if ((data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 'u') && (data[++index] == 'e')) - return TokenNamecontinue; - return TokenNameIdentifier; + return TokenName.CONTINUE; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'd': // declare default do die // TODO delete define ==> no keyword ! switch (length) { case 2: if ((data[++index] == 'o')) - return TokenNamedo; - return TokenNameIdentifier; + return TokenName.DO; + return TokenName.IDENTIFIER; // case 6 : // if ((data[++index] == 'e') // && (data[++index] == 'f') // && (data[++index] == 'i') // && (data[++index] == 'n') // && (data[++index] == 'e')) - // return TokenNamedefine; + // return TokenName.define; // else - // return TokenNameIdentifier; + // return TokenName.Identifier; case 7: if ((data[++index] == 'e') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 'r') && (data[++index] == 'e')) - return TokenNamedeclare; + return TokenName.DECLARE; index = 0; if ((data[++index] == 'e') && (data[++index] == 'f') && (data[++index] == 'a') && (data[++index] == 'u') && (data[++index] == 'l') && (data[++index] == 't')) - return TokenNamedefault; - return TokenNameIdentifier; + return TokenName.DEFAULT; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'e': // echo else exit elseif extends eval switch (length) { case 4: if ((data[++index] == 'c') && (data[++index] == 'h') && (data[++index] == 'o')) - return TokenNameecho; + return TokenName.ECHO; else if ((data[index] == 'l') && (data[++index] == 's') && (data[++index] == 'e')) - return TokenNameelse; + return TokenName.ELSE; else if ((data[index] == 'x') && (data[++index] == 'i') && (data[++index] == 't')) - return TokenNameexit; + return TokenName.EXIT; else if ((data[index] == 'v') && (data[++index] == 'a') && (data[++index] == 'l')) - return TokenNameeval; - return TokenNameIdentifier; + return TokenName.EVAL; + return TokenName.IDENTIFIER; case 5: // endif empty if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'i') && (data[++index] == 'f')) - return TokenNameendif; + return TokenName.ENDIF; if ((data[index] == 'm') && (data[++index] == 'p') && (data[++index] == 't') && (data[++index] == 'y')) - return TokenNameempty; - return TokenNameIdentifier; + return TokenName.EMPTY; + return TokenName.IDENTIFIER; case 6: // endfor if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'f') && (data[++index] == 'o') && (data[++index] == 'r')) - return TokenNameendfor; + return TokenName.ENDFOR; else if ((data[index] == 'l') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 'i') && (data[++index] == 'f')) - return TokenNameelseif; - return TokenNameIdentifier; + return TokenName.ELSEIF; + return TokenName.IDENTIFIER; case 7: if ((data[++index] == 'x') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 's')) - return TokenNameextends; - return TokenNameIdentifier; + return TokenName.EXTENDS; + return TokenName.IDENTIFIER; case 8: // endwhile if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 'w') && (data[++index] == 'h') && (data[++index] == 'i') && (data[++index] == 'l') && (data[++index] == 'e')) - return TokenNameendwhile; - return TokenNameIdentifier; + return TokenName.ENDWHILE; + return TokenName.IDENTIFIER; case 9: // endswitch if ((data[++index] == 'n') && (data[++index] == 'd') && (data[++index] == 's') && (data[++index] == 'w') && (data[++index] == 'i') && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) - return TokenNameendswitch; - return TokenNameIdentifier; + return TokenName.ENDSWITCH; + return TokenName.IDENTIFIER; case 10: // enddeclare if ((data[++index] == 'n') && (data[++index] == 'd') @@ -3433,7 +3439,7 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'a') && (data[++index] == 'r') && (data[++index] == 'e')) - return TokenNameenddeclare; + return TokenName.ENDDECLARE; index = 0; if ((data[++index] == 'n') // endforeach && (data[++index] == 'd') @@ -3443,138 +3449,153 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'h')) - return TokenNameendforeach; - return TokenNameIdentifier; + return TokenName.ENDFOREACH; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'f': // for false final function switch (length) { case 3: if ((data[++index] == 'o') && (data[++index] == 'r')) - return TokenNamefor; - return TokenNameIdentifier; + return TokenName.FOR; + return TokenName.IDENTIFIER; case 5: // if ((data[++index] == 'a') && (data[++index] == 'l') // && (data[++index] == 's') && (data[++index] == 'e')) - // return TokenNamefalse; + // return TokenName.false; if ((data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 'a') && (data[++index] == 'l')) - return TokenNamefinal; - return TokenNameIdentifier; + return TokenName.FINAL; + return TokenName.IDENTIFIER; case 7: // foreach if ((data[++index] == 'o') && (data[++index] == 'r') && (data[++index] == 'e') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'h')) - return TokenNameforeach; - return TokenNameIdentifier; + return TokenName.FOREACH; + return TokenName.IDENTIFIER; case 8: // function if ((data[++index] == 'u') && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 't') && (data[++index] == 'i') && (data[++index] == 'o') && (data[++index] == 'n')) - return TokenNamefunction; - return TokenNameIdentifier; + return TokenName.FUNCTION; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'g': - // global + // global if (length == 6) { if ((data[++index] == 'l') && (data[++index] == 'o') && (data[++index] == 'b') && (data[++index] == 'a') && (data[++index] == 'l')) { - return TokenNameglobal; + return TokenName.GLOBAL; } + } + else if (length == 4) { // goto + if ((data[++index] == 'o') && + (data[++index] == 't') && + (data[++index] == 'o')) { + return TokenName.GOTO; + } } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'i': // if int isset include include_once instanceof interface implements switch (length) { case 2: if (data[++index] == 'f') - return TokenNameif; - return TokenNameIdentifier; + return TokenName.IF; + return TokenName.IDENTIFIER; // case 3 : // if ((data[++index] == 'n') && (data[++index] == 't')) - // return TokenNameint; + // return TokenName.int; // else - // return TokenNameIdentifier; + // return TokenName.IDENTIFIER; case 5: if ((data[++index] == 's') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 't')) - return TokenNameisset; - return TokenNameIdentifier; + return TokenName.ISSET; + return TokenName.IDENTIFIER; case 7: if ((data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'u') && (data[++index] == 'd') && (data[++index] == 'e')) - return TokenNameinclude; - return TokenNameIdentifier; + return TokenName.INCLUDE; + return TokenName.IDENTIFIER; case 9: // interface if ((data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'r') && (data[++index] == 'f') && (data[++index] == 'a') && (data[++index] == 'c') && (data[++index] == 'e')) - return TokenNameinterface; - return TokenNameIdentifier; + return TokenName.INTERFACE; + return TokenName.IDENTIFIER; case 10: - // instanceof + // instanceof implements if ((data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 't') && (data[++index] == 'a') && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e') && (data[++index] == 'o') && (data[++index] == 'f')) - return TokenNameinstanceof; + return TokenName.INSTANCEOF; if ((data[index] == 'm') && (data[++index] == 'p') && (data[++index] == 'l') && (data[++index] == 'e') && (data[++index] == 'm') && (data[++index] == 'e') && (data[++index] == 'n') && (data[++index] == 't') && (data[++index] == 's')) - return TokenNameimplements; - return TokenNameIdentifier; - case 12: + return TokenName.IMPLEMENTS; + return TokenName.IDENTIFIER; + case 12: // include_once if ((data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'l') && (data[++index] == 'u') && (data[++index] == 'd') && (data[++index] == 'e') && (data[++index] == '_') && (data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e')) - return TokenNameinclude_once; - return TokenNameIdentifier; + return TokenName.INCLUDE_ONCE; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'l': // list if (length == 4) { if ((data[++index] == 'i') && (data[++index] == 's') && (data[++index] == 't')) { - return TokenNamelist; + return TokenName.LIST; } } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'n': - // new null + // new null namespace switch (length) { case 3: if ((data[++index] == 'e') && (data[++index] == 'w')) - return TokenNamenew; - return TokenNameIdentifier; + return TokenName.NEW; + return TokenName.IDENTIFIER; // case 4 : // if ((data[++index] == 'u') && (data[++index] == 'l') // && (data[++index] == 'l')) - // return TokenNamenull; + // return TokenName.null; // else - // return TokenNameIdentifier; + // return TokenName.IDENTIFIER; + case 9: + if ((data[++index] == 'a') && (data[++index] == 'm') + && (data[++index] == 'e') && (data[++index] == 's') + && (data[++index] == 'p') && (data[++index] == 'a') + && (data[++index] == 'c') && (data[++index] == 'e')) { + return TokenName.NAMESPACE; + } + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'o': // or old_function if (length == 2) { if (data[++index] == 'r') { - return TokenNameor; + return TokenName.OP_OR_OLD; } } // if (length == 12) { @@ -3589,56 +3610,56 @@ public class Scanner implements IScanner, ITerminalSymbols { // && (data[++index] == 'i') // && (data[++index] == 'o') // && (data[++index] == 'n')) { - // return TokenNameold_function; + // return TokenName.old_function; // } // } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'p': // print public private protected switch (length) { case 5: if ((data[++index] == 'r') && (data[++index] == 'i') && (data[++index] == 'n') && (data[++index] == 't')) { - return TokenNameprint; + return TokenName.PRINT; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 6: if ((data[++index] == 'u') && (data[++index] == 'b') && (data[++index] == 'l') && (data[++index] == 'i') && (data[++index] == 'c')) { - return TokenNamepublic; + return TokenName.PUBLIC; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 7: if ((data[++index] == 'r') && (data[++index] == 'i') && (data[++index] == 'v') && (data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'e')) { - return TokenNameprivate; + return TokenName.PRIVATE; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 9: if ((data[++index] == 'r') && (data[++index] == 'o') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'c') && (data[++index] == 't') && (data[++index] == 'e') && (data[++index] == 'd')) { - return TokenNameprotected; + return TokenName.PROTECTED; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'r': // return require require_once if (length == 6) { if ((data[++index] == 'e') && (data[++index] == 't') && (data[++index] == 'u') && (data[++index] == 'r') && (data[++index] == 'n')) { - return TokenNamereturn; + return TokenName.RETURN; } } else if (length == 7) { if ((data[++index] == 'e') && (data[++index] == 'q') && (data[++index] == 'u') && (data[++index] == 'i') && (data[++index] == 'r') && (data[++index] == 'e')) { - return TokenNamerequire; + return TokenName.REQUIRE; } } else if (length == 12) { if ((data[++index] == 'e') && (data[++index] == 'q') @@ -3647,10 +3668,10 @@ public class Scanner implements IScanner, ITerminalSymbols { && (data[++index] == '_') && (data[++index] == 'o') && (data[++index] == 'n') && (data[++index] == 'c') && (data[++index] == 'e')) { - return TokenNamerequire_once; + return TokenName.REQUIRE_ONCE; } } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 's': // self static switch switch (length) { @@ -3658,92 +3679,92 @@ public class Scanner implements IScanner, ITerminalSymbols { // if ((data[++index] == 'e') && (data[++index] == 'l') && // (data[++index] // == 'f')) { - // return TokenNameself; + // return TokenName.self; // } - // return TokenNameIdentifier; + // return TokenName.IDENTIFIER; case 6: if (data[++index] == 't') if ((data[++index] == 'a') && (data[++index] == 't') && (data[++index] == 'i') && (data[++index] == 'c')) { - return TokenNamestatic; + return TokenName.STATIC; } else - return TokenNameIdentifier; + return TokenName.IDENTIFIER; else if ((data[index] == 'w') && (data[++index] == 'i') && (data[++index] == 't') && (data[++index] == 'c') && (data[++index] == 'h')) - return TokenNameswitch; + return TokenName.SWITCH; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 't': // try true throw switch (length) { case 3: if ((data[++index] == 'r') && (data[++index] == 'y')) - return TokenNametry; + return TokenName.TRY; // case 4 : // if ((data[++index] == 'r') && (data[++index] == 'u') // && (data[++index] == 'e')) - // return TokenNametrue; + // return TokenName.true; else - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 5: if ((data[++index] == 'h') && (data[++index] == 'r') && (data[++index] == 'o') && (data[++index] == 'w')) - return TokenNamethrow; + return TokenName.THROW; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'u': // use unset switch (length) { case 3: if ((data[++index] == 's') && (data[++index] == 'e')) - return TokenNameuse; + return TokenName.USE; else - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 5: if ((data[++index] == 'n') && (data[++index] == 's') && (data[++index] == 'e') && (data[++index] == 't')) - return TokenNameunset; + return TokenName.UNSET; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'v': // var switch (length) { case 3: if ((data[++index] == 'a') && (data[++index] == 'r')) - return TokenNamevar; + return TokenName.VAR; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'w': // while switch (length) { case 5: if ((data[++index] == 'h') && (data[++index] == 'i') && (data[++index] == 'l') && (data[++index] == 'e')) - return TokenNamewhile; + return TokenName.WHILE; // case 6:if ( (data[++index] =='i') && (data[++index]=='d') && // (data[++index]=='e') && (data[++index]=='f')&& // (data[++index]=='p')) - // return TokenNamewidefp ; + // return TokenName.widefp ; // else - // return TokenNameIdentifier; + // return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; case 'x': // xor switch (length) { case 3: if ((data[++index] == 'o') && (data[++index] == 'r')) - return TokenNamexor; + return TokenName.OP_XOR_OLD; else - return TokenNameIdentifier; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; } - return TokenNameIdentifier; + return TokenName.IDENTIFIER; } - public int scanNumber(boolean dotPrefix) throws InvalidInputException { + public TokenName scanNumber(boolean dotPrefix) throws InvalidInputException { // when entering this method the currentCharacter is the firt // digit of the number , i.e. it may be preceeded by a . when // dotPrefix is true @@ -3769,9 +3790,9 @@ public class Scanner implements IScanner, ITerminalSymbols { } ; // if (getNextChar('l', 'L') >= 0) - // return TokenNameLongLiteral; + // return TokenName.LongLiteral; // else - return TokenNameIntegerLiteral; + return TokenName.INTEGERLITERAL; } // there is x or X in the number // potential octal ! ... some one may write 000099.0 ! thus 00100 < @@ -3782,14 +3803,14 @@ public class Scanner implements IScanner, ITerminalSymbols { } ; // if (getNextChar('l', 'L') >= 0) { - // return TokenNameLongLiteral; + // return TokenName.LongLiteral; // } // // if (getNextChar('f', 'F') >= 0) { - // return TokenNameFloatingPointLiteral; + // return TokenName.FloatingPointLiteral; // } if (getNextChar('d', 'D') >= 0) { - return TokenNameDoubleLiteral; + return TokenName.DOUBLELITERAL; } else { // make the distinction between octal and float .... if (getNextChar('.')) { // bingo ! .... while (getNextCharAsDigit()) { @@ -3832,11 +3853,11 @@ public class Scanner implements IScanner, ITerminalSymbols { ; } // if (getNextChar('f', 'F') >= 0) - // return TokenNameFloatingPointLiteral; + // return TokenName.FloatingPointLiteral; getNextChar('d', 'D'); // jump over potential d or D - return TokenNameDoubleLiteral; + return TokenName.DOUBLELITERAL; } else { - return TokenNameIntegerLiteral; + return TokenName.INTEGERLITERAL; } } } else { @@ -3847,7 +3868,7 @@ public class Scanner implements IScanner, ITerminalSymbols { } ; // if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) - // return TokenNameLongLiteral; + // return TokenName.LongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { // decimal part that can be // empty while (getNextCharAsDigit()) { @@ -3890,16 +3911,16 @@ public class Scanner implements IScanner, ITerminalSymbols { ; } if (getNextChar('d', 'D') >= 0) - return TokenNameDoubleLiteral; + return TokenName.DOUBLELITERAL; // if (getNextChar('f', 'F') >= 0) - // return TokenNameFloatingPointLiteral; + // return TokenName.FloatingPointLiteral; // the long flag has been tested before - return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; + return floating ? TokenName.DOUBLELITERAL : TokenName.INTEGERLITERAL; } /** * Search the line number corresponding to a specific position - * + * */ public final int getLineNumber(int position) { if (lineEnds == null) @@ -3945,7 +3966,7 @@ public class Scanner implements IScanner, ITerminalSymbols { initialPosition = currentPosition = 0; containsAssertKeyword = false; withoutUnicodeBuffer = new char[this.source.length]; - fFillerToken = TokenNameEOF; + fFillerToken = TokenName.EOF; // encapsedStringStack = new Stack(); } @@ -3974,300 +3995,302 @@ public class Scanner implements IScanner, ITerminalSymbols { + new String(end); } - public final String toStringAction(int act) { + public final String toStringAction(TokenName act) { switch (act) { - case TokenNameERROR: + case ERROR: return "ScannerError"; // + new String(getCurrentTokenSource()) + // ")"; // //$NON-NLS-1$ - case TokenNameINLINE_HTML: + case INLINE_HTML: return "Inline-HTML(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameECHO_INVISIBLE: + case ECHO_INVISIBLE: // 0-length token return ""; - case TokenNameIdentifier: + case IDENTIFIER: return "Identifier(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameVariable: + case VARIABLE: return "Variable(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameabstract: + case ABSTRACT: return "abstract"; //$NON-NLS-1$ - case TokenNameand: + case OP_AND_OLD: return "AND"; //$NON-NLS-1$ - case TokenNamearray: + case ARRAY: return "array"; //$NON-NLS-1$ - case TokenNameas: + case AS: return "as"; //$NON-NLS-1$ - case TokenNamebreak: + case BREAK: return "break"; //$NON-NLS-1$ - case TokenNamecase: + case CASE: return "case"; //$NON-NLS-1$ - case TokenNameclass: + case CLASS: return "class"; //$NON-NLS-1$ - case TokenNamecatch: + case CATCH: return "catch"; //$NON-NLS-1$ - case TokenNameclone: + case CLONE: //$NON-NLS-1$ return "clone"; - case TokenNameconst: + case CONST: //$NON-NLS-1$ return "const"; - case TokenNamecontinue: + case CONTINUE: return "continue"; //$NON-NLS-1$ - case TokenNamedefault: + case DEFAULT: return "default"; //$NON-NLS-1$ - // case TokenNamedefine : + // case define : // return "define"; //$NON-NLS-1$ - case TokenNamedo: + case DO: return "do"; //$NON-NLS-1$ - case TokenNameecho: + case ECHO: return "echo"; //$NON-NLS-1$ - case TokenNameelse: + case ELSE: return "else"; //$NON-NLS-1$ - case TokenNameelseif: + case ELSEIF: return "elseif"; //$NON-NLS-1$ - case TokenNameendfor: + case ENDFOR: return "endfor"; //$NON-NLS-1$ - case TokenNameendforeach: + case ENDFOREACH: return "endforeach"; //$NON-NLS-1$ - case TokenNameendif: + case ENDIF: return "endif"; //$NON-NLS-1$ - case TokenNameendswitch: + case ENDSWITCH: return "endswitch"; //$NON-NLS-1$ - case TokenNameendwhile: + case ENDWHILE: return "endwhile"; //$NON-NLS-1$ - case TokenNameexit: + case EXIT: return "exit"; - case TokenNameextends: + case EXTENDS: return "extends"; //$NON-NLS-1$ - // case TokenNamefalse : + // case false : // return "false"; //$NON-NLS-1$ - case TokenNamefinal: + case FINAL: return "final"; //$NON-NLS-1$ - case TokenNamefor: + case FOR: return "for"; //$NON-NLS-1$ - case TokenNameforeach: + case FOREACH: return "foreach"; //$NON-NLS-1$ - case TokenNamefunction: + case FUNCTION: return "function"; //$NON-NLS-1$ - case TokenNameglobal: + case GLOBAL: return "global"; //$NON-NLS-1$ - case TokenNameif: + case IF: return "if"; //$NON-NLS-1$ - case TokenNameimplements: + case IMPLEMENTS: return "implements"; //$NON-NLS-1$ - case TokenNameinclude: + case INCLUDE: return "include"; //$NON-NLS-1$ - case TokenNameinclude_once: + case INCLUDE_ONCE: return "include_once"; //$NON-NLS-1$ - case TokenNameinstanceof: + case INSTANCEOF: return "instanceof"; //$NON-NLS-1$ - case TokenNameinterface: + case INTERFACE: return "interface"; //$NON-NLS-1$ - case TokenNameisset: + case ISSET: return "isset"; //$NON-NLS-1$ - case TokenNamelist: + case LIST: return "list"; //$NON-NLS-1$ - case TokenNamenew: + case NEW: return "new"; //$NON-NLS-1$ - // case TokenNamenull : + // case null : // return "null"; //$NON-NLS-1$ - case TokenNameor: + case OP_OR_OLD: return "OR"; //$NON-NLS-1$ - case TokenNameprint: + case PRINT: return "print"; //$NON-NLS-1$ - case TokenNameprivate: + case PRIVATE: return "private"; //$NON-NLS-1$ - case TokenNameprotected: + case PROTECTED: return "protected"; //$NON-NLS-1$ - case TokenNamepublic: + case PUBLIC: return "public"; //$NON-NLS-1$ - case TokenNamerequire: + case REQUIRE: return "require"; //$NON-NLS-1$ - case TokenNamerequire_once: + case REQUIRE_ONCE: return "require_once"; //$NON-NLS-1$ - case TokenNamereturn: + case RETURN: return "return"; //$NON-NLS-1$ - // case TokenNameself: + // case self: // return "self"; //$NON-NLS-1$ - case TokenNamestatic: + case STATIC: return "static"; //$NON-NLS-1$ - case TokenNameswitch: + case SWITCH: return "switch"; //$NON-NLS-1$ - // case TokenNametrue : + // case true : // return "true"; //$NON-NLS-1$ - case TokenNameunset: + case UNSET: return "unset"; //$NON-NLS-1$ - case TokenNamevar: + case VAR: return "var"; //$NON-NLS-1$ - case TokenNamewhile: + case WHILE: return "while"; //$NON-NLS-1$ - case TokenNamexor: + case OP_XOR_OLD: return "XOR"; //$NON-NLS-1$ - // case TokenNamethis : + // case this : // return "$this"; //$NON-NLS-1$ - case TokenNameIntegerLiteral: + case INTEGERLITERAL: return "Integer(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameDoubleLiteral: + case DOUBLELITERAL: return "Double(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameStringDoubleQuote: + case STRINGDOUBLEQUOTE: return "StringLiteral(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameStringSingleQuote: + case STRINGSINGLEQUOTE: return "StringConstant(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameStringInterpolated: + case STRINGINTERPOLATED: return "StringInterpolated(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameEncapsedString0: + case ENCAPSEDSTRING0: return "`"; //$NON-NLS-1$ - // case TokenNameEncapsedString1: + // case EncapsedString1: // return "\'"; //$NON-NLS-1$ - // case TokenNameEncapsedString2: + // case EncapsedString2: // return "\""; //$NON-NLS-1$ - case TokenNameSTRING: + case STRING: return "STRING_DQ(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - case TokenNameHEREDOC: + case HEREDOC: return "HEREDOC(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - case TokenNamePLUS_PLUS: + case PLUS_PLUS: return "++"; //$NON-NLS-1$ - case TokenNameMINUS_MINUS: + case MINUS_MINUS: return "--"; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL: + case EQUAL_EQUAL: return "=="; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL_EQUAL: + case EQUAL_EQUAL_EQUAL: return "==="; //$NON-NLS-1$ - case TokenNameEQUAL_GREATER: + case EQUAL_GREATER: return "=>"; //$NON-NLS-1$ - case TokenNameLESS_EQUAL: + case LESS_EQUAL: return "<="; //$NON-NLS-1$ - case TokenNameGREATER_EQUAL: + case GREATER_EQUAL: return ">="; //$NON-NLS-1$ - case TokenNameNOT_EQUAL: + case NOT_EQUAL: return "!="; //$NON-NLS-1$ - case TokenNameNOT_EQUAL_EQUAL: + case NOT_EQUAL_EQUAL: return "!=="; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT: + case LEFT_SHIFT: return "<<"; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT: + case RIGHT_SHIFT: return ">>"; //$NON-NLS-1$ - case TokenNamePLUS_EQUAL: + case PLUS_EQUAL: return "+="; //$NON-NLS-1$ - case TokenNameMINUS_EQUAL: + case MINUS_EQUAL: return "-="; //$NON-NLS-1$ - case TokenNameMULTIPLY_EQUAL: + case MULTIPLY_EQUAL: return "*="; //$NON-NLS-1$ - case TokenNameDIVIDE_EQUAL: + case DIVIDE_EQUAL: return "/="; //$NON-NLS-1$ - case TokenNameAND_EQUAL: + case AND_EQUAL: return "&="; //$NON-NLS-1$ - case TokenNameOR_EQUAL: + case OR_EQUAL: return "|="; //$NON-NLS-1$ - case TokenNameXOR_EQUAL: + case XOR_EQUAL: return "^="; //$NON-NLS-1$ - case TokenNameREMAINDER_EQUAL: + case REMAINDER_EQUAL: return "%="; //$NON-NLS-1$ - case TokenNameDOT_EQUAL: + case DOT_EQUAL: return ".="; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT_EQUAL: + case LEFT_SHIFT_EQUAL: return "<<="; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT_EQUAL: + case RIGHT_SHIFT_EQUAL: return ">>="; //$NON-NLS-1$ - case TokenNameOR_OR: + case OR_OR: return "||"; //$NON-NLS-1$ - case TokenNameAND_AND: + case AND_AND: return "&&"; //$NON-NLS-1$ - case TokenNamePLUS: + case PLUS: return "+"; //$NON-NLS-1$ - case TokenNameMINUS: + case MINUS: return "-"; //$NON-NLS-1$ - case TokenNameMINUS_GREATER: + case MINUS_GREATER: return "->"; - case TokenNameNOT: + case NOT: return "!"; //$NON-NLS-1$ - case TokenNameREMAINDER: + case REMAINDER: return "%"; //$NON-NLS-1$ - case TokenNameXOR: + case OP_XOR: return "^"; //$NON-NLS-1$ - case TokenNameAND: + case OP_AND: return "&"; //$NON-NLS-1$ - case TokenNameMULTIPLY: + case MULTIPLY: return "*"; //$NON-NLS-1$ - case TokenNameOR: + case OP_OR: return "|"; //$NON-NLS-1$ - case TokenNameTWIDDLE: + case TWIDDLE: return "~"; //$NON-NLS-1$ - case TokenNameTWIDDLE_EQUAL: + case TWIDDLE_EQUAL: return "~="; //$NON-NLS-1$ - case TokenNameDIVIDE: + case DIVIDE: return "/"; //$NON-NLS-1$ - case TokenNameGREATER: + case GREATER: return ">"; //$NON-NLS-1$ - case TokenNameLESS: + case LESS: return "<"; //$NON-NLS-1$ - case TokenNameLPAREN: + case LPAREN: return "("; //$NON-NLS-1$ - case TokenNameRPAREN: + case RPAREN: return ")"; //$NON-NLS-1$ - case TokenNameLBRACE: + case LBRACE: return "{"; //$NON-NLS-1$ - case TokenNameRBRACE: + case RBRACE: return "}"; //$NON-NLS-1$ - case TokenNameLBRACKET: + case LBRACKET: return "["; //$NON-NLS-1$ - case TokenNameRBRACKET: + case RBRACKET: return "]"; //$NON-NLS-1$ - case TokenNameSEMICOLON: + case SEMICOLON: return ";"; //$NON-NLS-1$ - case TokenNameQUESTION: + case QUESTION: return "?"; //$NON-NLS-1$ - case TokenNameCOLON: + case COLON: return ":"; //$NON-NLS-1$ - case TokenNameCOMMA: + case COMMA: return ","; //$NON-NLS-1$ - case TokenNameDOT: + case DOT: return "."; //$NON-NLS-1$ - case TokenNameEQUAL: + case EQUAL: return "="; //$NON-NLS-1$ - case TokenNameAT: + case OP_AT: return "@"; - case TokenNameDOLLAR: + case DOLLAR: return "$"; - case TokenNameDOLLAR_LBRACE: + case DOLLAR_LBRACE: return "${"; - case TokenNameLBRACE_DOLLAR: + case LBRACE_DOLLAR: return "{$"; - case TokenNameEOF: + case EOF: return "EOF"; //$NON-NLS-1$ - case TokenNameWHITESPACE: + case WHITESPACE: return "WHITESPACE(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - case TokenNameCOMMENT_LINE: + case COMMENT_LINE: return "COMMENT_LINE(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - case TokenNameCOMMENT_BLOCK: + case COMMENT_BLOCK: return "COMMENT_BLOCK(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - case TokenNameCOMMENT_PHPDOC: + case COMMENT_PHPDOC: return "COMMENT_PHPDOC(" + new String(getCurrentTokenSource()) + ")"; //$NON-NLS-1$ - // case TokenNameHTML : + // case HTML : // return "HTML(" + new String(getCurrentTokenSource()) + ")"; // //$NON-NLS-1$ - case TokenNameFILE: + case FILE: return "__FILE__"; //$NON-NLS-1$ - case TokenNameLINE: + case LINE: return "__LINE__"; //$NON-NLS-1$ - case TokenNameCLASS_C: + case CLASS_C: return "__CLASS__"; //$NON-NLS-1$ - case TokenNameMETHOD_C: + case METHOD_C: return "__METHOD__"; //$NON-NLS-1$ - case TokenNameFUNC_C: + case FUNC_C: return "__FUNCTION__"; //$NON-NLS-1 - case TokenNameboolCAST: + case BOOLCAST: return "( bool )"; //$NON-NLS-1$ - case TokenNameintCAST: + case INTCAST: return "( int )"; //$NON-NLS-1$ - case TokenNamedoubleCAST: + case DOUBLECAST: return "( double )"; //$NON-NLS-1$ - case TokenNameobjectCAST: + case OBJECTCAST: return "( object )"; //$NON-NLS-1$ - case TokenNamestringCAST: + case STRINGCAST: return "( string )"; //$NON-NLS-1$ + case NAMESPACE: + return "( namespace )"; //$NON-NLS-1$ default: - return "not-a-token(" + (new Integer(act)) + ") " + new String(getCurrentTokenSource()); //$NON-NLS-1$ + return "token not handled (" + (act.toString ()) + ") " + new String(getCurrentTokenSource()); //$NON-NLS-1$ } } @@ -4697,4 +4720,4 @@ public class Scanner implements IScanner, ITerminalSymbols { // this.foundTaskMessages[i] = message; // } // } -} \ No newline at end of file +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java index a22b3c4..3fce708 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/UnitParser.java @@ -48,21 +48,21 @@ public class UnitParser extends Parser { public void goForConstructorBody() { // tells the scanner to go for compilation unit parsing - firstToken = TokenNameEQUAL_EQUAL; + firstToken = TokenName.EQUAL_EQUAL; scanner.recordLineSeparator = false; } public void goForExpression() { // tells the scanner to go for an expression parsing - firstToken = TokenNameREMAINDER; + firstToken = TokenName.REMAINDER; scanner.recordLineSeparator = false; } public void goForCompilationUnit() { // tells the scanner to go for compilation unit parsing - firstToken = TokenNamePLUS_PLUS; + firstToken = TokenName.PLUS_PLUS; scanner.linePtr = -1; scanner.foundTaskCount = 0; scanner.recordLineSeparator = true; @@ -72,14 +72,14 @@ public class UnitParser extends Parser { public void goForInitializer() { // tells the scanner to go for initializer parsing - firstToken = TokenNameRIGHT_SHIFT; + firstToken = TokenName.RIGHT_SHIFT; scanner.recordLineSeparator = false; } public void goForMethodBody() { // tells the scanner to go for method body parsing - firstToken = TokenNameMINUS_MINUS; + firstToken = TokenName.MINUS_MINUS; scanner.recordLineSeparator = false; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java index 9758077..444d07e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/problem/ProblemReporter.java @@ -9,6 +9,7 @@ package net.sourceforge.phpdt.internal.compiler.problem; import net.sourceforge.phpdt.core.compiler.CharOperation; import net.sourceforge.phpdt.core.compiler.IProblem; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.internal.compiler.CompilationResult; import net.sourceforge.phpdt.internal.compiler.IErrorHandlingPolicy; @@ -3492,15 +3493,15 @@ public class ProblemReporter extends ProblemHandler implements ProblemReasons { try { Scanner scanner = new Scanner(); scanner.setSource(tokenSource); - int token = scanner.getNextToken(); + TokenName token = scanner.getNextToken(); char[] currentKeyword; try { currentKeyword = scanner.getCurrentIdentifierSource(); } catch (ArrayIndexOutOfBoundsException e) { return false; } - int nextToken = scanner.getNextToken(); - if (nextToken == Scanner.TokenNameEOF + TokenName nextToken = scanner.getNextToken(); + if (nextToken == Scanner.TokenName.EOF && scanner.startPosition == scanner.source.length) { // to // handle // case @@ -3511,7 +3512,7 @@ public class ProblemReporter extends ProblemHandler implements ProblemReasons { // ArrayIndexOutOfBoundsException // while reading the last token switch (token) { - case Scanner.TokenNameERROR: + case ERROR: if (CharOperation.equals("goto".toCharArray(), currentKeyword) || CharOperation.equals( @@ -3520,56 +3521,56 @@ public class ProblemReporter extends ProblemHandler implements ProblemReasons { } else { return false; } - case Scanner.TokenNameabstract: - // case Scanner.TokenNameassert: - // case Scanner.TokenNamebyte: - case Scanner.TokenNamebreak: - // case Scanner.TokenNameboolean: - case Scanner.TokenNamecase: - // case Scanner.TokenNamechar: - case Scanner.TokenNamecatch: - case Scanner.TokenNameclass: - case Scanner.TokenNamecontinue: - case Scanner.TokenNamedo: - // case Scanner.TokenNamedouble: - case Scanner.TokenNamedefault: - case Scanner.TokenNameelse: - case Scanner.TokenNameextends: - case Scanner.TokenNamefor: - // case Scanner.TokenNamefinal: - // case Scanner.TokenNamefloat: - // case Scanner.TokenNamefalse : - case Scanner.TokenNamefinally: - case Scanner.TokenNameif: - // case Scanner.TokenNameint: - // case Scanner.TokenNameimport: - case Scanner.TokenNameinterface: - case Scanner.TokenNameimplements: - case Scanner.TokenNameinstanceof: - // case Scanner.TokenNamelong: - case Scanner.TokenNamenew: - // case Scanner.TokenNamenull : - // case Scanner.TokenNamenative: - case Scanner.TokenNamepublic: - // case Scanner.TokenNamepackage: - case Scanner.TokenNameprivate: - case Scanner.TokenNameprotected: - case Scanner.TokenNamereturn: - // case Scanner.TokenNameshort: - case Scanner.TokenNamesuper: - case Scanner.TokenNamestatic: - case Scanner.TokenNameswitch: - // case Scanner.TokenNamestrictfp: - // case Scanner.TokenNamesynchronized: - case Scanner.TokenNametry: - // case Scanner.TokenNamethis : - // case Scanner.TokenNametrue : - case Scanner.TokenNamethrow: - // case Scanner.TokenNamethrows: - // case Scanner.TokenNametransient: - // case Scanner.TokenNamevoid: - // case Scanner.TokenNamevolatile: - case Scanner.TokenNamewhile: + case ABSTRACT: + // case ASSERT: + // case BYTE: + case BREAK: + // case BOOLEAN: + case CASE: + // case CHAR: + case CATCH: + case CLASS: + case CONTINUE: + case DO: + // case DOUBLE: + case DEFAULT: + case ELSE: + case EXTENDS: + case FOR: + // case FINAL: + // case FLOAT: + // case FALSE : + case FINALLY: + case IF: + // case INT: + // case IMPORT: + case INTERFACE: + case IMPLEMENTS: + case INSTANCEOF: + // case LONG: + case NEW: + // case NULL : + // case NATIVE: + case PUBLIC: + // case PACKAGE: + case PRIVATE: + case PROTECTED: + case RETURN: + // case SHORT: + case SUPER: + case STATIC: + case SWITCH: + // case STRICTFP: + // case SYNCHRONIZED: + case TRY: + // case THIS : + // case TRUE : + case THROW: + // case THROWS: + // case TRANSIENT: + // case VOID: + // case VOLATILE: + case WHILE: return true; default: return false; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java index d0c21dc..c9617e0 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java @@ -16,6 +16,7 @@ import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.core.jdom.IDOMMethod; import net.sourceforge.phpdt.core.jdom.IDOMNode; @@ -547,12 +548,12 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; scanner.resetTo(fNameRange[1] + 1, fDocument.length); try { - int currentToken = scanner.getNextToken(); - while (currentToken != ITerminalSymbols.TokenNameLBRACE - && currentToken != ITerminalSymbols.TokenNameEOF) { + TokenName currentToken = scanner.getNextToken(); + while (currentToken != ITerminalSymbols.TokenName.LBRACE + && currentToken != ITerminalSymbols.TokenName.EOF) { currentToken = scanner.getNextToken(); } - if (currentToken == ITerminalSymbols.TokenNameLBRACE) { + if (currentToken == ITerminalSymbols.TokenName.LBRACE) { openBodyEnd = scanner.currentPosition - 1; openBodyStart = scanner.startPosition; } else { @@ -581,12 +582,12 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; scanner.setSource(fDocument); scanner.resetTo(lastNode.getEndPosition() + 1, fDocument.length); try { - int currentToken = scanner.getNextToken(); - while (currentToken != ITerminalSymbols.TokenNameRBRACE - && currentToken != ITerminalSymbols.TokenNameEOF) { + TokenName currentToken = scanner.getNextToken(); + while (currentToken != ITerminalSymbols.TokenName.RBRACE + && currentToken != ITerminalSymbols.TokenName.EOF) { currentToken = scanner.getNextToken(); } - if (currentToken == ITerminalSymbols.TokenNameRBRACE) { + if (currentToken == ITerminalSymbols.TokenName.RBRACE) { closeBodyStart = scanner.startPosition; closeBodyEnd = scanner.currentPosition - 1; } else { @@ -600,12 +601,12 @@ import net.sourceforge.phpdt.internal.core.util.CharArrayOps; } else { scanner.resetTo(openBodyEnd, fDocument.length); try { - int currentToken = scanner.getNextToken(); - while (currentToken != ITerminalSymbols.TokenNameRBRACE - && currentToken != ITerminalSymbols.TokenNameEOF) { + TokenName currentToken = scanner.getNextToken(); + while (currentToken != ITerminalSymbols.TokenName.RBRACE + && currentToken != ITerminalSymbols.TokenName.EOF) { currentToken = scanner.getNextToken(); } - if (currentToken == ITerminalSymbols.TokenNameRBRACE) { + if (currentToken == ITerminalSymbols.TokenName.RBRACE) { closeBodyStart = scanner.startPosition; closeBodyEnd = scanner.currentPosition - 1; } else { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java index fc68d4f..c20030e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CommentRecorderScanner.java @@ -39,9 +39,9 @@ public class CommentRecorderScanner extends Scanner { * * @see net.sourceforge.phpdt.internal.compiler.parser.Scanner#recordComment(int) */ - public void recordComment(int token) { + public void recordComment(TokenName token) { super.recordComment(token); - if (token == TokenNameCOMMENT_LINE) { + if (token == TokenName.COMMENT_LINE) { // for comment line both positions are negative this.commentStarts[this.commentPtr] = -this.commentStarts[this.commentPtr]; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PHPFileUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PHPFileUtil.java index f1a9d67..784fed1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PHPFileUtil.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/PHPFileUtil.java @@ -7,9 +7,7 @@ package net.sourceforge.phpdt.internal.core.util; import java.io.File; //import java.util.List; -//import net.sourceforge.phpeclipse.PHPeclipsePlugin; import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.ui.WebUI; //import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil; import org.eclipse.core.filebuffers.FileBuffers; diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/IRequestQuery.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java new file mode 100644 index 0000000..0015661 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/StubUtility.java @@ -0,0 +1,1445 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.corext.codemanipulation; + +//import java.util.Arrays; +//import java.util.Comparator; +//import java.util.List; +//import java.util.StringTokenizer; + +//import net.sourceforge.phpdt.core.Flags; +//import net.sourceforge.phpdt.core.IBuffer; +import net.sourceforge.phpdt.core.ICodeFormatter; +import net.sourceforge.phpdt.core.ICompilationUnit; +//import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IPackageFragment; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.Signature; +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.internal.corext.util.Strings; +import net.sourceforge.phpdt.internal.corext.util.PHPUIStatus; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateBuffer; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateVariable; +//import org.eclipse.swt.SWT; + +public class StubUtility { + + public static class GenStubSettings extends CodeGenerationSettings { + + public boolean callSuper; + + public boolean methodOverwrites; + + public boolean noBody; + + public int methodModifiers; + + public GenStubSettings(CodeGenerationSettings settings) { + settings.setSettings(this); + methodModifiers = -1; + } + + } + + //private static final String[] EMPTY = new String[0]; + + /** + * Generates a method stub including the method comment. Given a template + * method, a stub with the same signature will be constructed so it can be + * added to a type. The method body will be empty or contain a return or + * super call. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param definingType + * The type that defines the method. + * @param settings + * Options as defined above (GenStubSettings) + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @throws JavaModelException + */ +// public static String genStub(ICompilationUnit cu, String destTypeName, +// IMethod method, IType definingType, GenStubSettings settings) +// throws CoreException { +// // IImportsStructure imports) throws CoreException { +// String methName = method.getElementName(); +// String[] paramNames = suggestArgumentNames(method.getJavaProject(), +// method.getParameterNames()); +// String returnType = method.isConstructor() ? null : method +// .getReturnType(); +// String lineDelimiter = String.valueOf('\n'); // reformatting required +// +// StringBuffer buf = new StringBuffer(); +// // add method comment +// if (settings.createComments && cu != null) { +// IMethod overridden = null; +// if (settings.methodOverwrites && returnType != null) { +// overridden = JavaModelUtil.findMethod(methName, method +// .getParameterTypes(), false, definingType.getMethods()); +// } +// String comment = getMethodComment(cu, destTypeName, methName, +// paramNames, method.getExceptionTypes(), returnType, +// overridden, lineDelimiter); +// if (comment != null) { +// buf.append(comment); +// } else { +// buf.append("/**").append(lineDelimiter); //$NON-NLS-1$ +// buf.append(" *").append(lineDelimiter); //$NON-NLS-1$ +// buf.append(" */").append(lineDelimiter); //$NON-NLS-1$ +// } +// buf.append(lineDelimiter); +// } +// // add method declaration +// String bodyContent = null; +// if (!settings.noBody) { +// String bodyStatement = getDefaultMethodBodyStatement(methName, +// paramNames, returnType, settings.callSuper); +// bodyContent = getMethodBodyContent(returnType == null, method +// .getJavaProject(), destTypeName, methName, bodyStatement, +// lineDelimiter); +// if (bodyContent == null) { +// bodyContent = ""; //$NON-NLS-1$ +// } +// } +// int flags = settings.methodModifiers; +// if (flags == -1) { +// flags = method.getFlags(); +// } +// +// genMethodDeclaration(destTypeName, method, flags, bodyContent, buf); // imports, +// // buf); +// return buf.toString(); +// } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param bodyContent + * Content of the body + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @param buf + * The buffer to append the gerenated code. + * @throws JavaModelException + */ +// public static void genMethodDeclaration(String destTypeName, +// IMethod method, String bodyContent, StringBuffer buf) +// throws CoreException { // IImportsStructure imports, StringBuffer +// // buf) throws CoreException { +// genMethodDeclaration(destTypeName, method, method.getFlags(), +// bodyContent, buf); +// } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * + * @param destTypeName + * The name of the type to which the method will be added to + * @param method + * A method template (method belongs to different type than the + * parent) + * @param bodyContent + * Content of the body + * @param imports + * Imports required by the stub are added to the imports + * structure. If imports structure is null all + * type names are qualified. + * @param buf + * The buffer to append the gerenated code. + * @throws JavaModelException + */ +// public static void genMethodDeclaration(String destTypeName, +// IMethod method, int flags, String bodyContent, StringBuffer buf) +// throws CoreException { +// // IImportsStructure imports, StringBuffer buf) throws CoreException { +// IType parentType = method.getDeclaringType(); +// String methodName = method.getElementName(); +// String[] paramTypes = method.getParameterTypes(); +// String[] paramNames = suggestArgumentNames(parentType.getJavaProject(), +// method.getParameterNames()); +// +// String[] excTypes = method.getExceptionTypes(); +// +// boolean isConstructor = method.isConstructor(); +// String retTypeSig = isConstructor ? null : method.getReturnType(); +// +// int lastParam = paramTypes.length - 1; +// +// if (Flags.isPublic(flags) +// || (parentType.isInterface() && bodyContent != null)) { +// buf.append("public "); //$NON-NLS-1$ +// } else if (Flags.isProtected(flags)) { +// buf.append("protected "); //$NON-NLS-1$ +// } else if (Flags.isPrivate(flags)) { +// buf.append("private "); //$NON-NLS-1$ +// } +// // if (Flags.isSynchronized(flags)) { +// // buf.append("synchronized "); //$NON-NLS-1$ +// // } +// // if (Flags.isVolatile(flags)) { +// // buf.append("volatile "); //$NON-NLS-1$ +// // } +// // if (Flags.isStrictfp(flags)) { +// // buf.append("strictfp "); //$NON-NLS-1$ +// // } +// if (Flags.isStatic(flags)) { +// buf.append("static "); //$NON-NLS-1$ +// } +// +// if (isConstructor) { +// buf.append(destTypeName); +// } else { +// String retTypeFrm; +// if (!isPrimitiveType(retTypeSig)) { +// retTypeFrm = resolveAndAdd(retTypeSig, parentType); +// } else { +// retTypeFrm = Signature.toString(retTypeSig); +// } +// buf.append(retTypeFrm); +// buf.append(' '); +// buf.append(methodName); +// } +// buf.append('('); +// for (int i = 0; i <= lastParam; i++) { +// String paramTypeSig = paramTypes[i]; +// String paramTypeFrm; +// +// if (!isPrimitiveType(paramTypeSig)) { +// paramTypeFrm = resolveAndAdd(paramTypeSig, parentType); +// } else { +// paramTypeFrm = Signature.toString(paramTypeSig); +// } +// buf.append(paramTypeFrm); +// buf.append(' '); +// buf.append(paramNames[i]); +// if (i < lastParam) { +// buf.append(", "); //$NON-NLS-1$ +// } +// } +// buf.append(')'); +// +// int lastExc = excTypes.length - 1; +// if (lastExc >= 0) { +// buf.append(" throws "); //$NON-NLS-1$ +// for (int i = 0; i <= lastExc; i++) { +// String excTypeSig = excTypes[i]; +// String excTypeFrm = resolveAndAdd(excTypeSig, parentType); +// buf.append(excTypeFrm); +// if (i < lastExc) { +// buf.append(", "); //$NON-NLS-1$ +// } +// } +// } +// if (bodyContent == null) { +// buf.append(";\n\n"); //$NON-NLS-1$ +// } else { +// buf.append(" {\n\t"); //$NON-NLS-1$ +// if ((bodyContent != null) && (bodyContent.length() > 0)) { +// buf.append(bodyContent); +// buf.append('\n'); +// } +// buf.append("}\n"); //$NON-NLS-1$ +// } +// } + +// public static String getDefaultMethodBodyStatement(String methodName, +// String[] paramNames, String retTypeSig, boolean callSuper) { +// StringBuffer buf = new StringBuffer(); +// if (callSuper) { +// if (retTypeSig != null) { +// if (!Signature.SIG_VOID.equals(retTypeSig)) { +// buf.append("return "); //$NON-NLS-1$ +// } +// buf.append("super."); //$NON-NLS-1$ +// buf.append(methodName); +// } else { +// buf.append("super"); //$NON-NLS-1$ +// } +// buf.append('('); +// for (int i = 0; i < paramNames.length; i++) { +// if (i > 0) { +// buf.append(", "); //$NON-NLS-1$ +// } +// buf.append(paramNames[i]); +// } +// buf.append(");"); //$NON-NLS-1$ +// } else { +// if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { +// if (!isPrimitiveType(retTypeSig) +// || Signature.getArrayCount(retTypeSig) > 0) { +// buf.append("return null;"); //$NON-NLS-1$ +// } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { +// buf.append("return false;"); //$NON-NLS-1$ +// } else { +// buf.append("return 0;"); //$NON-NLS-1$ +// } +// } +// } +// return buf.toString(); +// } + + public static String getMethodBodyContent(boolean isConstructor, + IJavaProject project, String destTypeName, String methodName, + String bodyStatement, String lineDelimiter) throws CoreException { + String templateName = isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB + : CodeTemplateContextType.METHODSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return bodyStatement; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.BODY_STATEMENT, + bodyStatement); + String str = evaluateTemplate(context, template); + if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) { + return bodyStatement; + } + return str; + } + + public static String getGetterMethodBodyContent(IJavaProject project, + String destTypeName, String methodName, String fieldName, + String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.GETTERSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + public static String getSetterMethodBodyContent(IJavaProject project, + String destTypeName, String methodName, String fieldName, + String paramName, String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.SETTERSTUB; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, + destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + +// public static String getCatchBodyContent(ICompilationUnit cu, +// String exceptionType, String variableName, String lineDelimiter) +// throws CoreException { +// Template template = PHPeclipsePlugin.getDefault() +// .getCodeTemplateStore().findTemplate( +// CodeTemplateContextType.CATCHBLOCK); +// if (template == null) { +// return null; +// } +// +// CodeTemplateContext context = new CodeTemplateContext(template +// .getContextTypeId(), cu.getJavaProject(), lineDelimiter); +// context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, +// exceptionType); +// context +// .setVariable(CodeTemplateContextType.EXCEPTION_VAR, +// variableName); //$NON-NLS-1$ +// return evaluateTemplate(context, template); +// } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, + * String, String) + */ + public static String getCompilationUnitContent(ICompilationUnit cu, + String typeComment, String typeContent, String lineDelimiter) + throws CoreException { + IPackageFragment pack = (IPackageFragment) cu.getParent(); + String packDecl = pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$ + + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + + IJavaProject project = cu.getJavaProject(); + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), project, lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, + packDecl); + context.setVariable(CodeTemplateContextType.TYPE_COMMENT, + typeComment != null ? typeComment : ""); //$NON-NLS-1$ + context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, + typeContent); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature + .getQualifier(cu.getElementName())); + return evaluateTemplate(context, template); + } + + /* + * @see net.sourceforge.phpdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, + * String, String) + */ + public static String getTypeComment(ICompilationUnit cu, + String typeQualifiedName, String lineDelim) throws CoreException { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.TYPECOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelim); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature + .getQualifier(typeQualifiedName)); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature + .getSimpleName(typeQualifiedName)); + return evaluateTemplate(context, template); + } + + // private static String[] getParameterTypesQualifiedNames(IMethodBinding + // binding) { + // ITypeBinding[] typeBindings= binding.getParameterTypes(); + // String[] result= new String[typeBindings.length]; + // for (int i= 0; i < result.length; i++) { + // result[i]= typeBindings[i].getQualifiedName(); + // } + // return result; + // } + +// private static String getSeeTag(String declaringClassQualifiedName, +// String methodName, String[] parameterTypesQualifiedNames) { +// StringBuffer buf = new StringBuffer(); +// buf.append("@see "); //$NON-NLS-1$ +// buf.append(declaringClassQualifiedName); +// buf.append('#'); +// buf.append(methodName); +// buf.append('('); +// for (int i = 0; i < parameterTypesQualifiedNames.length; i++) { +// if (i > 0) { +// buf.append(", "); //$NON-NLS-1$ +// } +// buf.append(parameterTypesQualifiedNames[i]); +// } +// buf.append(')'); +// return buf.toString(); +// } + + private static String getSeeTag(IMethod overridden) + throws JavaModelException { + IType declaringType = overridden.getDeclaringType(); + StringBuffer buf = new StringBuffer(); + buf.append("@see "); //$NON-NLS-1$ + buf.append(declaringType.getFullyQualifiedName('.')); + buf.append('#'); + buf.append(overridden.getElementName()); + buf.append('('); + String[] paramTypes = overridden.getParameterTypes(); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ + } + String curr = paramTypes[i]; + buf.append(JavaModelUtil.getResolvedTypeName(curr, declaringType)); + int arrayCount = Signature.getArrayCount(curr); + while (arrayCount > 0) { + buf.append("[]"); //$NON-NLS-1$ + arrayCount--; + } + } + buf.append(')'); + return buf.toString(); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(IMethod,IMethod,String) + */ + public static String getMethodComment(IMethod method, IMethod overridden, + String lineDelimiter) throws CoreException { + String retType = method.isConstructor() ? null : method.getReturnType(); + String[] paramNames = method.getParameterNames(); + + return getMethodComment(method.getCompilationUnit(), method + .getDeclaringType().getElementName(), method.getElementName(), + paramNames, method.getExceptionTypes(), retType, overridden, + lineDelimiter); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, + * String, String, String[], String[], String, IMethod, String) + */ + public static String getMethodComment(ICompilationUnit cu, String typeName, + String methodName, String[] paramNames, String[] excTypeSig, + String retTypeSig, IMethod overridden, String lineDelimiter) + throws CoreException { + String templateName = CodeTemplateContextType.METHODCOMMENT; + if (retTypeSig == null) { + templateName = CodeTemplateContextType.CONSTRUCTORCOMMENT; + } else if (overridden != null) { + templateName = CodeTemplateContextType.OVERRIDECOMMENT; + } + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + + if (retTypeSig != null) { + context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature + .toString(retTypeSig)); + } + if (overridden != null) { + context.setVariable(CodeTemplateContextType.SEE_TAG, + getSeeTag(overridden)); + } + TemplateBuffer buffer; + try { + buffer = context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) { + return null; + } + + String str = buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + TemplateVariable position = findTagVariable(buffer); // look if + // Javadoc tags + // have to be + // added + if (position == null) { + return str; + } + + IDocument textBuffer = new Document(str); + String[] exceptionNames = new String[excTypeSig.length]; + for (int i = 0; i < excTypeSig.length; i++) { + exceptionNames[i] = Signature.toString(excTypeSig[i]); + } + String returnType = retTypeSig != null ? Signature.toString(retTypeSig) + : null; + int[] tagOffsets = position.getOffsets(); + for (int i = tagOffsets.length - 1; i >= 0; i--) { // from last to + // first + try { + insertTag(textBuffer, tagOffsets[i], position.getLength(), + paramNames, exceptionNames, returnType, false, + lineDelimiter); + } catch (BadLocationException e) { + throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, + e)); + } + } + return textBuffer.get(); + } + + public static String getFieldComment(ICompilationUnit cu, String typeName, + String fieldName, String lineDelimiter) throws CoreException { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.FIELDCOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, + * String, String, String, String, String, String, String) + */ + public static String getSetterComment(ICompilationUnit cu, String typeName, + String methodName, String fieldName, String fieldType, + String paramName, String bareFieldName, String lineDelimiter) + throws CoreException { + String templateName = CodeTemplateContextType.SETTERCOMMENT; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, + bareFieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, + * String, String, String, String, String, String) + */ + public static String getGetterComment(ICompilationUnit cu, String typeName, + String methodName, String fieldName, String fieldType, + String bareFieldName, String lineDelimiter) throws CoreException { + String templateName = CodeTemplateContextType.GETTERCOMMENT; + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, + bareFieldName); + + return evaluateTemplate(context, template); + } + + public static String evaluateTemplate(CodeTemplateContext context, + Template template) throws CoreException { + TemplateBuffer buffer; + try { + buffer = context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) + return null; + String str = buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + return str; + } + + /** + * @see net.sourceforge.phpdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, + * String, MethodDeclaration, IMethodBinding, String) + */ + // public static String getMethodComment(ICompilationUnit cu, String + // typeName, IMethodBinding overridden, String lineDelimiter) throws + // CoreException { + // if (overridden != null) { + // String declaringClassQualifiedName= + // overridden.getDeclaringClass().getQualifiedName(); + // String[] parameterTypesQualifiedNames= + // getParameterTypesQualifiedNames(overridden); + // return getMethodComment(cu, typeName, decl, true, + // overridden.isDeprecated(), declaringClassQualifiedName, + // parameterTypesQualifiedNames, lineDelimiter); + // } else { + // return getMethodComment(cu, typeName, decl, false, false, null, null, + // lineDelimiter); + // } + // } + /** + * Returns the comment for a method using the comment code templates. + * null is returned if the template is empty. + * + * @param cu + * The compilation unit to which the method belongs + * @param typeName + * Name of the type to which the method belongs. + * @param decl + * The AST MethodDeclaration node that will be added as new + * method. + * @param isOverridden + * true iff decl overrides another method + * @param isDeprecated + * true iff the method that decl overrides is + * deprecated. Note: it must not be true if + * isOverridden is false. + * @param declaringClassQualifiedName + * Fully qualified name of the type in which the overriddden + * method (if any exists) in declared. If isOverridden is + * false, this is ignored. + * @param parameterTypesQualifiedNames + * Fully qualified names of parameter types of the type in which + * the overriddden method (if any exists) in declared. If + * isOverridden is false, this is ignored. + * @return String Returns the method comment or null if the + * configured template is empty. (formatting required) + * @throws CoreException + */ + // public static String getMethodComment(ICompilationUnit cu, String + // typeName, MethodDeclaration decl, boolean isOverridden, boolean + // isDeprecated, String declaringClassQualifiedName, String[] + // parameterTypesQualifiedNames, String lineDelimiter) throws CoreException + // { + // String templateName= CodeTemplateContextType.METHODCOMMENT; + // if (decl.isConstructor()) { + // templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; + // } else if (isOverridden) { + // templateName= CodeTemplateContextType.OVERRIDECOMMENT; + // } + // Template template= + // PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + // if (template == null) { + // return null; + // } + // CodeTemplateContext context= new + // CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), + // lineDelimiter); + // context.setCompilationUnitVariables(cu); + // context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + // context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, + // decl.getName().getIdentifier()); + // if (!decl.isConstructor()) { + // context.setVariable(CodeTemplateContextType.RETURN_TYPE, + // ASTNodes.asString(decl.getReturnType())); + // } + // if (isOverridden) { + // String methodName= decl.getName().getIdentifier(); + // context.setVariable(CodeTemplateContextType.SEE_TAG, + // getSeeTag(declaringClassQualifiedName, methodName, + // parameterTypesQualifiedNames)); + // } + // + // TemplateBuffer buffer; + // try { + // buffer= context.evaluate(template); + // } catch (BadLocationException e) { + // throw new CoreException(Status.CANCEL_STATUS); + // } catch (TemplateException e) { + // throw new CoreException(Status.CANCEL_STATUS); + // } + // if (buffer == null) + // return null; + // String str= buffer.getString(); + // if (Strings.containsOnlyWhitespaces(str)) { + // return null; + // } + // TemplateVariable position= findTagVariable(buffer); // look if Javadoc + // tags have to be added + // if (position == null) { + // return str; + // } + // + // IDocument textBuffer= new Document(str); + // List params= decl.parameters(); + // String[] paramNames= new String[params.size()]; + // for (int i= 0; i < params.size(); i++) { + // SingleVariableDeclaration elem= (SingleVariableDeclaration) + // params.get(i); + // paramNames[i]= elem.getName().getIdentifier(); + // } + // List exceptions= decl.thrownExceptions(); + // String[] exceptionNames= new String[exceptions.size()]; + // for (int i= 0; i < exceptions.size(); i++) { + // exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) + // exceptions.get(i)); + // } + // String returnType= !decl.isConstructor() ? + // ASTNodes.asString(decl.getReturnType()) : null; + // int[] tagOffsets= position.getOffsets(); + // for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first + // try { + // insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, + // exceptionNames, returnType, isDeprecated, lineDelimiter); + // } catch (BadLocationException e) { + // throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); + // } + // } + // return textBuffer.get(); + // } + private static TemplateVariable findTagVariable(TemplateBuffer buffer) { + TemplateVariable[] positions = buffer.getVariables(); + for (int i = 0; i < positions.length; i++) { + TemplateVariable curr = positions[i]; + if (CodeTemplateContextType.TAGS.equals(curr.getType())) { + return curr; + } + } + return null; + } + + private static void insertTag(IDocument textBuffer, int offset, int length, + String[] paramNames, String[] exceptionNames, String returnType, + boolean isDeprecated, String lineDelimiter) + throws BadLocationException { + IRegion region = textBuffer.getLineInformationOfOffset(offset); + if (region == null) { + return; + } + String lineStart = textBuffer.get(region.getOffset(), offset + - region.getOffset()); + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < paramNames.length; i++) { + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); + } + buf.append("@param ");buf.append(paramNames[i]); //$NON-NLS-1$ + } + if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$ + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); + } + buf.append("@return"); //$NON-NLS-1$ + } + if (exceptionNames != null) { + for (int i = 0; i < exceptionNames.length; i++) { + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); + } + buf.append("@throws ");buf.append(exceptionNames[i]); //$NON-NLS-1$ + } + } + if (isDeprecated) { + if (buf.length() > 0) { + buf.append(lineDelimiter); + buf.append(lineStart); + } + buf.append("@deprecated"); //$NON-NLS-1$ + } + textBuffer.replace(offset, length, buf.toString()); + } + +// private static boolean isPrimitiveType(String typeName) { +// char first = Signature.getElementType(typeName).charAt(0); +// return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); +// } + +// private static String resolveAndAdd(String refTypeSig, IType declaringType) +// throws JavaModelException {// , IImportsStructure imports) throws +// // JavaModelException { +// String resolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, +// declaringType); +// if (resolvedTypeName != null) { +// StringBuffer buf = new StringBuffer(); +// // if (imports != null) { +// // buf.append(imports.addImport(resolvedTypeName)); +// // } else { +// buf.append(resolvedTypeName); +// // } +// int arrayCount = Signature.getArrayCount(refTypeSig); +// for (int i = 0; i < arrayCount; i++) { +// buf.append("[]"); //$NON-NLS-1$ +// } +// return buf.toString(); +// } +// return Signature.toString(refTypeSig); +// } + + /** + * Finds a method in a list of methods. + * + * @return The found method or null, if nothing found + */ +// private static IMethod findMethod(IMethod method, List allMethods) +// throws JavaModelException { +// String name = method.getElementName(); +// String[] paramTypes = method.getParameterTypes(); +// boolean isConstructor = method.isConstructor(); +// +// for (int i = allMethods.size() - 1; i >= 0; i--) { +// IMethod curr = (IMethod) allMethods.get(i); +// if (JavaModelUtil.isSameMethodSignature(name, paramTypes, +// isConstructor, curr)) { +// return curr; +// } +// } +// return null; +// } + + /** + * Creates needed constructors for a type. + * + * @param type + * The type to create constructors for + * @param supertype + * The type's super type + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static String[] evalConstructors(IType type, IType supertype, + // IImportsStructure imports) throws CoreException { + // IMethod[] superMethods= supertype.getMethods(); + // String typeName= type.getElementName(); + // ICompilationUnit cu= type.getCompilationUnit(); + // IMethod[] methods= type.getMethods(); + // GenStubSettings genStubSettings= new GenStubSettings(settings); + // genStubSettings.callSuper= true; + // + // ArrayList newMethods= new ArrayList(superMethods.length); + // for (int i= 0; i < superMethods.length; i++) { + // IMethod curr= superMethods[i]; + // if (curr.isConstructor() && (JavaModelUtil.isVisibleInHierarchy(curr, + // type.getPackageFragment()))) { + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) { + // genStubSettings.methodModifiers= Flags.AccPublic | + // JdtFlags.clearAccessModifiers(curr.getFlags()); + // String newStub= genStub(cu, typeName, curr, curr.getDeclaringType(), + // genStubSettings, imports); + // newMethods.add(newStub); + // } + // } + // } + // return (String[]) newMethods.toArray(new String[newMethods.size()]); + // } + /** + * Returns all unimplemented constructors of a type including root type + * default constructors if there are no other superclass constructors + * unimplemented. + * + * @param type + * The type to create constructors for + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static IMethod[] getOverridableConstructors(IType type) throws + // CoreException { + // List constructorMethods= new ArrayList(); + // ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); + // IType supertype= hierarchy.getSuperclass(type); + // if (supertype == null) + // return (new IMethod[0]); + // + // IMethod[] superMethods= supertype.getMethods(); + // boolean constuctorFound= false; + // String typeName= type.getElementName(); + // IMethod[] methods= type.getMethods(); + // for (int i= 0; i < superMethods.length; i++) { + // IMethod curr= superMethods[i]; + // if (curr.isConstructor()) { + // constuctorFound= true; + // if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) + // constructorMethods.add(curr); + // + // } + // } + // + // // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38487 + // if (!constuctorFound) { + // IType objectType= type.getJavaProject().findType("java.lang.Object"); + // //$NON-NLS-1$ + // IMethod curr= objectType.getMethod("Object", EMPTY); //$NON-NLS-1$ + // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, + // methods) == null) { + // constructorMethods.add(curr); + // } + // } + // return (IMethod[]) constructorMethods.toArray(new + // IMethod[constructorMethods.size()]); + // } + /** + * Returns all overridable methods of a type + * + * @param type + * The type to search the overridable methods for + * @param hierarchy + * The type hierarchy of the type + * @param isSubType + * If set, the result can include methods of the passed type, if + * not only methods from super types are considered + * @return Returns the all methods that can be overridden + */ + // public static IMethod[] getOverridableMethods(IType type, ITypeHierarchy + // hierarchy, boolean isSubType) throws JavaModelException { + // List allMethods= new ArrayList(); + // + // IMethod[] typeMethods= type.getMethods(); + // for (int i= 0; i < typeMethods.length; i++) { + // IMethod curr= typeMethods[i]; + // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && + // !Flags.isPrivate(curr.getFlags())) { + // allMethods.add(curr); + // } + // } + // + // IType[] superTypes= hierarchy.getAllSuperclasses(type); + // for (int i= 0; i < superTypes.length; i++) { + // IMethod[] methods= superTypes[i].getMethods(); + // for (int k= 0; k < methods.length; k++) { + // IMethod curr= methods[k]; + // if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && + // !Flags.isPrivate(curr.getFlags())) { + // if (findMethod(curr, allMethods) == null) { + // allMethods.add(curr); + // } + // } + // } + // } + // + // IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); + // for (int i= 0; i < superInterfaces.length; i++) { + // IMethod[] methods= superInterfaces[i].getMethods(); + // for (int k= 0; k < methods.length; k++) { + // IMethod curr= methods[k]; + // + // // binary interfaces can contain static initializers (variable + // intializations) + // // 1G4CKUS + // if (!Flags.isStatic(curr.getFlags())) { + // IMethod impl= findMethod(curr, allMethods); + // if (impl == null || !JavaModelUtil.isVisibleInHierarchy(impl, + // type.getPackageFragment()) || prefereInterfaceMethod(hierarchy, curr, + // impl)) { + // if (impl != null) { + // allMethods.remove(impl); + // } + // // implement an interface method when it does not exist in the hierarchy + // // or when it throws less exceptions that the implemented + // allMethods.add(curr); + // } + // } + // } + // } + // if (!isSubType) { + // allMethods.removeAll(Arrays.asList(typeMethods)); + // } + // // remove finals + // for (int i= allMethods.size() - 1; i >= 0; i--) { + // IMethod curr= (IMethod) allMethods.get(i); + // if (Flags.isFinal(curr.getFlags())) { + // allMethods.remove(i); + // } + // } + // return (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); + // } + // private static boolean prefereInterfaceMethod(ITypeHierarchy hierarchy, + // IMethod interfaceMethod, IMethod curr) throws JavaModelException { + // if (Flags.isFinal(curr.getFlags())) { + // return false; + // } + // IType interfaceType= interfaceMethod.getDeclaringType(); + // IType[] interfaces= + // hierarchy.getAllSuperInterfaces(curr.getDeclaringType()); + // for (int i= 0; i < interfaces.length; i++) { + // if (interfaces[i] == interfaceType) { + // return false; + // } + // } + // return curr.getExceptionTypes().length > + // interfaceMethod.getExceptionTypes().length; + // } + /** + * Generate method stubs for methods to overrride + * + * @param type + * The type to search the overridable methods for + * @param hierarchy + * The type hierarchy of the type + * @param methodsToImplement + * Methods to override or implement + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs + */ + // public static String[] genOverrideStubs(IMethod[] methodsToImplement, + // IType type, ITypeHierarchy hierarchy, CodeGenerationSettings settings, + // IImportsStructure imports) throws CoreException { + // GenStubSettings genStubSettings= new GenStubSettings(settings); + // genStubSettings.methodOverwrites= true; + // ICompilationUnit cu= type.getCompilationUnit(); + // String[] result= new String[methodsToImplement.length]; + // for (int i= 0; i < methodsToImplement.length; i++) { + // IMethod curr= methodsToImplement[i]; + // IMethod overrides= + // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, + // curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); + // if (overrides != null) { + // genStubSettings.callSuper= true; + // curr= overrides; + // } + // genStubSettings.methodModifiers= curr.getFlags(); + // IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, + // type, curr.getElementName(), curr.getParameterTypes(), + // curr.isConstructor()); + // if (desc == null) { + // desc= curr; + // } + // result[i]= genStub(cu, type.getElementName(), curr, + // desc.getDeclaringType(), genStubSettings, imports); + // } + // return result; + // } + /** + * Searches for unimplemented methods of a type. + * + * @param isSubType + * If set, the evaluation is for a subtype of the given type. If + * not set, the evaluation is for the type itself. + * @param settings + * Options for comment generation + * @param imports + * Required imports are added to the import structure. Structure + * can be null, types are qualified then. + * @return Returns the generated stubs or null if the + * creation has been canceled + */ + // public static String[] evalUnimplementedMethods(IType type, + // ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings + // settings, + // IImportsStructure imports) throws CoreException { + // + // IMethod[] inheritedMethods= getOverridableMethods(type, hierarchy, + // isSubType); + // + // List toImplement= new ArrayList(); + // for (int i= 0; i < inheritedMethods.length; i++) { + // IMethod curr= inheritedMethods[i]; + // if (JdtFlags.isAbstract(curr)) { + // toImplement.add(curr); + // } + // } + // IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new + // IMethod[toImplement.size()]); + // return genOverrideStubs(toImplementArray, type, hierarchy, settings, + // imports); + // } + /** + * Examines a string and returns the first line delimiter found. + */ +// public static String getLineDelimiterUsed(IJavaElement elem) +// throws JavaModelException { +// ICompilationUnit cu = (ICompilationUnit) elem +// .getAncestor(IJavaElement.COMPILATION_UNIT); +// if (cu != null && cu.exists()) { +// IBuffer buf = cu.getBuffer(); +// int length = buf.getLength(); +// for (int i = 0; i < length; i++) { +// char ch = buf.getChar(i); +// if (ch == SWT.CR) { +// if (i + 1 < length) { +// if (buf.getChar(i + 1) == SWT.LF) { +// return "\r\n"; //$NON-NLS-1$ +// } +// } +// return "\r"; //$NON-NLS-1$ +// } else if (ch == SWT.LF) { +// return "\n"; //$NON-NLS-1$ +// } +// } +// } +// return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ +// } + + /** + * Embodies the policy which line delimiter to use when inserting into a + * document. + */ + public static String getLineDelimiterFor(IDocument doc) { + // new for: 1GF5UU0: ITPJUI:WIN2000 - "Organize Imports" in php editor + // inserts lines in wrong format + String lineDelim = null; + try { + lineDelim = doc.getLineDelimiter(0); + } catch (BadLocationException e) { + } + if (lineDelim == null) { + String systemDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + String[] lineDelims = doc.getLegalLineDelimiters(); + for (int i = 0; i < lineDelims.length; i++) { + if (lineDelims[i].equals(systemDelimiter)) { + lineDelim = systemDelimiter; + break; + } + } + if (lineDelim == null) { + lineDelim = lineDelims.length > 0 ? lineDelims[0] + : systemDelimiter; + } + } + return lineDelim; + } + + /** + * Evaluates the indention used by a Java element. (in tabulators) + */ + // public static int getIndentUsed(IJavaElement elem) throws + // JavaModelException { + // if (elem instanceof ISourceReference) { + // ICompilationUnit cu= (ICompilationUnit) + // elem.getAncestor(IJavaElement.COMPILATION_UNIT); + // if (cu != null) { + // IBuffer buf= cu.getBuffer(); + // int offset= ((ISourceReference)elem).getSourceRange().getOffset(); + // int i= offset; + // // find beginning of line + // while (i > 0 && !Strings.isLineDelimiterChar(buf.getChar(i - 1)) ){ + // i--; + // } + // return Strings.computeIndent(buf.getText(i, offset - i), + // CodeFormatterUtil.getTabWidth()); + // } + // } + // return 0; + // } + public static String codeFormat(String sourceString, + int initialIndentationLevel, String lineDelim) { + ICodeFormatter formatter = ToolFactory.createDefaultCodeFormatter(null); + return formatter.format(sourceString, initialIndentationLevel, null, + lineDelim); + } + + /** + * Returns the element after the give element. + */ + // public static IJavaElement findNextSibling(IJavaElement member) throws + // JavaModelException { + // IJavaElement parent= member.getParent(); + // if (parent instanceof IParent) { + // IJavaElement[] elements= ((IParent)parent).getChildren(); + // for (int i= elements.length - 2; i >= 0 ; i--) { + // if (member.equals(elements[i])) { + // return elements[i+1]; + // } + // } + // } + // return null; + // } + // + public static String getTodoTaskTag(IJavaProject project) { + String markers = null; + if (project == null) { + markers = JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS); + } else { + markers = project.getOption(JavaCore.COMPILER_TASK_TAGS, true); + } + + if (markers != null && markers.length() > 0) { + int idx = markers.indexOf(','); + if (idx == -1) { + return markers; + } else { + return markers.substring(0, idx); + } + } + return null; + } + + /* + * Workarounds for bug 38111 + */ + // public static String[] getArgumentNameSuggestions(IJavaProject project, + // String baseName, int dimensions, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestArgumentNames(project, "", name, + // dimensions, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } + // + // public static String[] getFieldNameSuggestions(IJavaProject project, + // String baseName, int dimensions, int modifiers, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestFieldNames(project, "", name, + // dimensions, modifiers, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } + // + // public static String[] getLocalNameSuggestions(IJavaProject project, + // String baseName, int dimensions, String[] excluded) { + // String name= workaround38111(baseName); + // String[] res= NamingConventions.suggestLocalVariableNames(project, "", + // name, dimensions, excluded); //$NON-NLS-1$ + // return sortByLength(res); // longest first + // } +// private static String[] sortByLength(String[] proposals) { +// Arrays.sort(proposals, new Comparator() { +// public int compare(Object o1, Object o2) { +// return ((String) o2).length() - ((String) o1).length(); +// } +// }); +// return proposals; +// } + +/* private static String workaround38111(String baseName) { + if (BASE_TYPES.contains(baseName)) + return baseName; + return Character.toUpperCase(baseName.charAt(0)) + + baseName.substring(1); + } +*/ +// private static final List BASE_TYPES = Arrays +// .asList(new String[] { +// "boolean", "byte", "char", "double", "float", "int", "long", "short" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + +// public static String suggestArgumentName(IJavaProject project, +// String baseName, String[] excluded) { +// // String[] argnames= getArgumentNameSuggestions(project, baseName, 0, +// // excluded); +// // if (argnames.length > 0) { +// // return argnames[0]; +// // } +// return baseName; +// } + +// public static String[] suggestArgumentNames(IJavaProject project, +// String[] paramNames) { +// String prefixes = project.getOption( +// JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); +// String suffixes = project.getOption( +// JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); +// if (prefixes.length() + suffixes.length() == 0) { +// return paramNames; +// } +// +// String[] newNames = new String[paramNames.length]; +// // Ensure that the codegeneration preferences are respected +// for (int i = 0; i < paramNames.length; i++) { +// String curr = paramNames[i]; +// if (!hasPrefixOrSuffix(prefixes, suffixes, curr)) { +// newNames[i] = suggestArgumentName(project, paramNames[i], null); +// } else { +// newNames[i] = curr; +// } +// } +// return newNames; +// } + +// public static boolean hasFieldName(IJavaProject project, String name) { +// String prefixes = project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, +// true); +// String suffixes = project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, +// true); +// String staticPrefixes = project.getOption( +// JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true); +// String staticSuffixes = project.getOption( +// JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true); +// +// return hasPrefixOrSuffix(prefixes, suffixes, name) +// || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name); +// } + +// public static boolean hasParameterName(IJavaProject project, String name) { +// String prefixes = project.getOption( +// JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); +// String suffixes = project.getOption( +// JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); +// return hasPrefixOrSuffix(prefixes, suffixes, name); +// } + +// public static boolean hasLocalVariableName(IJavaProject project, String name) { +// String prefixes = project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, +// true); +// String suffixes = project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, +// true); +// return hasPrefixOrSuffix(prefixes, suffixes, name); +// } + +// public static boolean hasConstantName(String name) { +// return Character.isUpperCase(name.charAt(0)); +// } + +// private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, +// String name) { +// final String listSeparartor = ","; //$NON-NLS-1$ +// +// StringTokenizer tok = new StringTokenizer(prefixes, listSeparartor); +// while (tok.hasMoreTokens()) { +// String curr = tok.nextToken(); +// if (name.startsWith(curr)) { +// return true; +// } +// } +// +// tok = new StringTokenizer(suffixes, listSeparartor); +// while (tok.hasMoreTokens()) { +// String curr = tok.nextToken(); +// if (name.endsWith(curr)) { +// return true; +// } +// } +// return false; +// } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java new file mode 100644 index 0000000..07b4032 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +import java.util.Iterator; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultLineTracker; +import org.eclipse.jface.text.ILineTracker; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateBuffer; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateTranslator; +import org.eclipse.jface.text.templates.TemplateVariableResolver; + +public class CodeTemplateContext extends TemplateContext { + + private String fLineDelimiter; + + private IJavaProject fProject; + + public CodeTemplateContext(String contextTypeName, IJavaProject project, + String lineDelim) { + super(PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry() + .getContextType(contextTypeName)); + fLineDelimiter = lineDelim; + fProject = project; + } + + public IJavaProject getJavaProject() { + return fProject; + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#evaluate(net.sourceforge.phpdt.internal.corext.template.Template) + */ + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { + // test that all variables are defined + Iterator iterator = getContextType().resolvers(); + while (iterator.hasNext()) { + TemplateVariableResolver var = (TemplateVariableResolver) iterator + .next(); + if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) { + // Assert.isNotNull(getVariable(var.getType()), "Variable " + + // var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + if (!canEvaluate(template)) + return null; + + String pattern = changeLineDelimiter(template.getPattern(), + fLineDelimiter); + + TemplateTranslator translator = new TemplateTranslator(); + TemplateBuffer buffer = translator.translate(pattern); + getContextType().resolve(buffer, this); + + return buffer; + } + + private static String changeLineDelimiter(String code, String lineDelim) { + try { + ILineTracker tracker = new DefaultLineTracker(); + tracker.set(code); + int nLines = tracker.getNumberOfLines(); + if (nLines == 1) { + return code; + } + + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < nLines; i++) { + if (i != 0) { + buf.append(lineDelim); + } + IRegion region = tracker.getLineInformation(i); + String line = code.substring(region.getOffset(), region + .getOffset() + + region.getLength()); + buf.append(line); + } + return buf.toString(); + } catch (BadLocationException e) { + // can not happen + return code; + } + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.corext.template.TemplateContext#canEvaluate(net.sourceforge.phpdt.internal.corext.template.Template) + */ + public boolean canEvaluate(Template template) { + return true; + } + + public void setCompilationUnitVariables(ICompilationUnit cu) { + setVariable(CodeTemplateContextType.FILENAME, cu.getElementName()); + setVariable(CodeTemplateContextType.PACKAGENAME, cu.getParent() + .getElementName()); + setVariable(CodeTemplateContextType.PROJECTNAME, cu.getJavaProject() + .getElementName()); + } + + public void setFileNameVariable(String filename, String projectname) { + setVariable(CodeTemplateContextType.FILENAME, filename); + setVariable(CodeTemplateContextType.PROJECTNAME, projectname); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java new file mode 100644 index 0000000..9e0d590 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContextType.java @@ -0,0 +1,529 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +import java.util.ArrayList; + +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.core.compiler.IScanner; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; + +import org.eclipse.jface.text.templates.ContextTypeRegistry; +import org.eclipse.jface.text.templates.GlobalTemplateVariables; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateVariable; +import org.eclipse.jface.text.templates.TemplateVariableResolver; + +/** + */ +public class CodeTemplateContextType extends TemplateContextType { + + /* context types */ + public static final String CATCHBLOCK_CONTEXTTYPE = "php_catchblock_context"; //$NON-NLS-1$ + + public static final String METHODBODY_CONTEXTTYPE = "php_methodbody_context"; //$NON-NLS-1$ + + public static final String CONSTRUCTORBODY_CONTEXTTYPE = "php_constructorbody_context"; //$NON-NLS-1$ + + public static final String GETTERBODY_CONTEXTTYPE = "php_getterbody_context"; //$NON-NLS-1$ + + public static final String SETTERBODY_CONTEXTTYPE = "php_setterbody_context"; //$NON-NLS-1$ + + public static final String NEWTYPE_CONTEXTTYPE = "php_newtype_context"; //$NON-NLS-1$ + + public static final String NEWHTML_CONTEXTTYPE = "php_newhtml_context"; //$NON-NLS-1$ + + public static final String TYPECOMMENT_CONTEXTTYPE = "php_typecomment_context"; //$NON-NLS-1$ + + public static final String FIELDCOMMENT_CONTEXTTYPE = "php_fieldcomment_context"; //$NON-NLS-1$ + + public static final String METHODCOMMENT_CONTEXTTYPE = "php_methodcomment_context"; //$NON-NLS-1$ + + public static final String CONSTRUCTORCOMMENT_CONTEXTTYPE = "php_constructorcomment_context"; //$NON-NLS-1$ + + public static final String OVERRIDECOMMENT_CONTEXTTYPE = "php_overridecomment_context"; //$NON-NLS-1$ + + public static final String GETTERCOMMENT_CONTEXTTYPE = "php_gettercomment_context"; //$NON-NLS-1$ + + public static final String SETTERCOMMENT_CONTEXTTYPE = "php_settercomment_context"; //$NON-NLS-1$ + + /* templates */ + public static final String COMMENT_SUFFIX = "comment"; //$NON-NLS-1$ + + public static final String CATCHBLOCK = "catchblock"; //$NON-NLS-1$ + + public static final String METHODSTUB = "methodbody"; //$NON-NLS-1$ + + public static final String NEWTYPE = "newtype"; //$NON-NLS-1$ + + public static final String NEWHTML = "newhtml"; //$NON-NLS-1$ + + public static final String CONSTRUCTORSTUB = "constructorbody"; //$NON-NLS-1$ + + public static final String GETTERSTUB = "getterbody"; //$NON-NLS-1$ + + public static final String SETTERSTUB = "setterbody"; //$NON-NLS-1$ + + public static final String TYPECOMMENT = "type" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String FIELDCOMMENT = "field" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String METHODCOMMENT = "method" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String CONSTRUCTORCOMMENT = "constructor" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String OVERRIDECOMMENT = "override" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String GETTERCOMMENT = "getter" + COMMENT_SUFFIX; //$NON-NLS-1$ + + public static final String SETTERCOMMENT = "setter" + COMMENT_SUFFIX; //$NON-NLS-1$ + + /* resolver types */ + public static final String EXCEPTION_TYPE = "exception_type"; //$NON-NLS-1$ + + public static final String EXCEPTION_VAR = "exception_var"; //$NON-NLS-1$ + + public static final String ENCLOSING_METHOD = "enclosing_method"; //$NON-NLS-1$ + + public static final String ENCLOSING_TYPE = "enclosing_type"; //$NON-NLS-1$ + + public static final String BODY_STATEMENT = "body_statement"; //$NON-NLS-1$ + + public static final String FIELD = "field"; //$NON-NLS-1$ + + public static final String FIELD_TYPE = "field_type"; //$NON-NLS-1$ + + public static final String BARE_FIELD_NAME = "bare_field_name"; //$NON-NLS-1$ + + public static final String PARAM = "param"; //$NON-NLS-1$ + + public static final String RETURN_TYPE = "return_type"; //$NON-NLS-1$ + + public static final String SEE_TAG = "see_to_overridden"; //$NON-NLS-1$ + + public static final String TAGS = "tags"; //$NON-NLS-1$ + + public static final String TYPENAME = "type_name"; //$NON-NLS-1$ + + public static final String FILENAME = "file_name"; //$NON-NLS-1$ + + public static final String PACKAGENAME = "package_name"; //$NON-NLS-1$ + + public static final String PROJECTNAME = "project_name"; //$NON-NLS-1$ + + public static final String PACKAGE_DECLARATION = "package_declaration"; //$NON-NLS-1$ + + public static final String TYPE_DECLARATION = "type_declaration"; //$NON-NLS-1$ + + public static final String TYPE_COMMENT = "typecomment"; //$NON-NLS-1$ + + /** + * Resolver that resolves to the variable defined in the context. + */ + public static class CodeTemplateVariableResolver extends + TemplateVariableResolver { + public CodeTemplateVariableResolver(String type, String description) { + super(type, description); + } + + protected String resolve(TemplateContext context) { + return context.getVariable(getType()); + } + } + + /** + * Resolver for javadoc tags. + */ + public static class TagsVariableResolver extends TemplateVariableResolver { + public TagsVariableResolver() { + super( + TAGS, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.tags")); //$NON-NLS-1$ + } + + protected String resolve(TemplateContext context) { + return "@"; //$NON-NLS-1$ + } + } + + /** + * Resolver for todo tags. + */ + protected static class Todo extends TemplateVariableResolver { + + public Todo() { + super( + "todo", JavaTemplateMessages.getString("CodeTemplateContextType.variable.description.todo")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + protected String resolve(TemplateContext context) { + String todoTaskTag = StubUtility + .getTodoTaskTag(((CodeTemplateContext) context) + .getJavaProject()); + if (todoTaskTag == null) + return "XXX"; //$NON-NLS-1$ + + return todoTaskTag; + } + } + + private boolean fIsComment; + + public CodeTemplateContextType(String contextName) { + super(contextName); + + fIsComment = false; + + // global + addResolver(new GlobalTemplateVariables.Dollar()); + addResolver(new GlobalTemplateVariables.Date()); + addResolver(new GlobalTemplateVariables.Year()); + addResolver(new GlobalTemplateVariables.Time()); + addResolver(new GlobalTemplateVariables.User()); + addResolver(new Todo()); + + if (CATCHBLOCK_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + EXCEPTION_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.exceptiontype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + EXCEPTION_VAR, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.exceptionvar"))); //$NON-NLS-1$ + } else if (METHODBODY_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BODY_STATEMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ + } else if (CONSTRUCTORBODY_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BODY_STATEMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.bodystatement"))); //$NON-NLS-1$ + } else if (GETTERBODY_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + } else if (SETTERBODY_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PARAM, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ + } else if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_COMMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + } else if (NEWHTML_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packdeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_DECLARATION, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typedeclaration"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + TYPE_COMMENT, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typecomment"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + } else if (TYPECOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + TYPENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.typename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new TagsVariableResolver()); + addCompilationUnitVariables(); + fIsComment = true; + } else if (FIELDCOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.fieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.fieldname"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + fIsComment = true; + } else if (METHODCOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + RETURN_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.returntype"))); //$NON-NLS-1$ + addResolver(new TagsVariableResolver()); + addCompilationUnitVariables(); + fIsComment = true; + } else if (OVERRIDECOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + SEE_TAG, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.seetag"))); //$NON-NLS-1$ + addResolver(new TagsVariableResolver()); + addCompilationUnitVariables(); + fIsComment = true; + } else if (CONSTRUCTORCOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new TagsVariableResolver()); + addCompilationUnitVariables(); + fIsComment = true; + } else if (GETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BARE_FIELD_NAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + fIsComment = true; + } else if (SETTERCOMMENT_CONTEXTTYPE.equals(contextName)) { + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD_TYPE, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldtype"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + FIELD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.getterfieldname"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + ENCLOSING_METHOD, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.enclosingmethod"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PARAM, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.param"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + BARE_FIELD_NAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.barefieldname"))); //$NON-NLS-1$ + addCompilationUnitVariables(); + fIsComment = true; + } + } + + private void addCompilationUnitVariables() { + addResolver(new CodeTemplateVariableResolver( + FILENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.filename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PACKAGENAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.packagename"))); //$NON-NLS-1$ + addResolver(new CodeTemplateVariableResolver( + PROJECTNAME, + JavaTemplateMessages + .getString("CodeTemplateContextType.variable.description.projectname"))); //$NON-NLS-1$ + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validateVariables(net.sourceforge.phpdt.internal.corext.template.TemplateVariable[]) + */ + protected void validateVariables(TemplateVariable[] variables) + throws TemplateException { + ArrayList required = new ArrayList(5); + //String contextName = getId(); + // if (NEWTYPE_CONTEXTTYPE.equals(contextName)) { + // required.add(PACKAGE_DECLARATION); + // required.add(TYPE_DECLARATION); + // } + for (int i = 0; i < variables.length; i++) { + String type = variables[i].getType(); + if (getResolver(type) == null) { + throw new TemplateException( + JavaTemplateMessages + .getFormattedString( + "CodeTemplateContextType.validate.unknownvariable", type)); //$NON-NLS-1$ + } + required.remove(type); + } + if (!required.isEmpty()) { + String missing = (String) required.get(0); + throw new TemplateException( + JavaTemplateMessages + .getFormattedString( + "CodeTemplateContextType.validate.missingvariable", missing)); //$NON-NLS-1$ + } + super.validateVariables(variables); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.corext.template.ContextType#createContext() + */ +// public TemplateContext createContext() { +// return null; +// } + + public static void registerContextTypes(ContextTypeRegistry registry) { + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CATCHBLOCK_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.METHODBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CONSTRUCTORBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.GETTERBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.SETTERBODY_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.NEWTYPE_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.NEWHTML_CONTEXTTYPE)); + + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.TYPECOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.FIELDCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.METHODCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.CONSTRUCTORCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.OVERRIDECOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.GETTERCOMMENT_CONTEXTTYPE)); + registry.addContextType(new CodeTemplateContextType( + CodeTemplateContextType.SETTERCOMMENT_CONTEXTTYPE)); + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.ContextType#validate(java.lang.String) + */ + public void validate(String pattern) throws TemplateException { + super.validate(pattern); + if (fIsComment) { + if (!isValidComment(pattern)) { + throw new TemplateException( + JavaTemplateMessages + .getString("CodeTemplateContextType.validate.invalidcomment")); //$NON-NLS-1$ + } + } + } + + private boolean isValidComment(String template) { + IScanner scanner = ToolFactory.createScanner(true, false, false, true);// false); + scanner.setSource(template.toCharArray()); + try { + TokenName next = scanner.getNextToken(); + while (next == ITerminalSymbols.TokenName.COMMENT_LINE + || next == ITerminalSymbols.TokenName.COMMENT_PHPDOC + || next == ITerminalSymbols.TokenName.COMMENT_BLOCK) { + next = scanner.getNextToken(); + } + return next == ITerminalSymbols.TokenName.EOF; + } catch (InvalidInputException e) { + } + return false; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java new file mode 100644 index 0000000..0b10e64 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplates.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +import java.io.File; +import java.io.InputStream; +import java.util.ResourceBundle; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +//import org.eclipse.jface.text.templates.Template; + +/** + * CodeTemplates gives access to the available code templates. + * + * @since 3.0 + * @deprecated use + * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getCodeTemplateStore()} + * instead + */ +public class CodeTemplates extends + net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { + + private static final String DEFAULT_FILE = "default-codetemplates.xml"; //$NON-NLS-1$ + + private static final String TEMPLATE_FILE = "codetemplates.xml"; //$NON-NLS-1$ + + private static final ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(JavaTemplateMessages.class.getName()); + + /** Singleton. */ + private static CodeTemplates fgTemplates; + +// public static Template getCodeTemplate(String name) { +// return getInstance().getFirstTemplate(name); +// } + + /** + * Returns an instance of templates. + */ + public static CodeTemplates getInstance() { + if (fgTemplates == null) + fgTemplates = new CodeTemplates(); + + return fgTemplates; + } + + private CodeTemplates() { + super( + "codetemplate", PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry()); //$NON-NLS-1$ + create(); + } + + private void create() { + + try { + addFromStream(getDefaultsAsStream(), false, true, fgResourceBundle); + File templateFile = getTemplateFile(); + if (templateFile.exists()) { + addFromFile(templateFile, false, fgResourceBundle); + } + saveToFile(templateFile); + + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + clear(); + } + + } + + /** + * Resets the template set. + */ + public void reset() throws CoreException { + clear(); + addFromFile(getTemplateFile(), false, fgResourceBundle); + } + + /** + * Resets the template set with the default templates. + */ +// public void restoreDefaults() throws CoreException { +// clear(); +// addFromStream(getDefaultsAsStream(), false, true, fgResourceBundle); +// } + + /** + * Saves the template set. + */ +// public void save() throws CoreException { +// saveToFile(getTemplateFile()); +// } + + private static InputStream getDefaultsAsStream() { + return CodeTemplates.class.getResourceAsStream(DEFAULT_FILE); + } + + private static File getTemplateFile() { + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(TEMPLATE_FILE); + + return path.toFile(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitCompletion.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContext.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CompilationUnitContextType.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLContextType.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/HTMLUnitContext.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java new file mode 100644 index 0000000..ea92cff --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContext.java @@ -0,0 +1,663 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +//import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.core.ICompilationUnit; +//import net.sourceforge.phpdt.internal.corext.Assert; +//import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitCompletion.LocalVariable; +import net.sourceforge.phpdt.internal.corext.util.Strings; +import net.sourceforge.phpdt.internal.ui.preferences.CodeFormatterPreferencePage; +import net.sourceforge.phpdt.internal.ui.text.template.contentassist.MultiVariable; +//import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +//import org.eclipse.jface.dialogs.MessageDialog; +//import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateBuffer; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateTranslator; +import org.eclipse.jface.text.templates.TemplateVariable; +//import org.eclipse.swt.widgets.Shell; + +/** + * A context for java source. + */ +public class JavaContext extends CompilationUnitContext { + + /** The platform default line delimiter. */ + private static final String PLATFORM_LINE_DELIMITER = System + .getProperty("line.separator"); //$NON-NLS-1$ + + /** A code completion requestor for guessing local variable names. */ + //private CompilationUnitCompletion fCompletion; + + /** + * Creates a java template context. + * + * @param type + * the context type. + * @param document + * the document. + * @param completionOffset + * the completion offset within the document. + * @param completionLength + * the completion length. + * @param compilationUnit + * the compilation unit (may be null). + */ + public JavaContext(TemplateContextType type, IDocument document, + int completionOffset, int completionLength, + ICompilationUnit compilationUnit) { + super(type, document, completionOffset, completionLength, + compilationUnit); + } + + /** + * Returns the indentation level at the position of code completion. + */ + private int getIndentation() { + int start = getStart(); + IDocument document = getDocument(); + try { + IRegion region = document.getLineInformationOfOffset(start); + String lineContent = document.get(region.getOffset(), region + .getLength()); + return Strings.computeIndent(lineContent, + CodeFormatterPreferencePage.getTabSize()); + // return Strings.computeIndent(lineContent, + // CodeFormatterUtil.getTabWidth()); + } catch (BadLocationException e) { + return 0; + } + } + + /* + * @see TemplateContext#evaluate(Template template) + */ + public TemplateBuffer evaluate(Template template) + throws BadLocationException, TemplateException { + + if (!canEvaluate(template)) + throw new TemplateException(JavaTemplateMessages + .getString("Context.error.cannot.evaluate")); //$NON-NLS-1$ + + TemplateTranslator translator = new TemplateTranslator() { + /* + * @see org.eclipse.jface.text.templates.TemplateTranslator#createVariable(java.lang.String, + * java.lang.String, int[]) + */ + protected TemplateVariable createVariable(String type, String name, + int[] offsets) { + return new MultiVariable(type, name, offsets); + } + }; + TemplateBuffer buffer = translator.translate(template); + + getContextType().resolve(buffer, this); + String lineDelimiter = null; + try { + lineDelimiter = getDocument().getLineDelimiter(0); + } catch (BadLocationException e) { + } + + if (lineDelimiter == null) + lineDelimiter = PLATFORM_LINE_DELIMITER; +// IPreferenceStore prefs = PHPeclipsePlugin.getDefault() +// .getPreferenceStore(); + // axelcl start + // boolean useCodeFormatter = + // prefs.getBoolean(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER); + boolean useCodeFormatter = false; + // axelcl end + + JavaFormatter formatter = new JavaFormatter(lineDelimiter, + getIndentation(), useCodeFormatter); + formatter.format(buffer, this); + // debug start + // String res = buffer.getString(); + // res = res.replaceAll("\n","/n"); + // res = res.replaceAll("\t","/t"); + // System.out.println(res); + // debug end + return buffer; + } + + /* + * @see TemplateContext#canEvaluate(Template templates) + */ + public boolean canEvaluate(Template template) { + String key = getKey(); + + if (fForceEvaluation) + return true; + + return template.matches(key, getContextType().getId()) + && key.length() != 0 + && template.getName().toLowerCase().startsWith( + key.toLowerCase()); + } + + public boolean canEvaluate(String identifier) { + String prefix = getKey(); + return identifier.toLowerCase().startsWith(prefix.toLowerCase()); + } + + /* + * @see DocumentTemplateContext#getCompletionPosition(); + */ + public int getStart() { + + try { + IDocument document = getDocument(); + + if (getCompletionLength() == 0) { + + int start = getCompletionOffset(); + while ((start != 0) + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) + start--; + + if ((start != 0) + && (Character.isUnicodeIdentifierStart(document + .getChar(start - 1)) || (document + .getChar(start - 1) == '$'))) + start--; + + return start; + + } else { + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); + + while (start != 0 + && Character.isUnicodeIdentifierPart(document + .getChar(start - 1))) + start--; + if ((start != 0) + && (Character.isUnicodeIdentifierStart(document + .getChar(start - 1)) || (document + .getChar(start - 1) == '$'))) + start--; + while (start != end + && Character.isWhitespace(document.getChar(start))) + start++; + + if (start == end) + start = getCompletionOffset(); + + return start; + } + + } catch (BadLocationException e) { + return super.getStart(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getEnd() + */ + public int getEnd() { + + if (getCompletionLength() == 0) + return super.getEnd(); + + try { + IDocument document = getDocument(); + + int start = getCompletionOffset(); + int end = getCompletionOffset() + getCompletionLength(); + + while (start != end + && Character.isWhitespace(document.getChar(end - 1))) + end--; + + return end; + + } catch (BadLocationException e) { + return super.getEnd(); + } + } + + /* + * @see net.sourceforge.phpdt.internal.corext.template.DocumentTemplateContext#getKey() + */ + public String getKey() { + + // if (getCompletionLength() == 0) { + // return super.getKey(); + // } + + try { + IDocument document = getDocument(); + + int start = getStart(); + int end = getCompletionOffset(); + return start <= end ? document.get(start, end - start) : ""; //$NON-NLS-1$ + + } catch (BadLocationException e) { + return super.getKey(); + } + } + + /** + * Returns the character before start position of completion. + */ + public char getCharacterBeforeStart() { + int start = getStart(); + + try { + return start == 0 ? ' ' : getDocument().getChar(start - 1); + + } catch (BadLocationException e) { + return ' '; + } + } + +// private static void handleException(Shell shell, Exception e) { +// String title = JavaTemplateMessages +// .getString("JavaContext.error.title"); //$NON-NLS-1$ +// if (e instanceof CoreException) +// ExceptionHandler.handle((CoreException) e, shell, title, null); +// else if (e instanceof InvocationTargetException) +// ExceptionHandler.handle((InvocationTargetException) e, shell, +// title, null); +// else { +// PHPeclipsePlugin.log(e); +// MessageDialog.openError(shell, title, e.getMessage()); +// } +// } + + // private CompilationUnitCompletion getCompletion() { + // ICompilationUnit compilationUnit= getCompilationUnit(); + // if (fCompletion == null) { + // fCompletion= new CompilationUnitCompletion(compilationUnit); + // + // if (compilationUnit != null) { + // try { + // compilationUnit.codeComplete(getStart(), fCompletion); + // } catch (JavaModelException e) { + // // ignore + // } + // } + // } + // + // return fCompletion; + // } + + /** + * Returns the name of a guessed local array, null if no + * local array exists. + */ + // public String guessArray() { + // return firstOrNull(guessArrays()); + // } + /** + * Returns the name of a guessed local array, null if no + * local array exists. + */ + // public String[] guessArrays() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[] ret= new String[localArrays.length]; + // for (int i= 0; i < ret.length; i++) { + // ret[ret.length - i - 1]= localArrays[i].name; + // } + // return ret; + // } + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String guessArrayType() { + // return firstOrNull(guessArrayTypes()); + // } +// private String firstOrNull(String[] strings) { +// if (strings.length > 0) +// return strings[0]; +// else +// return null; +// } + + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String[][] guessGroupedArrayTypes() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[][] ret= new String[localArrays.length][]; + // + // for (int i= 0; i < localArrays.length; i++) { + // String type= getArrayTypeFromLocalArray(completion, + // localArrays[localArrays.length - i - 1]); + // ret[i]= new String[] {type}; + // } + // + // return ret; + // } + /** + * Returns the name of the type of a local array, null if no + * local array exists. + */ + // public String[] guessArrayTypes() { + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // List ret= new ArrayList(); + // + // for (int i= 0; i < localArrays.length; i++) { + // String type= getArrayTypeFromLocalArray(completion, + // localArrays[localArrays.length - i - 1]); + // if (!ret.contains(type)) + // ret.add(type); + // } + // + // return (String[]) ret.toArray(new String[ret.size()]); + // } +// private String getArrayTypeFromLocalArray( +// CompilationUnitCompletion completion, LocalVariable array) { +// String arrayTypeName = array.typeName; +// String typeName = getScalarType(arrayTypeName); +// int dimension = getArrayDimension(arrayTypeName) - 1; +// Assert.isTrue(dimension >= 0); +// +// String qualifiedName = createQualifiedTypeName(array.typePackageName, +// typeName); +// String innerTypeName = completion.simplifyTypeName(qualifiedName); +// +// return innerTypeName == null ? createArray(typeName, dimension) +// : createArray(innerTypeName, dimension); +// } + +// private static String createArray(String type, int dimension) { +// StringBuffer buffer = new StringBuffer(type); +// for (int i = 0; i < dimension; i++) +// buffer.append("[]"); //$NON-NLS-1$ +// return buffer.toString(); +// } + +// private static String getScalarType(String type) { +// return type.substring(0, type.indexOf('[')); +// } + +// private static int getArrayDimension(String type) { +// +// int dimension = 0; +// int index = type.indexOf('['); +// +// while (index != -1) { +// dimension++; +// index = type.indexOf('[', index + 1); +// } +// +// return dimension; +// } + +// private static String createQualifiedTypeName(String packageName, +// String className) { +// StringBuffer buffer = new StringBuffer(); +// +// if (packageName.length() != 0) { +// buffer.append(packageName); +// buffer.append('.'); +// } +// buffer.append(className); +// +// return buffer.toString(); +// } + + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String guessArrayElement() { + // return firstOrNull(guessArrayElements()); + // } + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String[] guessArrayElements() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return new String[0]; + // } + // + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // List ret= new ArrayList(); + // + // for (int i= 0; i < localArrays.length; i++) { + // int idx= localArrays.length - i - 1; + // + // LocalVariable var= localArrays[idx]; + // + // IJavaProject project= cu.getJavaProject(); + // String typeName= var.typeName; + // String baseTypeName= typeName.substring(0, typeName.lastIndexOf('[')); + // + // String indexName= getIndex(); + // String[] excludedNames= completion.getLocalVariableNames(); + // if (indexName != null) { + // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); + // excludedNamesList.add(indexName); + // excludedNames= (String[])excludedNamesList.toArray(new + // String[excludedNamesList.size()]); + // } + // String[] proposals= NamingConventions.suggestLocalVariableNames(project, + // var.typePackageName, baseTypeName, 0, excludedNames); + // for (int j= 0; j < proposals.length; j++) { + // if (!ret.contains(proposals[j])) + // ret.add(proposals[j]); + // } + // } + // + // return (String[]) ret.toArray(new String[ret.size()]); + // } + /** + * Returns a proposal for a variable name of a local array element, + * null if no local array exists. + */ + // public String[][] guessGroupedArrayElements() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return new String[0][]; + // } + // + // CompilationUnitCompletion completion= getCompletion(); + // LocalVariable[] localArrays= completion.findLocalArrays(); + // + // String[][] ret= new String[localArrays.length][]; + // + // for (int i= 0; i < localArrays.length; i++) { + // int idx= localArrays.length - i - 1; + // + // LocalVariable var= localArrays[idx]; + // + // IJavaProject project= cu.getJavaProject(); + // String typeName= var.typeName; + // int dim= -1; // we expect at least one array + // int lastIndex= typeName.length(); + // int bracket= typeName.lastIndexOf('['); + // while (bracket != -1) { + // lastIndex= bracket; + // dim++; + // bracket= typeName.lastIndexOf('[', bracket - 1); + // } + // typeName= typeName.substring(0, lastIndex); + // + // String indexName= getIndex(); + // String[] excludedNames= completion.getLocalVariableNames(); + // if (indexName != null) { + // ArrayList excludedNamesList= new ArrayList(Arrays.asList(excludedNames)); + // excludedNamesList.add(indexName); + // excludedNames= (String[])excludedNamesList.toArray(new + // String[excludedNamesList.size()]); + // } + // String[] proposals= NamingConventions.suggestLocalVariableNames(project, + // var.typePackageName, typeName, dim, excludedNames); + // + // ret[i]= proposals; + // } + // + // return ret; + // } + /** + * Returns an array index name. 'i', 'j', 'k' are tried until no name + * collision with an existing local variable occurs. If all names collide, + * null is returned. + */ + // public String getIndex() { + // CompilationUnitCompletion completion= getCompletion(); + // String[] proposals= {"i", "j", "k"}; //$NON-NLS-1$ //$NON-NLS-2$ + // //$NON-NLS-3$ + // + // for (int i= 0; i != proposals.length; i++) { + // String proposal = proposals[i]; + // + // if (!completion.existsLocalName(proposal)) + // return proposal; + // } + // + // return null; + // } + /** + * Returns the name of a local collection, null if no local + * collection exists. + */ + // public String guessCollection() { + // return firstOrNull(guessCollections()); + // } + /** + * Returns the names of local collections. + */ + // public String[] guessCollections() { + // CompilationUnitCompletion completion= getCompletion(); + // try { + // LocalVariable[] localCollections= completion.findLocalCollections(); + // String[] ret= new String[localCollections.length]; + // for (int i= 0; i < ret.length; i++) { + // ret[ret.length - i - 1]= localCollections[i].name; + // } + // + // return ret; + // + // } catch (JavaModelException e) { + // JavaPlugin.log(e); + // } + // + // return new String[0]; + // } + /** + * Returns an iterator name ('iter'). If 'iter' already exists as local + * variable, null is returned. + */ + // public String getIterator() { + // CompilationUnitCompletion completion= getCompletion(); + // String[] proposals= {"iter"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + // + // for (int i= 0; i != proposals.length; i++) { + // String proposal = proposals[i]; + // + // if (!completion.existsLocalName(proposal)) + // return proposal; + // } + // + // return null; + // } + // public void addIteratorImport() { + // ICompilationUnit cu= getCompilationUnit(); + // if (cu == null) { + // return; + // } + // + // try { + // Position position= new Position(getCompletionOffset(), + // getCompletionLength()); + // IDocument document= getDocument(); + // final String category= "__template_position_importer" + + // System.currentTimeMillis(); //$NON-NLS-1$ + // IPositionUpdater updater= new DefaultPositionUpdater(category); + // document.addPositionCategory(category); + // document.addPositionUpdater(updater); + // document.addPosition(position); + // + // CodeGenerationSettings settings= + // JavaPreferencesSettings.getCodeGenerationSettings(); + // ImportsStructure structure= new ImportsStructure(cu, + // settings.importOrder, settings.importThreshold, true); + // structure.addImport("java.util.Iterator"); //$NON-NLS-1$ + // structure.create(false, null); + // + // document.removePosition(position); + // document.removePositionUpdater(updater); + // document.removePositionCategory(category); + // + // setCompletionOffset(position.getOffset()); + // setCompletionLength(position.getLength()); + // + // } catch (CoreException e) { + // handleException(null, e); + // } catch (BadLocationException e) { + // handleException(null, e); + // } catch (BadPositionCategoryException e) { + // handleException(null, e); + // } + // } + /** + * Evaluates a 'java' template in thecontext of a compilation unit + */ + public static String evaluateTemplate(Template template, + ICompilationUnit compilationUnit, int position) + throws CoreException, BadLocationException, TemplateException { + + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("java"); //$NON-NLS-1$ + if (contextType == null) + throw new CoreException( + new Status( + IStatus.ERROR, + PHPeclipsePlugin.PLUGIN_ID, + IStatus.ERROR, + JavaTemplateMessages + .getString("JavaContext.error.message"), null)); //$NON-NLS-1$ + + IDocument document = new Document(); + if (compilationUnit != null && compilationUnit.exists()) + document.set(compilationUnit.getSource()); + + JavaContext context = new JavaContext(contextType, document, position, + 0, compilationUnit); + context.setForceEvaluation(true); + + TemplateBuffer buffer = context.evaluate(template); + if (buffer == null) + return null; + return buffer.getString(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaContextType.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContext.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaDocContextType.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java new file mode 100644 index 0000000..d1cd8bc --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaFormatter.java @@ -0,0 +1,392 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.internal.corext.util.CodeFormatterUtil; +import net.sourceforge.phpdt.internal.corext.util.Strings; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; +import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.templates.DocumentTemplateContext; +import org.eclipse.jface.text.templates.GlobalTemplateVariables; +import org.eclipse.jface.text.templates.TemplateBuffer; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.jface.text.templates.TemplateVariable; +import org.eclipse.text.edits.DeleteEdit; +import org.eclipse.text.edits.InsertEdit; +import org.eclipse.text.edits.MalformedTreeException; +import org.eclipse.text.edits.MultiTextEdit; +import org.eclipse.text.edits.RangeMarker; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; + +/** + * A template editor using the Java formatter to format a template buffer. + */ +public class JavaFormatter { + + private static final String MARKER = "/*${" + GlobalTemplateVariables.Cursor.NAME + "}*/"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** The line delimiter to use if code formatter is not used. */ + private final String fLineDelimiter; + + /** The initial indent level */ + private final int fInitialIndentLevel; + + /** The java partitioner */ + private boolean fUseCodeFormatter; + + /** + * Creates a JavaFormatter with the target line delimiter. + * + * @param lineDelimiter + * the line delimiter to use + * @param initialIndentLevel + * the initial indentation level + * @param useCodeFormatter + * true if the core code formatter should be used + */ + public JavaFormatter(String lineDelimiter, int initialIndentLevel, + boolean useCodeFormatter) { + fLineDelimiter = lineDelimiter; + fUseCodeFormatter = useCodeFormatter; + fInitialIndentLevel = initialIndentLevel; + } + + /** + * Formats the template buffer. + * + * @param buffer + * @param context + * @throws BadLocationException + */ + public void format(TemplateBuffer buffer, TemplateContext context) + throws BadLocationException { + try { + if (fUseCodeFormatter) + // try to format and fall back to indenting + try { + format(buffer, (JavaContext) context); + } catch (BadLocationException e) { + indent(buffer); + } catch (MalformedTreeException e) { + indent(buffer); + } + else + indent(buffer); + + // don't trim the buffer if the replacement area is empty + // case: surrounding empty lines with block + if (context instanceof DocumentTemplateContext) { + DocumentTemplateContext dtc = (DocumentTemplateContext) context; + if (dtc.getStart() == dtc.getCompletionOffset()) + if (dtc.getDocument().get(dtc.getStart(), + dtc.getEnd() - dtc.getEnd()).trim().length() == 0) + return; + } + + trimBegin(buffer); + } catch (MalformedTreeException e) { + throw new BadLocationException(); + } + } + + private static int getCaretOffset(TemplateVariable[] variables) { + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + + if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) + return variable.getOffsets()[0]; + } + + return -1; + } + + private boolean isInsideCommentOrString(String string, int offset) { + + IDocument document = new Document(string); + PHPeclipsePlugin.getDefault().getJavaTextTools() + .setupJavaDocumentPartitioner(document); + + try { + ITypedRegion partition = document.getPartition(offset); + String partitionType = partition.getType(); + + return partitionType != null + && (partitionType + .equals(IPHPPartitions.PHP_MULTILINE_COMMENT) + || partitionType + .equals(IPHPPartitions.PHP_SINGLELINE_COMMENT) + || partitionType + .equals(IPHPPartitions.PHP_STRING_DQ) + || partitionType + .equals(IPHPPartitions.PHP_STRING_SQ) + || partitionType + .equals(IPHPPartitions.PHP_STRING_HEREDOC) || partitionType + .equals(IPHPPartitions.PHP_PHPDOC_COMMENT)); + + } catch (BadLocationException e) { + return false; + } + } + + private void format(TemplateBuffer templateBuffer, JavaContext context) + throws BadLocationException { + // XXX 4360, 15247 + // workaround for code formatter limitations + // handle a special case where cursor position is surrounded by + // whitespaces + + String string = templateBuffer.getString(); + TemplateVariable[] variables = templateBuffer.getVariables(); + + int caretOffset = getCaretOffset(variables); + if ((caretOffset > 0) + && Character.isWhitespace(string.charAt(caretOffset - 1)) + && (caretOffset < string.length()) + && Character.isWhitespace(string.charAt(caretOffset)) + && !isInsideCommentOrString(string, caretOffset)) { + List positions = variablesToPositions(variables); + + TextEdit insert = new InsertEdit(caretOffset, MARKER); + string = edit(string, positions, insert); + positionsToVariables(positions, variables); + templateBuffer.setContent(string, variables); + + plainFormat(templateBuffer, context); + + string = templateBuffer.getString(); + variables = templateBuffer.getVariables(); + caretOffset = getCaretOffset(variables); + + positions = variablesToPositions(variables); + TextEdit delete = new DeleteEdit(caretOffset, MARKER.length()); + string = edit(string, positions, delete); + positionsToVariables(positions, variables); + templateBuffer.setContent(string, variables); + + } else { + plainFormat(templateBuffer, context); + } + } + + private void plainFormat(TemplateBuffer templateBuffer, JavaContext context) + throws BadLocationException { + } + + // private void plainFormat(TemplateBuffer templateBuffer, JavaContext + // context) throws BadLocationException { + // + // IDocument doc= new Document(templateBuffer.getString()); + // + // TemplateVariable[] variables= templateBuffer.getVariables(); + // + // List offsets= variablesToPositions(variables); + // + // Map options; + // if (context.getCompilationUnit() != null) + // options= context.getCompilationUnit().getJavaProject().getOptions(true); + // else + // options= JavaCore.getOptions(); + // + // TextEdit edit= CodeFormatterUtil.format2(CodeFormatter.K_UNKNOWN, + // doc.get(), fInitialIndentLevel, fLineDelimiter, options); + // if (edit == null) + // throw new BadLocationException(); // fall back to indenting + // + // MultiTextEdit root; + // if (edit instanceof MultiTextEdit) + // root= (MultiTextEdit) edit; + // else { + // root= new MultiTextEdit(0, doc.getLength()); + // root.addChild(edit); + // } + // for (Iterator it= offsets.iterator(); it.hasNext();) { + // TextEdit position= (TextEdit) it.next(); + // try { + // root.addChild(position); + // } catch (MalformedTreeException e) { + // // position conflicts with formatter edit + // // ignore this position + // } + // } + // + // root.apply(doc, TextEdit.UPDATE_REGIONS); + // + // positionsToVariables(offsets, variables); + // + // templateBuffer.setContent(doc.get(), variables); + // } + + private void indent(TemplateBuffer templateBuffer) + throws BadLocationException, MalformedTreeException { + + TemplateVariable[] variables = templateBuffer.getVariables(); + List positions = variablesToPositions(variables); + + IDocument document = new Document(templateBuffer.getString()); + MultiTextEdit root = new MultiTextEdit(0, document.getLength()); + root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions + .size()])); + + JavaHeuristicScanner scanner = new JavaHeuristicScanner(document); + JavaIndenter indenter = new JavaIndenter(document, scanner); + + // first line + int offset = document.getLineOffset(0); + TextEdit edit = new InsertEdit(offset, CodeFormatterUtil + .createIndentString(fInitialIndentLevel)); + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + + formatDelimiter(document, root, 0); + + // following lines + int lineCount = document.getNumberOfLines(); + + for (int line = 1; line < lineCount; line++) { + IRegion region = document.getLineInformation(line); + offset = region.getOffset(); + StringBuffer indent = indenter.computeIndentation(offset); + if (indent == null) + continue; + // axelcl delete start + // int nonWS = + // scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + + // region.getLength()); + // if (nonWS == JavaHeuristicScanner.NOT_FOUND) + // continue; + // edit = new ReplaceEdit(offset, nonWS - offset, + // indent.toString()); + // axelcl delete end + // axelcl insert start + int nonWS = offset; + edit = new ReplaceEdit(offset, nonWS - offset, CodeFormatterUtil + .createIndentString(fInitialIndentLevel)); + // axelcl insert end + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + + formatDelimiter(document, root, line); + } + + positionsToVariables(positions, variables); + templateBuffer.setContent(document.get(), variables); + } + + /** + * Changes the delimiter to the configured line delimiter. + * + * @param document + * the temporary document being edited + * @param root + * the root edit containing all positions that will be updated + * along the way + * @param line + * the line to format + * @throws BadLocationException + * if applying the changes fails + */ + private void formatDelimiter(IDocument document, MultiTextEdit root, + int line) throws BadLocationException { + IRegion region = document.getLineInformation(line); + String lineDelimiter = document.getLineDelimiter(line); + if (lineDelimiter != null) { + TextEdit edit = new ReplaceEdit(region.getOffset() + + region.getLength(), lineDelimiter.length(), + fLineDelimiter); + root.addChild(edit); + root.apply(document, TextEdit.UPDATE_REGIONS); + root.removeChild(edit); + } + } + + private static void trimBegin(TemplateBuffer templateBuffer) + throws BadLocationException { + String string = templateBuffer.getString(); + TemplateVariable[] variables = templateBuffer.getVariables(); + + List positions = variablesToPositions(variables); + + int i = 0; + while ((i != string.length()) + && Character.isWhitespace(string.charAt(i))) + i++; + + string = edit(string, positions, new DeleteEdit(0, i)); + positionsToVariables(positions, variables); + + templateBuffer.setContent(string, variables); + } + + private static String edit(String string, List positions, TextEdit edit) + throws BadLocationException { + MultiTextEdit root = new MultiTextEdit(0, string.length()); + root.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions + .size()])); + root.addChild(edit); + IDocument document = new Document(string); + root.apply(document); + + return document.get(); + } + + private static List variablesToPositions(TemplateVariable[] variables) { + List positions = new ArrayList(5); + for (int i = 0; i != variables.length; i++) { + int[] offsets = variables[i].getOffsets(); + + // trim positions off whitespace + String value = variables[i].getDefaultValue(); + int wsStart = 0; + while (wsStart < value.length() + && Character.isWhitespace(value.charAt(wsStart)) + && !Strings.isLineDelimiterChar(value.charAt(wsStart))) + wsStart++; + + variables[i].getValues()[0] = value.substring(wsStart); + + for (int j = 0; j != offsets.length; j++) { + offsets[j] += wsStart; + positions.add(new RangeMarker(offsets[j], 0)); + } + } + return positions; + } + + private static void positionsToVariables(List positions, + TemplateVariable[] variables) { + Iterator iterator = positions.iterator(); + + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + + int[] offsets = new int[variable.getOffsets().length]; + for (int j = 0; j != offsets.length; j++) + offsets[j] = ((TextEdit) iterator.next()).getOffset(); + + variable.setOffsets(offsets); + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/JavaTemplateMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/TemplateSet.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java new file mode 100644 index 0000000..e103ef1 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/Templates.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.corext.template.php; + +import java.io.File; +//import java.io.InputStream; +import java.util.ResourceBundle; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; + +/** + * Templates gives access to the available templates. + * + * @deprecated As of 3.0, replaced by + * {@link org.eclipse.jface.text.templates.persistence.TemplateStore} + */ +public class Templates extends + net.sourceforge.phpdt.internal.corext.template.php.TemplateSet { + + //private static final String DEFAULT_FILE = "default-templates.xml"; //$NON-NLS-1$ + + private static final String TEMPLATE_FILE = "templates.xml"; //$NON-NLS-1$ + + private static final ResourceBundle fgResourceBundle = ResourceBundle + .getBundle(JavaTemplateMessages.class.getName()); + + /** Singleton. */ + private static Templates fgTemplates; + + /** + * Returns an instance of templates. + * + * @deprecated As of 3.0, replaced by + * {@link net.sourceforge.phpdt.internal.ui.JavaPlugin#getTemplateStore()} + */ + public static Templates getInstance() { + if (fgTemplates == null) + fgTemplates = new Templates(); + + return fgTemplates; + } + + public Templates() { + super( + "template", PHPeclipsePlugin.getDefault().getTemplateContextRegistry()); //$NON-NLS-1$ + create(); + } + + private void create() { + + try { + File templateFile = getTemplateFile(); + if (templateFile.exists()) { + addFromFile(templateFile, true, fgResourceBundle); + } + + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + clear(); + } + + } + + /** + * Resets the template set. + */ + public void reset() throws CoreException { + clear(); + addFromFile(getTemplateFile(), true, fgResourceBundle); + } + + /** + * Resets the template set with the default templates. + */ +// public void restoreDefaults() throws CoreException { +// clear(); +// addFromStream(getDefaultsAsStream(), true, true, fgResourceBundle); +// } + + /** + * Saves the template set. + */ +// public void save() throws CoreException { +// saveToFile(getTemplateFile()); +// } + +// private static InputStream getDefaultsAsStream() { +// return Templates.class.getResourceAsStream(DEFAULT_FILE); +// } + + private static File getTemplateFile() { + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(TEMPLATE_FILE); + + return path.toFile(); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/PHPUIStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/PHPUIStatus.java index 1c7f96e..9d7d9f8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/PHPUIStatus.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/util/PHPUIStatus.java @@ -5,7 +5,6 @@ package net.sourceforge.phpdt.internal.corext.util; import net.sourceforge.phpeclipse.PHPeclipsePlugin; -//import net.sourceforge.phpeclipse.ui.WebUI; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java index 4d7ed3e..20b7a2a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/CodeFormatter.java @@ -44,13 +44,13 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { /** * Represents a block in the constructions stack. */ - public static final int BLOCK = ITerminalSymbols.TokenNameLBRACE; + public static final TokenName BLOCK = TokenName.LBRACE; /** * Represents a block following a control statement in the * constructions stack. */ - public static final int NONINDENT_BLOCK = -100; + public static final TokenName NONINDENT_BLOCK = TokenName.NONE_INDENT_BLOCK; /** * Contains the formatted output. @@ -72,7 +72,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Contains the tokens responsible for the current indentation level and the * blocks not closed yet. */ - private int[] constructions; + private TokenName[] constructions; /** * Index in the constructions array. @@ -158,7 +158,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { public CodeFormatter(Map settings) { // initialize internal state constructionsCount = 0; - constructions = new int[10]; + constructions = new TokenName[10]; currentLineIndentationLevel = indentationLevel = initialIndentationLevel; currentCommentOffset = -1; // initialize primary and secondary scanners @@ -189,11 +189,11 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Returns true if a lineSeparator has to be inserted before * operator false otherwise. */ - private static boolean breakLineBeforeOperator(int operator) { + private static boolean breakLineBeforeOperator(TokenName operator) { switch (operator) { - case TokenNameCOMMA: - case TokenNameSEMICOLON: - case TokenNameEQUAL: + case COMMA: + case SEMICOLON: + case EQUAL: return false; default: return true; @@ -293,12 +293,18 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { beginningOfLineIndex = formattedSource.length(); if (containsOpenCloseBraces) { containsOpenCloseBraces = false; - outputLine(currentString, false, - indentationLevelForOpenCloseBraces, 0, -1, null, 0); + outputLine(currentString, + false, + indentationLevelForOpenCloseBraces, + TokenName.NONE, + -1, null, 0); indentationLevelForOpenCloseBraces = currentLineIndentationLevel; } else { - outputLine(currentString, false, currentLineIndentationLevel, 0, - -1, null, 0); + outputLine(currentString, + false, + currentLineIndentationLevel, + TokenName.NONE, + -1, null, 0); } int scannerSourceLength = scanner.source.length; if ((scannerSourceLength > 2) @@ -322,9 +328,10 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Formats the input string. */ private void format() { - int token = 0; - int previousToken = 0; - int previousCompilableToken = 0; + TokenName token = TokenName.NONE; + TokenName previousToken = TokenName.NONE; + TokenName previousCompilableToken = TokenName.NONE; + int indentationOffset = 0; int newLinesInWhitespace = 0; // number of new lines in the previous whitespace token @@ -358,10 +365,10 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // : // it can be case or ? int tokenBeforeColonCount = 0; - int[] tokenBeforeColon = new int[10]; + TokenName[] tokenBeforeColon = new TokenName[10]; constructionsCount = 0; // initializes the constructions count. // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise. - int nlicsToken = 0; + TokenName nlicsToken = ITerminalSymbols.TokenName.NONE; // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and // else boolean specialElse = false; @@ -390,7 +397,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } // Patch for line comment // See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=23096 - if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) { + if (token == ITerminalSymbols.TokenName.COMMENT_LINE) { int length = scanner.currentPosition; loop: for (int index = length - 1; index >= 0; index--) { switch (scanner.source[index]) { @@ -407,22 +414,22 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { if (!handleInvalidToken(e)) { throw e; } - token = 0; + token = ITerminalSymbols.TokenName.NONE; } - if (token == Scanner.TokenNameEOF) { + if (token == Scanner.TokenName.EOF) { break; - } else if (token == Scanner.TokenNameHEREDOC) { + } else if (token == Scanner.TokenName.HEREDOC) { // no indentation for heredocs and HTML ! - outputCurrentTokenWithoutIndent(Scanner.TokenNameHEREDOC, 0); + outputCurrentTokenWithoutIndent(Scanner.TokenName.HEREDOC, 0); continue; - } else if (token == Scanner.TokenNameINLINE_HTML) { + } else if (token == Scanner.TokenName.INLINE_HTML) { // no indentation for heredocs and HTML ! int newLineCount = 1; if (scanner.startPosition == 0) { newLineCount = 0; } outputCurrentTokenWithoutIndent( - Scanner.TokenNameINLINE_HTML, newLineCount); + Scanner.TokenName.INLINE_HTML, newLineCount); int srcLen = scanner.source.length; if (scanner.currentPosition < srcLen - 1) { newLine(1); @@ -439,25 +446,25 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // except if the current token is ELSE, CATCH or if we are in a // switch/case if (clearNonBlockIndents - && (token != Scanner.TokenNameWHITESPACE)) { + && (token != Scanner.TokenName.WHITESPACE)) { switch (token) { - case TokenNameelse: + case ELSE: if (constructionsCount > 0 - && constructions[constructionsCount - 1] == TokenNameelse) { + && constructions[constructionsCount - 1] == TokenName.ELSE) { pendingNewLines = 1; specialElse = true; } - indentationLevel += popInclusiveUntil(TokenNameif); + indentationLevel += popInclusiveUntil(TokenName.IF); break; - // case TokenNamecatch : - // indentationLevel += popInclusiveUntil(TokenNamecatch); + // case TokenName.catch : + // indentationLevel += popInclusiveUntil(TokenName.catch); // break; - // case TokenNamefinally : - // indentationLevel += popInclusiveUntil(TokenNamecatch); + // case TokenName.finally : + // indentationLevel += popInclusiveUntil(TokenName.catch); // break; - case TokenNamewhile: - if (nlicsToken == TokenNamedo) { - indentationLevel += pop(TokenNamedo); + case WHILE: + if (nlicsToken == TokenName.DO) { + indentationLevel += pop(TokenName.DO); break; } default: @@ -472,14 +479,14 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // returns to the indentation level created by the SWITCH // keyword // if the current token is a CASE or a DEFAULT - if (token == TokenNamecase || token == TokenNamedefault) { - indentationLevel += pop(TokenNamecase); + if (token == TokenName.CASE || token == TokenName.DEFAULT) { + indentationLevel += pop(TokenName.CASE); } - // if (token == Scanner.TokenNamethrows) { + // if (token == Scanner.TokenName.throws) { // inThrowsClause = true; // } - if ((token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) - && previousToken != Scanner.TokenNameDOT) { + if ((token == Scanner.TokenName.CLASS || token == Scanner.TokenName.INTERFACE) + && previousToken != Scanner.TokenName.DOT) { inClassOrInterfaceHeader = true; } /* @@ -489,12 +496,12 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // elseIfOnSameLine is true. // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting // if (pendingNewlineAfterParen - // && previousCompilableToken == TokenNameelse - // && token == TokenNameif + // && previousCompilableToken == TokenName.else + // && token == TokenName.if // && options.compactElseIfMode) { // pendingNewlineAfterParen = false; // pendingNewLines = 0; - // indentationLevel += pop(TokenNameelse); + // indentationLevel += pop(TokenName.else); // // because else if is now one single statement, // // the indentation level after it is increased by one and not // by 2 @@ -506,9 +513,9 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // block // following it. pendingNewlineAfterParen = pendingNewlineAfterParen - || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE); + || (previousCompilableToken == TokenName.RPAREN && token == TokenName.LBRACE); if (pendingNewlineAfterParen - && token != Scanner.TokenNameWHITESPACE) { + && token != Scanner.TokenName.WHITESPACE) { pendingNewlineAfterParen = false; // Do to add a newline & indent sequence if the current // token is an @@ -520,17 +527,17 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // statement // has been closed and the current token is not an opening // brace - if (token != TokenNameLBRACE && !isComment(token) + if (token != TokenName.LBRACE && !isComment(token) // to avoid adding new line between else and a // comment - && token != TokenNameDOT - && !(previousCompilableToken == TokenNameRPAREN && token == TokenNameSEMICOLON)) { + && token != TokenName.DOT + && !(previousCompilableToken == TokenName.RPAREN && token == TokenName.SEMICOLON)) { newLine(1); currentLineIndentationLevel = indentationLevel; pendingNewLines = 0; pendingSpace = false; } else { - if (token == TokenNameLBRACE + if (token == TokenName.LBRACE && options.newLineBeforeOpeningBraceMode) { newLine(1); if (constructionsCount > 0 @@ -545,17 +552,17 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } } - if (token == TokenNameLBRACE + if (token == TokenName.LBRACE && options.newLineBeforeOpeningBraceMode && constructionsCount > 0 - && constructions[constructionsCount - 1] == TokenNamedo) { + && constructions[constructionsCount - 1] == TokenName.DO) { newLine(1); currentLineIndentationLevel = indentationLevel - 1; pendingNewLines = 0; pendingSpace = false; } // see PR 1G5G8EC - if (token == TokenNameLBRACE && inThrowsClause) { + if (token == TokenName.LBRACE && inThrowsClause) { inThrowsClause = false; if (options.newLineBeforeOpeningBraceMode) { newLine(1); @@ -565,7 +572,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } // see PR 1G5G82G - if (token == TokenNameLBRACE && inClassOrInterfaceHeader) { + if (token == TokenName.LBRACE && inClassOrInterfaceHeader) { inClassOrInterfaceHeader = false; if (options.newLineBeforeOpeningBraceMode) { newLine(1); @@ -575,8 +582,8 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } // don't linebreak empty array declarations - if (token == TokenNameRPAREN && arrayDeclarationCount > 0) { - if (previousCompilableToken == TokenNameLPAREN) { + if (token == TokenName.RPAREN && arrayDeclarationCount > 0) { + if (previousCompilableToken == TokenName.LPAREN) { pendingNewLines = 0; } } @@ -588,37 +595,37 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // (if it's a one-line comment, a blank line is added after it). if (((pendingNewLines > 0 && (!isComment(token))) || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token))) - || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) || (newLinesInWhitespace > 0 && previousCompilableToken == TokenNameDOT)) - && token != Scanner.TokenNameWHITESPACE) { + || (previousCompilableToken == TokenName.LBRACE && token == TokenName.RBRACE) || (newLinesInWhitespace > 0 && previousCompilableToken == TokenName.DOT)) + && token != Scanner.TokenName.WHITESPACE) { // Do not add newline & indent between an adjoining close // brace and // close paren. Anonymous inner classes may use this form. - boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE - && token == TokenNameRPAREN; + boolean closeBraceAndCloseParen = previousToken == TokenName.RBRACE + && token == TokenName.RPAREN; // OPTION (NewLineInCompoundStatement): do not add newline & // indent // between close brace and else, (do) while, catch, and // finally if // newlineInCompoundStatement is true. - boolean nlicsOption = previousToken == TokenNameRBRACE + boolean nlicsOption = previousToken == TokenName.RBRACE && !options.newlineInControlStatementMode - && (token == TokenNameelse - || (token == TokenNamewhile && nlicsToken == TokenNamedo) - || token == TokenNamecatch || token == TokenNamefinally); + && (token == TokenName.ELSE + || (token == TokenName.WHILE && nlicsToken == TokenName.DO) + || token == TokenName.CATCH || token == TokenName.FINALLY); // Do not add a newline & indent between a close brace and // semi-colon. - boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE - && token == TokenNameSEMICOLON; + boolean semiColonAndCloseBrace = previousToken == TokenName.RBRACE + && token == TokenName.SEMICOLON; // Do not add a new line & indent between a multiline // comment and a // opening brace - boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK - && token == TokenNameLBRACE; + boolean commentAndOpenBrace = previousToken == Scanner.TokenName.COMMENT_BLOCK + && token == TokenName.LBRACE; // Do not add a newline & indent between a close brace and a // colon // (in array assignments, for example). - boolean commaAndCloseBrace = previousToken == TokenNameRBRACE - && token == TokenNameCOMMA; + boolean commaAndCloseBrace = previousToken == TokenName.RBRACE + && token == TokenName.COMMA; // Add a newline and indent, if appropriate. if (specialElse || (!commentAndOpenBrace @@ -637,8 +644,8 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines; } - if (previousCompilableToken == TokenNameLBRACE - && token == TokenNameRBRACE) { + if (previousCompilableToken == TokenName.LBRACE + && token == TokenName.RBRACE) { containsOpenCloseBraces = true; indentationLevelForOpenCloseBraces = currentLineIndentationLevel; if (isComment(previousToken)) { @@ -649,7 +656,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * constructions[constructionsCount-1] == * NONINDENT_BLOCK && * (constructions[constructionsCount-2] == - * TokenNamefor + * TokenName.for */ if (options.newLineInEmptyBlockMode) { if (inArrayAssignment) { @@ -665,18 +672,18 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // see PR 1FKKC3U: LFCOM:WINNT - Format problem with // a comment // before the ';' - if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) { + if (!((previousToken == Scanner.TokenName.COMMENT_BLOCK || previousToken == Scanner.TokenName.COMMENT_PHPDOC) && token == TokenName.SEMICOLON)) { newLine(pendingNewLines); } } - if (((previousCompilableToken == TokenNameSEMICOLON) - || (previousCompilableToken == TokenNameLBRACE) - || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken))) - && (token == TokenNameRBRACE)) { + if (((previousCompilableToken == TokenName.SEMICOLON) + || (previousCompilableToken == TokenName.LBRACE) + || (previousCompilableToken == TokenName.RBRACE) || (isComment(previousToken))) + && (token == TokenName.RBRACE)) { indentationOffset = -1; indentationLevel += popExclusiveUntilBlock(); } - if (previousToken == Scanner.TokenNameCOMMENT_LINE + if (previousToken == Scanner.TokenName.COMMENT_LINE && inAssignment) { // PR 1FI5IPO currentLineIndentationLevel++; @@ -690,51 +697,51 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { pendingNewLines = 0; newLinesInWhitespace = 0; specialElse = false; - if (nlicsToken == TokenNamedo && token == TokenNamewhile) { - nlicsToken = 0; + if (nlicsToken == TokenName.DO && token == TokenName.WHILE) { + nlicsToken = ITerminalSymbols.TokenName.NONE; } } - boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML - && token == TokenNameWHITESPACE; + boolean phpTagAndWhitespace = previousToken == TokenName.INLINE_HTML + && token == TokenName.WHITESPACE; switch (token) { - // case TokenNameDOLLAR : + // case TokenName.DOLLAR : // dollarBraceCount++; // break; - case TokenNameelse: - // case TokenNamefinally : + case ELSE: + // case TokenName.finally : expectingOpenBrace = true; pendingNewlineAfterParen = true; indentationLevel += pushControlStatement(token); break; - case TokenNamecase: - case TokenNamedefault: + case CASE: + case DEFAULT: if (tokenBeforeColonCount == tokenBeforeColon.length) { System .arraycopy( tokenBeforeColon, 0, - (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), + (tokenBeforeColon = new TokenName[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount); } - tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase; - indentationLevel += pushControlStatement(TokenNamecase); + tokenBeforeColon[tokenBeforeColonCount++] = TokenName.CASE; + indentationLevel += pushControlStatement(TokenName.CASE); break; - case TokenNameQUESTION: + case QUESTION: if (tokenBeforeColonCount == tokenBeforeColon.length) { System .arraycopy( tokenBeforeColon, 0, - (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), + (tokenBeforeColon = new TokenName[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount); } tokenBeforeColon[tokenBeforeColonCount++] = token; break; - case TokenNameswitch: - case TokenNamefor: - case TokenNameforeach: - case TokenNameif: - case TokenNamewhile: + case SWITCH: + case FOR: + case FOREACH: + case IF: + case WHILE: if (openParenthesisCount == openParenthesis.length) { System .arraycopy( @@ -747,42 +754,42 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { expectingOpenBrace = true; indentationLevel += pushControlStatement(token); break; - case TokenNametry: + case TRY: pendingNewlineAfterParen = true; - case TokenNamecatch: + case CATCH: // several CATCH statements can be contiguous. // a CATCH is encountered pop until first CATCH (if a CATCH // follows a TRY it works the same way, // as CATCH and TRY are the same token in the stack). expectingOpenBrace = true; - indentationLevel += pushControlStatement(TokenNamecatch); + indentationLevel += pushControlStatement(TokenName.CATCH); break; - case TokenNamedo: + case DO: expectingOpenBrace = true; indentationLevel += pushControlStatement(token); nlicsToken = token; break; - case TokenNamenew: + case NEW: break; - case TokenNameLPAREN: - // if (previousToken == TokenNamesynchronized) { + case LPAREN: + // if (previousToken == TokenName.synchronized) { // indentationLevel += pushControlStatement(previousToken); // } else { // Put a space between the previous and current token if the // previous token was not a keyword, open paren, logical // compliment (eg: !), semi-colon, open brace, close brace, // super, or this. - if (previousCompilableToken != TokenNameLBRACKET - && previousToken != TokenNameIdentifier - && previousToken != 0 - && previousToken != TokenNameNOT - && previousToken != TokenNameLPAREN - && previousToken != TokenNameTWIDDLE - && previousToken != TokenNameSEMICOLON - && previousToken != TokenNameLBRACE - && previousToken != TokenNameRBRACE - && previousToken != TokenNamesuper) { - // && previousToken != TokenNamethis) { + if (previousCompilableToken != TokenName.LBRACKET + && previousToken != TokenName.IDENTIFIER + && previousToken != TokenName.NONE + && previousToken != TokenName.NOT + && previousToken != TokenName.LPAREN + && previousToken != TokenName.TWIDDLE + && previousToken != TokenName.SEMICOLON + && previousToken != TokenName.LBRACE + && previousToken != TokenName.RBRACE + && previousToken != TokenName.SUPER) { + // && previousToken != TokenName.THIS) { if (!options.compactArrays) { space(); } @@ -797,7 +804,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { openParenthesis[0]++; pendingSpace = false; // recognize array declaration for nice output - if (previousCompilableToken == TokenNamearray) { + if (previousCompilableToken == TokenName.ARRAY) { arrayDeclarationCount++; arrayDeclarationParenthesis[arrayDeclarationCount] = openParenthesis[openParenthesisCount - 1]; if (!options.compactArrays) { @@ -807,17 +814,17 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } // S } break; - case TokenNameRPAREN: + case RPAREN: // check for closing array declaration if (arrayDeclarationCount > 0) { if (arrayDeclarationParenthesis[arrayDeclarationCount] == openParenthesis[openParenthesisCount - 1]) { - if (previousCompilableToken != TokenNameLPAREN) { + if (previousCompilableToken != TokenName.LPAREN) { if (!options.compactArrays) { newLine(1); } - } else if (previousToken == TokenNameCOMMENT_LINE - || previousToken == TokenNameCOMMENT_BLOCK - || previousToken == TokenNameCOMMENT_PHPDOC) { + } else if (previousToken == TokenName.COMMENT_LINE + || previousToken == TokenName.COMMENT_BLOCK + || previousToken == TokenName.COMMENT_PHPDOC) { // prevent to combine comment line and statement line (#1475484) if (!options.compactArrays) { newLine(1); @@ -850,13 +857,13 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } pendingSpace = false; break; - case TokenNameLBRACE: - if (previousCompilableToken == TokenNameDOLLAR) { + case LBRACE: + if (previousCompilableToken == TokenName.DOLLAR) { dollarBraceCount++; } else { - if ((previousCompilableToken == TokenNameRBRACKET) - || (previousCompilableToken == TokenNameEQUAL)) { - // if (previousCompilableToken == TokenNameRBRACKET) + if ((previousCompilableToken == TokenName.RBRACKET) + || (previousCompilableToken == TokenName.EQUAL)) { + // if (previousCompilableToken == TokenName.RBRACKET) // { inArrayAssignment = true; inAssignment = false; @@ -872,12 +879,12 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } break; - case TokenNameRBRACE: + case RBRACE: if (dollarBraceCount > 0) { dollarBraceCount--; break; } - if (previousCompilableToken == TokenNameRPAREN) { + if (previousCompilableToken == TokenName.RPAREN) { pendingSpace = false; } if (inArrayAssignment) { @@ -887,7 +894,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } else { pendingNewLines = 1; indentationLevel += popInclusiveUntilBlock(); - if (previousCompilableToken == TokenNameRPAREN) { + if (previousCompilableToken == TokenName.RPAREN) { // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on // message // expression @@ -897,19 +904,19 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } if (constructionsCount > 0) { switch (constructions[constructionsCount - 1]) { - case TokenNamefor: - case TokenNameforeach: + case FOR: + case FOREACH: // indentationLevel += popExclusiveUntilBlock(); // break; - case TokenNameswitch: - case TokenNameif: - case TokenNameelse: - case TokenNametry: - case TokenNamecatch: - case TokenNamefinally: - case TokenNamewhile: - case TokenNamedo: - // case TokenNamesynchronized : + case SWITCH: + case IF: + case ELSE: + case TRY: + case CATCH: + case FINALLY: + case WHILE: + case DO: + // case TokenName.synchronized : clearNonBlockIndents = true; default: break; @@ -917,18 +924,18 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } break; - case TokenNameLBRACKET: + case LBRACKET: openBracketCount++; pendingSpace = false; break; - case TokenNameRBRACKET: + case RBRACKET: openBracketCount -= (openBracketCount > 0) ? 1 : 0; // if there is no left bracket to close, the right bracket // is // ignored. pendingSpace = false; break; - case TokenNameCOMMA: + case COMMA: pendingSpace = false; if (arrayDeclarationCount > 0) { if (arrayDeclarationParenthesis[arrayDeclarationCount] == openParenthesis[openParenthesisCount - 1]) { @@ -939,13 +946,13 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } break; - case TokenNameDOT: + case DOT: if (!options.compactStringConcatenation) { space(); } pendingSpace = false; break; - case TokenNameSEMICOLON: + case SEMICOLON: // Do not generate line terminators in the definition of // the for statement. // if not in this case, jump a line and reduce indentation @@ -964,53 +971,53 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { inAssignment = false; pendingSpace = false; break; - case TokenNamePLUS_PLUS: - case TokenNameMINUS_MINUS: + case PLUS_PLUS: + case MINUS_MINUS: // Do not put a space between a post-increment/decrement // and the identifier being modified. - if (previousToken == TokenNameIdentifier - || previousToken == TokenNameRBRACKET - || previousToken == TokenNameVariable) { + if (previousToken == TokenName.IDENTIFIER + || previousToken == TokenName.RBRACKET + || previousToken == TokenName.VARIABLE) { pendingSpace = false; } break; - case TokenNamePLUS: + case PLUS: // previously ADDITION - case TokenNameMINUS: + case MINUS: // Handle the unary operators plus and minus via a flag if (!isLiteralToken(previousToken) - && previousToken != TokenNameIdentifier - && previousToken != TokenNameRPAREN - && previousToken != TokenNameRBRACKET) { + && previousToken != TokenName.IDENTIFIER + && previousToken != TokenName.RPAREN + && previousToken != TokenName.RBRACKET) { unarySignModifier = 1; } break; - case TokenNameCOLON: + case COLON: // In a switch/case statement, add a newline & indent // when a colon is encountered. if (tokenBeforeColonCount > 0) { - if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) { + if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenName.CASE) { pendingNewLines = 1; } tokenBeforeColonCount--; } break; - case TokenNameEQUAL: + case EQUAL: inAssignment = true; break; - case Scanner.TokenNameCOMMENT_LINE: + case COMMENT_LINE: pendingNewLines = 1; //if (inAssignment) { // currentLineIndentationLevel++; //} break; // a line is always inserted after a one-line // comment - case Scanner.TokenNameCOMMENT_PHPDOC: - case Scanner.TokenNameCOMMENT_BLOCK: + case COMMENT_PHPDOC: + case COMMENT_BLOCK: currentCommentOffset = getCurrentCommentOffset(); pendingNewLines = 1; break; - case Scanner.TokenNameWHITESPACE: + case WHITESPACE: if (!phpTagAndWhitespace) { // Count the number of line terminators in the // whitespace so @@ -1036,7 +1043,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { - scanner.currentPosition); break; } - // case TokenNameHTML : + // case TokenName.HTML : // // Add the next token to the formatted source string. // // outputCurrentToken(token); // int startPosition = scanner.startPosition; @@ -1050,16 +1057,16 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // } // break; default: - if ((token == TokenNameIdentifier) || isLiteralToken(token) - || token == TokenNamesuper) { - // || token == TokenNamethis) { + if ((token == TokenName.IDENTIFIER) || isLiteralToken(token) + || token == TokenName.SUPER) { + // || token == TokenName.this) { // Do not put a space between a unary operator // (eg: ++, --, +, -) and the identifier being modified. - if (previousToken == TokenNamePLUS_PLUS - || previousToken == TokenNameMINUS_MINUS - || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // -> - || (previousToken == TokenNamePLUS && unarySignModifier > 0) - || (previousToken == TokenNameMINUS && unarySignModifier > 0)) { + if (previousToken == TokenName.PLUS_PLUS + || previousToken == TokenName.MINUS_MINUS + || (previousToken == TokenName.MINUS_GREATER && options.compactDereferencingMode) // -> + || (previousToken == TokenName.PLUS && unarySignModifier > 0) + || (previousToken == TokenName.MINUS && unarySignModifier > 0)) { pendingSpace = false; } unarySignModifier = 0; @@ -1067,7 +1074,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { break; } // Do not output whitespace tokens. - if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { + if (token != Scanner.TokenName.WHITESPACE || phpTagAndWhitespace) { /* * Add pending space to the formatted source string. Do not * output a space under the following circumstances: 1) this @@ -1080,23 +1087,23 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * close brace 8) previous token is a single line comment 9) * current token is a '->' */ - if (token == TokenNameMINUS_GREATER + if (token == TokenName.MINUS_GREATER && options.compactDereferencingMode) pendingSpace = false; - boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE - && token == TokenNameRBRACE; + boolean openAndCloseBrace = previousCompilableToken == TokenName.LBRACE + && token == TokenName.RBRACE; if (pendingSpace && insertSpaceAfter(previousToken) - && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE)) - && previousToken != Scanner.TokenNameCOMMENT_LINE) { - if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) + && !(inAssignment && (previousToken == TokenName.LBRACE || token == TokenName.RBRACE)) + && previousToken != Scanner.TokenName.COMMENT_LINE) { + if ((!(options.compactAssignmentMode && token == TokenName.EQUAL)) && !openAndCloseBrace) space(); } // Add the next token to the formatted source string. outputCurrentToken(token); - if (token == Scanner.TokenNameCOMMENT_LINE + if (token == Scanner.TokenName.COMMENT_LINE && openParenthesisCount > 1) { pendingNewLines = 0; currentLineBuffer.append(options.lineSeparatorSequence); @@ -1105,11 +1112,11 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { pendingSpace = true; } // Whitespace tokens do not need to be remembered. - if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) { + if (token != Scanner.TokenName.WHITESPACE || phpTagAndWhitespace) { previousToken = token; - if (token != Scanner.TokenNameCOMMENT_BLOCK - && token != Scanner.TokenNameCOMMENT_LINE - && token != Scanner.TokenNameCOMMENT_PHPDOC) { + if (token != Scanner.TokenName.COMMENT_BLOCK + && token != Scanner.TokenName.COMMENT_LINE + && token != Scanner.TokenName.COMMENT_PHPDOC) { previousCompilableToken = token; } } @@ -1324,98 +1331,98 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { */ // private static int getTokenPriority(int token) { // switch (token) { -// case TokenNameextends: -// // case TokenNameimplements : -// // case TokenNamethrows : +// case TokenName.extends: +// // case TokenName.implements : +// // case TokenName.throws : // return 10; -// case TokenNameSEMICOLON: +// case TokenName.SEMICOLON: // // ; // return 20; -// case TokenNameCOMMA: +// case TokenName.COMMA: // // , // return 25; -// case TokenNameEQUAL: +// case TokenName.EQUAL: // // = // return 30; -// case TokenNameAND_AND: +// case TokenName.AND_AND: // // && -// case TokenNameOR_OR: +// case TokenName.OR_OR: // // || // return 40; -// case TokenNameQUESTION: +// case TokenName.QUESTION: // // ? -// case TokenNameCOLON: +// case TokenName.COLON: // // : // return 50; // it's better cutting on ?: than on ; -// case TokenNameEQUAL_EQUAL: +// case TokenName.EQUAL_EQUAL: // // == -// case TokenNameEQUAL_EQUAL_EQUAL: +// case TokenName.EQUAL_EQUAL_EQUAL: // // === -// case TokenNameNOT_EQUAL: +// case TokenName.NOT_EQUAL: // // != -// case TokenNameNOT_EQUAL_EQUAL: +// case TokenName.NOT_EQUAL_EQUAL: // // != // return 60; -// case TokenNameLESS: +// case TokenName.LESS: // // < -// case TokenNameLESS_EQUAL: +// case TokenName.LESS_EQUAL: // // <= -// case TokenNameGREATER: +// case TokenName.GREATER: // // > -// case TokenNameGREATER_EQUAL: +// case TokenName.GREATER_EQUAL: // // >= -// // case TokenNameinstanceof : // instanceof +// // case TokenName.instanceof : // instanceof // return 70; -// case TokenNamePLUS: +// case TokenName.PLUS: // // + -// case TokenNameMINUS: +// case TokenName.MINUS: // // - // return 80; -// case TokenNameMULTIPLY: +// case TokenName.MULTIPLY: // // * -// case TokenNameDIVIDE: +// case TokenName.DIVIDE: // // / -// case TokenNameREMAINDER: +// case TokenName.REMAINDER: // // % // return 90; -// case TokenNameLEFT_SHIFT: +// case TokenName.LEFT_SHIFT: // // << -// case TokenNameRIGHT_SHIFT: +// case TokenName.RIGHT_SHIFT: // // >> -// // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> +// // case TokenName.UNSIGNED_RIGHT_SHIFT : // >>> // return 100; -// case TokenNameAND: +// case TokenName.AND: // // & -// case TokenNameOR: +// case TokenName.OR: // // | -// case TokenNameXOR: +// case TokenName.XOR: // // ^ // return 110; -// case TokenNameMULTIPLY_EQUAL: +// case TokenName.MULTIPLY_EQUAL: // // *= -// case TokenNameDIVIDE_EQUAL: +// case TokenName.DIVIDE_EQUAL: // // /= -// case TokenNameREMAINDER_EQUAL: +// case TokenName.REMAINDER_EQUAL: // // %= -// case TokenNamePLUS_EQUAL: +// case TokenName.PLUS_EQUAL: // // += -// case TokenNameMINUS_EQUAL: +// case TokenName.MINUS_EQUAL: // // -= -// case TokenNameLEFT_SHIFT_EQUAL: +// case TokenName.LEFT_SHIFT_EQUAL: // // <<= -// case TokenNameRIGHT_SHIFT_EQUAL: +// case TokenName.RIGHT_SHIFT_EQUAL: // // >>= -// // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= -// case TokenNameAND_EQUAL: +// // case TokenName.UNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= +// case TokenName.AND_EQUAL: // // &= -// case TokenNameXOR_EQUAL: +// case TokenName.XOR_EQUAL: // // ^= -// case TokenNameOR_EQUAL: +// case TokenName.OR_EQUAL: // // .= -// case TokenNameDOT_EQUAL: +// case TokenName.DOT_EQUAL: // // |= // return 120; -// case TokenNameDOT: +// case TokenName.DOT: // // . // return 130; // default: @@ -1452,19 +1459,19 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Returns true if a space has to be inserted after operator * false otherwise. */ - private boolean insertSpaceAfter(int token) { + private boolean insertSpaceAfter(TokenName token) { switch (token) { - case TokenNameLPAREN: - case TokenNameNOT: - case TokenNameTWIDDLE: - case 0: + case LPAREN: + case NOT: + case TWIDDLE: + case NONE: // no token - case TokenNameWHITESPACE: - case TokenNameLBRACKET: - case TokenNameDOLLAR: - case Scanner.TokenNameCOMMENT_LINE: + case WHITESPACE: + case LBRACKET: + case DOLLAR: + case COMMENT_LINE: return false; - case TokenNameDOT: + case DOT: return !options.compactStringConcatenation; default: return true; @@ -1477,29 +1484,29 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Cannot be static as it uses the code formatter options (to know if the * compact assignment mode is on). */ - private boolean insertSpaceBefore(int token) { + private boolean insertSpaceBefore(TokenName token) { switch (token) { - case TokenNameEQUAL: + case EQUAL: return (!options.compactAssignmentMode); default: return false; } } - private static boolean isComment(int token) { - boolean result = token == Scanner.TokenNameCOMMENT_BLOCK - || token == Scanner.TokenNameCOMMENT_LINE - || token == Scanner.TokenNameCOMMENT_PHPDOC; + private static boolean isComment(TokenName token) { + boolean result = token == Scanner.TokenName.COMMENT_BLOCK + || token == Scanner.TokenName.COMMENT_LINE + || token == Scanner.TokenName.COMMENT_PHPDOC; return result; } - private static boolean isLiteralToken(int token) { - boolean result = token == TokenNameIntegerLiteral - // || token == TokenNameLongLiteral - // || token == TokenNameFloatingPointLiteral - || token == TokenNameDoubleLiteral - // || token == TokenNameCharacterLiteral - || token == TokenNameStringDoubleQuote; + private static boolean isLiteralToken(TokenName token) { + boolean result = token == TokenName.INTEGERLITERAL + // || token == TokenName.LongLiteral + // || token == TokenName.FloatingPointLiteral + || token == TokenName.DOUBLELITERAL + // || token == TokenName.CharacterLiteral + || token == TokenName.STRINGDOUBLEQUOTE; return result; } @@ -1519,10 +1526,10 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { if (containsOpenCloseBraces) { containsOpenCloseBraces = false; outputLine(currentLine, false, indentationLevelForOpenCloseBraces, - 0, -1, null, 0); + TokenName.NONE, -1, null, 0); indentationLevelForOpenCloseBraces = currentLineIndentationLevel; } else { - outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, + outputLine(currentLine, false, currentLineIndentationLevel, TokenName.NONE, -1, null, 0); } // dump line break(s) @@ -1541,139 +1548,139 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { currentLineIndentationLevel = initialIndentationLevel; } - private String operatorString(int operator) { + private String operatorString(TokenName operator) { switch (operator) { - case TokenNameextends: + case EXTENDS: return "extends"; //$NON-NLS-1$ - // case TokenNameimplements : + // case TokenName.implements : // return "implements"; //$NON-NLS-1$ // - // case TokenNamethrows : + // case TokenName.throws : // return "throws"; //$NON-NLS-1$ - case TokenNameSEMICOLON: + case SEMICOLON: // ; return ";"; //$NON-NLS-1$ - case TokenNameCOMMA: + case COMMA: // , return ","; //$NON-NLS-1$ - case TokenNameEQUAL: + case EQUAL: // = return "="; //$NON-NLS-1$ - case TokenNameAND_AND: + case AND_AND: // && (15.22) return "&&"; //$NON-NLS-1$ - case TokenNameOR_OR: + case OR_OR: // || (15.23) return "||"; //$NON-NLS-1$ - case TokenNameQUESTION: + case QUESTION: // ? (15.24) return "?"; //$NON-NLS-1$ - case TokenNameCOLON: + case COLON: // : (15.24) return ":"; //$NON-NLS-1$ - case TokenNamePAAMAYIM_NEKUDOTAYIM: + case PAAMAYIM_NEKUDOTAYIM: // : (15.24) return "::"; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL: + case EQUAL_EQUAL: // == (15.20, 15.20.1, 15.20.2, 15.20.3) return "=="; //$NON-NLS-1$ - case TokenNameEQUAL_EQUAL_EQUAL: + case EQUAL_EQUAL_EQUAL: // == (15.20, 15.20.1, 15.20.2, 15.20.3) return "==="; //$NON-NLS-1$ - case TokenNameEQUAL_GREATER: + case EQUAL_GREATER: // -= (15.25.2) return "=>"; //$NON-NLS-1$ - case TokenNameNOT_EQUAL: + case NOT_EQUAL: // != (15.20, 15.20.1, 15.20.2, 15.20.3) return "!="; //$NON-NLS-1$ - case TokenNameNOT_EQUAL_EQUAL: + case NOT_EQUAL_EQUAL: // != (15.20, 15.20.1, 15.20.2, 15.20.3) return "!=="; //$NON-NLS-1$ - case TokenNameLESS: + case LESS: // < (15.19.1) return "<"; //$NON-NLS-1$ - case TokenNameLESS_EQUAL: + case LESS_EQUAL: // <= (15.19.1) return "<="; //$NON-NLS-1$ - case TokenNameGREATER: + case GREATER: // > (15.19.1) return ">"; //$NON-NLS-1$ - case TokenNameGREATER_EQUAL: + case GREATER_EQUAL: // >= (15.19.1) return ">="; //$NON-NLS-1$ - // case TokenNameinstanceof : // instanceof + // case instanceof : // instanceof // return "instanceof"; //$NON-NLS-1$ - case TokenNamePLUS: + case PLUS: // + (15.17, 15.17.2) return "+"; //$NON-NLS-1$ - case TokenNameMINUS: + case MINUS: // - (15.17.2) return "-"; //$NON-NLS-1$ - case TokenNameMULTIPLY: + case MULTIPLY: // * (15.16.1) return "*"; //$NON-NLS-1$ - case TokenNameDIVIDE: + case DIVIDE: // / (15.16.2) return "/"; //$NON-NLS-1$ - case TokenNameREMAINDER: + case REMAINDER: // % (15.16.3) return "%"; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT: + case LEFT_SHIFT: // << (15.18) return "<<"; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT: + case RIGHT_SHIFT: // >> (15.18) return ">>"; //$NON-NLS-1$ - // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // case UNSIGNED_RIGHT_SHIFT : // >>> (15.18) // return ">>>"; //$NON-NLS-1$ - case TokenNameAND: + case OP_AND: // & (15.21, 15.21.1, 15.21.2) return "&"; //$NON-NLS-1$ - case TokenNameOR: + case OP_OR: // | (15.21, 15.21.1, 15.21.2) return "|"; //$NON-NLS-1$ - case TokenNameXOR: + case OP_XOR: // ^ (15.21, 15.21.1, 15.21.2) return "^"; //$NON-NLS-1$ - case TokenNameMULTIPLY_EQUAL: + case MULTIPLY_EQUAL: // *= (15.25.2) return "*="; //$NON-NLS-1$ - case TokenNameDIVIDE_EQUAL: + case DIVIDE_EQUAL: // /= (15.25.2) return "/="; //$NON-NLS-1$ - case TokenNameREMAINDER_EQUAL: + case REMAINDER_EQUAL: // %= (15.25.2) return "%="; //$NON-NLS-1$ - case TokenNamePLUS_EQUAL: + case PLUS_EQUAL: // += (15.25.2) return "+="; //$NON-NLS-1$ - case TokenNameMINUS_EQUAL: + case MINUS_EQUAL: // -= (15.25.2) return "-="; //$NON-NLS-1$ - case TokenNameMINUS_GREATER: + case MINUS_GREATER: // -= (15.25.2) return "->"; //$NON-NLS-1$ - case TokenNameLEFT_SHIFT_EQUAL: + case LEFT_SHIFT_EQUAL: // <<= (15.25.2) return "<<="; //$NON-NLS-1$ - case TokenNameRIGHT_SHIFT_EQUAL: + case RIGHT_SHIFT_EQUAL: // >>= (15.25.2) return ">>="; //$NON-NLS-1$ - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // case UNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) // return ">>>="; //$NON-NLS-1$ - case TokenNameAND_EQUAL: + case AND_EQUAL: // &= (15.25.2) return "&="; //$NON-NLS-1$ - case TokenNameXOR_EQUAL: + case XOR_EQUAL: // ^= (15.25.2) return "^="; //$NON-NLS-1$ - case TokenNameOR_EQUAL: + case OR_EQUAL: // |= (15.25.2) return "|="; //$NON-NLS-1$ - case TokenNameDOT_EQUAL: + case DOT_EQUAL: // .= return ".="; //$NON-NLS-1$ - case TokenNameDOT: + case DOT: // . return "."; //$NON-NLS-1$ default: @@ -1695,7 +1702,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } - private void outputCurrentTokenWithoutIndent(int token, int newLineCount) { + private void outputCurrentTokenWithoutIndent(TokenName heredoc, int newLineCount) { newLine(newLineCount); formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition); @@ -1706,13 +1713,13 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * If it contains \n, append a LINE_SEPARATOR and indent * after it. */ - private void outputCurrentToken(int token) { + private void outputCurrentToken(TokenName token) { char[] source = scanner.source; int startPosition = scanner.startPosition; switch (token) { - case Scanner.TokenNameCOMMENT_PHPDOC: - case Scanner.TokenNameCOMMENT_BLOCK: - case Scanner.TokenNameCOMMENT_LINE: + case COMMENT_PHPDOC: + case COMMENT_BLOCK: + case COMMENT_LINE: boolean endOfLine = false; int currentCommentOffset = getCurrentCommentOffset(); int beginningOfLineSpaces = 0; @@ -1827,7 +1834,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * value of the operator belonging to currentString. */ private void outputLine(String currentString, boolean preIndented, - int depth, int operator, int substringIndex, + int depth, TokenName operator, int substringIndex, int[] startSubstringIndexes, int offsetInGlobalLine) { boolean emptyFirstSubString = false; String operatorString = operatorString(operator); @@ -1839,7 +1846,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { dumpTab(depth); preIndented = true; } - if (operator != 0) { + if (operator.compareTo (TokenName.NONE) > 0) { if (insertSpaceBefore(operator)) { formattedSource.append(' '); increaseSplitDelta(1); @@ -1847,9 +1854,9 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { formattedSource.append(operatorString); increaseSplitDelta(operatorString.length()); if (insertSpaceAfter(operator) - && operator != TokenNameimplements - && operator != TokenNameextends) { - // && operator != TokenNamethrows) { + && operator != TokenName.IMPLEMENTS + && operator != TokenName.EXTENDS) { + // && operator != TokenName.throws) { formattedSource.append(' '); increaseSplitDelta(1); } @@ -1864,8 +1871,8 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // dumping it // indent before postfix operator // indent also when the line cannot be split - if (operator == TokenNameextends || operator == TokenNameimplements) { - // || operator == TokenNamethrows) { + if (operator == TokenName.EXTENDS || operator == TokenName.IMPLEMENTS) { + // || operator == TokenName.throws) { formattedSource.append(' '); increaseSplitDelta(1); } @@ -1948,12 +1955,12 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { if (placeOperatorBehind) { if (insertSpaceBefore(operator)) { formattedSource.append(' '); - if (operator != 0) { + if (operator.compareTo (TokenName.NONE) > 0) { increaseSplitDelta(1); } } formattedSource.append(operatorString); - if (operator != 0) { + if (operator.compareTo (TokenName.NONE) > 0) { increaseSplitDelta(operatorString.length()); } } @@ -1963,23 +1970,23 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // extends has to stand alone on a line when currentString has been // split. if (options.maxLineLength != 0 && splitLine != null - && (operator == TokenNameextends)) { - // || operator == TokenNameimplements - // || operator == TokenNamethrows)) { + && (operator == TokenName.EXTENDS)) { + // || operator == TokenName.IMPLEMENTS + // || operator == TokenName.THROWS)) { formattedSource.append(options.lineSeparatorSequence); increaseSplitDelta(options.lineSeparatorSequence.length); dumpTab(depth + 1); } else { - if (operator == TokenNameextends) { - // || operator == TokenNameimplements - // || operator == TokenNamethrows) { + if (operator == TokenName.EXTENDS) { + // || operator == TokenName.implements + // || operator == TokenName.throws) { formattedSource.append(' '); increaseSplitDelta(1); } } // perform actual splitting String result[] = splitLine.substrings; - int[] splitOperators = splitLine.operators; + TokenName[] splitOperators = splitLine.operators; if (result[0].length() == 0) { // when the substring 0 is null, the substring 1 is correctly // indented. @@ -1998,16 +2005,18 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // line // comments) String currentResult = result[i]; - if (currentResult.length() != 0 || splitOperators[i] != 0) { + if (currentResult.length() != 0 || splitOperators[i].compareTo (TokenName.NONE) > 0) { int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$ || currentResult.startsWith("//")) //$NON-NLS-1$ ? indentationLevel - 1 : depth; - outputLine(currentResult, i == 0 - || (i == 1 && emptyFirstSubString) ? preIndented - : false, i == 0 ? newDepth : newDepth + 1, - splitOperators[i], i, splitLine.startSubstringsIndexes, - currentString.indexOf(currentResult)); + outputLine(currentResult, + i == 0 || (i == 1 && emptyFirstSubString) ? preIndented: false, + i == 0 ? newDepth : newDepth + 1, + splitOperators[i], + i, + splitLine.startSubstringsIndexes, + currentString.indexOf(currentResult)); if (i != max - 1) { formattedSource.append(options.lineSeparatorSequence); increaseSplitDelta(options.lineSeparatorSequence.length); @@ -2015,13 +2024,13 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { } } if (result.length == splitOperators.length - 1) { - int lastOperator = splitOperators[result.length]; + TokenName lastOperator = splitOperators[result.length]; String lastOperatorString = operatorString(lastOperator); formattedSource.append(options.lineSeparatorSequence); increaseSplitDelta(options.lineSeparatorSequence.length); if (breakLineBeforeOperator(lastOperator)) { dumpTab(depth + 1); - if (lastOperator != 0) { + if (lastOperator.compareTo (TokenName.NONE) > 0) { if (insertSpaceBefore(lastOperator)) { formattedSource.append(' '); increaseSplitDelta(1); @@ -2029,9 +2038,9 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { formattedSource.append(lastOperatorString); increaseSplitDelta(lastOperatorString.length()); if (insertSpaceAfter(lastOperator) - && lastOperator != TokenNameimplements - && lastOperator != TokenNameextends) { - // && lastOperator != TokenNamethrows) { + && lastOperator != TokenName.IMPLEMENTS + && lastOperator != TokenName.EXTENDS) { + // && lastOperator != TokenName.throws) { formattedSource.append(' '); increaseSplitDelta(1); } @@ -2051,10 +2060,10 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { /** * Pops the top statement of the stack if it is token */ - private int pop(int token) { + private int pop(TokenName do1) { int delta = 0; if ((constructionsCount > 0) - && (constructions[constructionsCount - 1] == token)) { + && (constructions[constructionsCount - 1] == do1)) { delta--; constructionsCount--; } @@ -2122,7 +2131,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { int delta = 0; for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK - && constructions[i] != TokenNamecase; i--) { + && constructions[i] != TokenName.CASE; i--) { constructionsCount--; delta--; } @@ -2137,7 +2146,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * @param token * the token to remove from the stack */ - private int popInclusiveUntil(int token) { + private int popInclusiveUntil(TokenName token) { int startCount = constructionsCount; int delta = 0; for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) { @@ -2184,12 +2193,12 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { int delta = 0; if (constructionsCount == constructions.length) System.arraycopy(constructions, 0, - (constructions = new int[constructionsCount * 2]), 0, + (constructions = new TokenName[constructionsCount * 2]), 0, constructionsCount); if ((constructionsCount == 0) || (constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) - || (constructions[constructionsCount - 1] == TokenNamecase)) { + || (constructions[constructionsCount - 1] == TokenName.CASE)) { delta++; constructions[constructionsCount++] = BLOCK; } else { @@ -2202,24 +2211,24 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { * Pushes token.
* Creates a new bigger array if the current one is full. */ - private int pushControlStatement(int token) { + private int pushControlStatement(TokenName token) { if (constructionsCount == constructions.length) System.arraycopy(constructions, 0, - (constructions = new int[constructionsCount * 2]), 0, + (constructions = new TokenName[constructionsCount * 2]), 0, constructionsCount); constructions[constructionsCount++] = token; return 1; } // private static boolean separateFirstArgumentOn(int currentToken) { -// // return (currentToken == TokenNameCOMMA || currentToken == -// // TokenNameSEMICOLON); -// return currentToken != TokenNameif && currentToken != TokenNameLPAREN -// && currentToken != TokenNameNOT -// && currentToken != TokenNamewhile -// && currentToken != TokenNamefor -// && currentToken != TokenNameforeach -// && currentToken != TokenNameswitch; +// // return (currentToken == TokenName.COMMA || currentToken == +// // TokenName.SEMICOLON); +// return currentToken != TokenName.if && currentToken != TokenName.LPAREN +// && currentToken != TokenName.NOT +// && currentToken != TokenName.while +// && currentToken != TokenName.for +// && currentToken != TokenName.foreach +// && currentToken != TokenName.switch; // } /** @@ -2313,7 +2322,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // while (true) { // // takes the next token // try { - // if (currentToken != Scanner.TokenNameWHITESPACE) + // if (currentToken != Scanner.TokenName.WHITESPACE) // previousToken = currentToken; // currentToken = splitScanner.getNextToken(); // if (Scanner.DEBUG) { @@ -2330,14 +2339,14 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // currentToken = 0; // // this value is not modify when an exception is raised. // } - // if (currentToken == TokenNameEOF) + // if (currentToken == TokenName.EOF) // break; // if (firstTokenOnLine == -1) { // firstTokenOnLine = currentToken; // } // switch (currentToken) { - // case TokenNameRBRACE : - // case TokenNameRPAREN : + // case TokenName.RBRACE : + // case TokenName.RPAREN : // if (openParenthesisPositionCount > 0) { // if (openParenthesisPositionCount == 1 // && lastOpenParenthesisPosition < openParenthesisPosition[0]) { @@ -2363,8 +2372,8 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // openParenthesisPositionCount--; // } // break; - // case TokenNameLBRACE : - // case TokenNameLPAREN : + // case TokenName.LBRACE : + // case TokenName.LPAREN : // if (openParenthesisPositionCount == openParenthesisPosition.length) { // System // .arraycopy( @@ -2376,17 +2385,17 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // } // openParenthesisPosition[openParenthesisPositionCount++] = // splitScanner.currentPosition; - // if (currentToken == TokenNameLPAREN - // && previousToken == TokenNameRPAREN) { + // if (currentToken == TokenName.LPAREN + // && previousToken == TokenName.RPAREN) { // openParenthesisPosition[openParenthesisPositionCount - 1] = // splitScanner.startPosition; // } // break; - // case TokenNameSEMICOLON : + // case TokenName.SEMICOLON : // // ; - // case TokenNameCOMMA : + // case TokenName.COMMA : // // , - // case TokenNameEQUAL : + // case TokenName.EQUAL : // // = // if (openParenthesisPositionCount < splitTokenDepth // || (openParenthesisPositionCount == splitTokenDepth && @@ -2425,8 +2434,8 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // } else { // if ((openParenthesisPositionCount == splitTokenDepth && // splitTokenPriority == getTokenPriority(currentToken)) - // && splitTokenType != TokenNameEQUAL - // && currentToken != TokenNameEQUAL) { + // && splitTokenType != TokenName.EQUAL + // && currentToken != TokenName.EQUAL) { // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after // // split // // take only the 1st = into account. @@ -2460,93 +2469,93 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // } // } // break; - // case TokenNameCOLON : + // case TokenName.COLON : // // : (15.24) // // see 1FK7C5R, we only split on a colon, when it is associated // // with a question-mark. // // indeed it might appear also behind a case statement, and we do // // not to break at this point. // if ((splitOperatorsCount == 0) - // || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) { + // || splitOperators[splitOperatorsCount - 1] != TokenName.QUESTION) { // break; // } - // case TokenNameextends : - // case TokenNameimplements : - // //case TokenNamethrows : - // case TokenNameDOT : + // case TokenName.extends : + // case TokenName.implements : + // //case TokenName.throws : + // case TokenName.DOT : // // . - // case TokenNameMULTIPLY : + // case TokenName.MULTIPLY : // // * (15.16.1) - // case TokenNameDIVIDE : + // case TokenName.DIVIDE : // // / (15.16.2) - // case TokenNameREMAINDER : + // case TokenName.REMAINDER : // // % (15.16.3) - // case TokenNamePLUS : + // case TokenName.PLUS : // // + (15.17, 15.17.2) - // case TokenNameMINUS : + // case TokenName.MINUS : // // - (15.17.2) - // case TokenNameLEFT_SHIFT : + // case TokenName.LEFT_SHIFT : // // << (15.18) - // case TokenNameRIGHT_SHIFT : + // case TokenName.RIGHT_SHIFT : // // >> (15.18) - // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) - // case TokenNameLESS : + // // case TokenName.UNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // case TokenName.LESS : // // < (15.19.1) - // case TokenNameLESS_EQUAL : + // case TokenName.LESS_EQUAL : // // <= (15.19.1) - // case TokenNameGREATER : + // case TokenName.GREATER : // // > (15.19.1) - // case TokenNameGREATER_EQUAL : + // case TokenName.GREATER_EQUAL : // // >= (15.19.1) - // // case TokenNameinstanceof : // instanceof - // case TokenNameEQUAL_EQUAL : + // // case TokenName.instanceof : // instanceof + // case TokenName.EQUAL_EQUAL : // // == (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameEQUAL_EQUAL_EQUAL : + // case TokenName.EQUAL_EQUAL_EQUAL : // // == (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameNOT_EQUAL : + // case TokenName.NOT_EQUAL : // // != (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameNOT_EQUAL_EQUAL : + // case TokenName.NOT_EQUAL_EQUAL : // // != (15.20, 15.20.1, 15.20.2, 15.20.3) - // case TokenNameAND : + // case TokenName.AND : // // & (15.21, 15.21.1, 15.21.2) - // case TokenNameOR : + // case TokenName.OR : // // | (15.21, 15.21.1, 15.21.2) - // case TokenNameXOR : + // case TokenName.XOR : // // ^ (15.21, 15.21.1, 15.21.2) - // case TokenNameAND_AND : + // case TokenName.AND_AND : // // && (15.22) - // case TokenNameOR_OR : + // case TokenName.OR_OR : // // || (15.23) - // case TokenNameQUESTION : + // case TokenName.QUESTION : // // ? (15.24) - // case TokenNameMULTIPLY_EQUAL : + // case TokenName.MULTIPLY_EQUAL : // // *= (15.25.2) - // case TokenNameDIVIDE_EQUAL : + // case TokenName.DIVIDE_EQUAL : // // /= (15.25.2) - // case TokenNameREMAINDER_EQUAL : + // case TokenName.REMAINDER_EQUAL : // // %= (15.25.2) - // case TokenNamePLUS_EQUAL : + // case TokenName.PLUS_EQUAL : // // += (15.25.2) - // case TokenNameMINUS_EQUAL : + // case TokenName.MINUS_EQUAL : // // -= (15.25.2) - // case TokenNameLEFT_SHIFT_EQUAL : + // case TokenName.LEFT_SHIFT_EQUAL : // // <<= (15.25.2) - // case TokenNameRIGHT_SHIFT_EQUAL : + // case TokenName.RIGHT_SHIFT_EQUAL : // // >>= (15.25.2) - // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) - // case TokenNameAND_EQUAL : + // // case TokenName.UNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // case TokenName.AND_EQUAL : // // &= (15.25.2) - // case TokenNameXOR_EQUAL : + // case TokenName.XOR_EQUAL : // // ^= (15.25.2) - // case TokenNameOR_EQUAL : + // case TokenName.OR_EQUAL : // // |= (15.25.2) // if ((openParenthesisPositionCount < splitTokenDepth || // (openParenthesisPositionCount == splitTokenDepth && // splitTokenPriority // > getTokenPriority(currentToken))) - // && !((currentToken == TokenNamePLUS || currentToken == - // TokenNameMINUS) && (previousToken == TokenNameLBRACE - // || previousToken == TokenNameLBRACKET || splitScanner.startPosition + // && !((currentToken == TokenName.PLUS || currentToken == + // TokenName.MINUS) && (previousToken == TokenName.LBRACE + // || previousToken == TokenName.LBRACKET || splitScanner.startPosition // == 0))) { // // the current token is better than the one we currently have // // (in level or in priority if same level) @@ -2631,9 +2640,9 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // if (splitOperatorsCount == 0) // return null; // // ## SPECIAL CASES BEGIN - // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT + // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenName.DOT // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1) - // || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT + // || (splitOperatorsCount > 2 && splitOperators[1] == TokenName.DOT // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && // lastOpenParenthesisPosition <= options.maxLineLength) || // (separateFirstArgumentOn(firstTokenOnLine) @@ -2651,7 +2660,7 @@ public class CodeFormatter implements ITerminalSymbols, ICodeFormatter { // SplitLine sl = split( // stringToSplit.substring(lastOpenParenthesisPosition), // lastOpenParenthesisPosition); - // if (sl == null || sl.operators[0] != TokenNameCOMMA) { + // if (sl == null || sl.operators[0] != TokenName.COMMA) { // // trim() is used to remove the extra blanks at the end of the // // substring. See PR 1FGYPI1 // return new SplitLine(new int[]{0, 0}, new String[]{ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java index 51de1a4..5a8abc3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/formatter/impl/SplitLine.java @@ -16,7 +16,7 @@ import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; * Represents a split line: contains an operator and all substrings */ public class SplitLine implements ITerminalSymbols { - public int[] operators; // the operator on which the string was split. + public TokenName[] operators; // the operator on which the string was split. public String[] substrings; @@ -49,158 +49,158 @@ public class SplitLine implements ITerminalSymbols { String operatorString = new String(); for (int i = 0, max = substrings.length; i < max; i++) { - int currentOperator = operators[i]; + TokenName currentOperator = operators[i]; String currentString = substrings[i]; - boolean placeOperatorAhead = currentOperator != TokenNameCOMMA - && currentOperator != TokenNameSEMICOLON; - boolean placeOperatorBehind = currentOperator == TokenNameCOMMA - || currentOperator == TokenNameSEMICOLON; + boolean placeOperatorAhead = currentOperator != TokenName.COMMA + && currentOperator != TokenName.SEMICOLON; + boolean placeOperatorBehind = currentOperator == TokenName.COMMA + || currentOperator == TokenName.SEMICOLON; switch (currentOperator) { - case TokenNameextends: + case EXTENDS: operatorString = "extends"; //$NON-NLS-1$ break; - // case TokenNameimplements: + // case implements: // operatorString="implements"; //$NON-NLS-1$ // break; - // case TokenNamethrows: + // case throws: // operatorString="throws"; //$NON-NLS-1$ // break; - case TokenNameSEMICOLON: // ; + case SEMICOLON: // ; operatorString = ";"; //$NON-NLS-1$ break; - case TokenNameCOMMA: // , + case COMMA: // , operatorString = ","; //$NON-NLS-1$ break; - case TokenNameEQUAL: // = + case EQUAL: // = operatorString = "="; //$NON-NLS-1$ break; - case TokenNameAND_AND: // && (15.22) + case AND_AND: // && (15.22) operatorString = "&&"; //$NON-NLS-1$ break; - case TokenNameOR_OR: // || (15.23) + case OR_OR: // || (15.23) operatorString = "||"; //$NON-NLS-1$ break; - case TokenNameQUESTION: // ? (15.24) + case QUESTION: // ? (15.24) operatorString = "?"; //$NON-NLS-1$ break; - case TokenNameCOLON: // : (15.24) + case COLON: // : (15.24) operatorString = ":"; //$NON-NLS-1$ break; - case TokenNameEQUAL_EQUAL: // == (15.20, 15.20.1, 15.20.2, 15.20.3) + case EQUAL_EQUAL: // == (15.20, 15.20.1, 15.20.2, 15.20.3) operatorString = "=="; //$NON-NLS-1$ break; - case TokenNameNOT_EQUAL: // != (15.20, 15.20.1, 15.20.2, 15.20.3) + case NOT_EQUAL: // != (15.20, 15.20.1, 15.20.2, 15.20.3) operatorString = "!="; //$NON-NLS-1$ break; - case TokenNameLESS: // < (15.19.1) + case LESS: // < (15.19.1) operatorString = "<"; //$NON-NLS-1$ break; - case TokenNameLESS_EQUAL: // <= (15.19.1) + case LESS_EQUAL: // <= (15.19.1) operatorString = "<="; //$NON-NLS-1$ break; - case TokenNameGREATER: // > (15.19.1) + case GREATER: // > (15.19.1) operatorString = ">"; //$NON-NLS-1$ break; - case TokenNameGREATER_EQUAL: // >= (15.19.1) + case GREATER_EQUAL: // >= (15.19.1) operatorString = ">="; //$NON-NLS-1$ break; - // case TokenNameinstanceof : // instanceof + // case instanceof : // instanceof // operatorString="instanceof"; //$NON-NLS-1$ // break; - case TokenNamePLUS: // + (15.17, 15.17.2) + case PLUS: // + (15.17, 15.17.2) operatorString = "+"; //$NON-NLS-1$ break; - case TokenNameMINUS: // - (15.17.2) + case MINUS: // - (15.17.2) operatorString = "-"; //$NON-NLS-1$ break; - case TokenNameMULTIPLY: // * (15.16.1) + case MULTIPLY: // * (15.16.1) operatorString = "*"; //$NON-NLS-1$ break; - case TokenNameDIVIDE: // / (15.16.2) + case DIVIDE: // / (15.16.2) operatorString = "/"; //$NON-NLS-1$ break; - case TokenNameREMAINDER: // % (15.16.3) + case REMAINDER: // % (15.16.3) operatorString = "%"; //$NON-NLS-1$ break; - case TokenNameLEFT_SHIFT: // << (15.18) + case LEFT_SHIFT: // << (15.18) operatorString = "<<"; //$NON-NLS-1$ break; - case TokenNameRIGHT_SHIFT: // >> (15.18) + case RIGHT_SHIFT: // >> (15.18) operatorString = ">>"; //$NON-NLS-1$ break; - // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18) + // case UNSIGNED_RIGHT_SHIFT : // >>> (15.18) // operatorString=">>>"; //$NON-NLS-1$ // break; - case TokenNameAND: // & (15.21, 15.21.1, 15.21.2) + case OP_AND: // & (15.21, 15.21.1, 15.21.2) operatorString = "&"; //$NON-NLS-1$ break; - case TokenNameOR: // | (15.21, 15.21.1, 15.21.2) + case OP_OR: // | (15.21, 15.21.1, 15.21.2) operatorString = "|"; //$NON-NLS-1$ break; - case TokenNameXOR: // ^ (15.21, 15.21.1, 15.21.2) + case OP_XOR: // ^ (15.21, 15.21.1, 15.21.2) operatorString = "^"; //$NON-NLS-1$ break; - case TokenNameMULTIPLY_EQUAL: // *= (15.25.2) + case MULTIPLY_EQUAL: // *= (15.25.2) operatorString = "*="; //$NON-NLS-1$ break; - case TokenNameDIVIDE_EQUAL: // /= (15.25.2) + case DIVIDE_EQUAL: // /= (15.25.2) operatorString = "/="; //$NON-NLS-1$ break; - case TokenNameREMAINDER_EQUAL: // %= (15.25.2) + case REMAINDER_EQUAL: // %= (15.25.2) operatorString = "%="; //$NON-NLS-1$ break; - case TokenNamePLUS_EQUAL: // += (15.25.2) + case PLUS_EQUAL: // += (15.25.2) operatorString = "+="; //$NON-NLS-1$ break; - case TokenNameMINUS_EQUAL: // -= (15.25.2) + case MINUS_EQUAL: // -= (15.25.2) operatorString = "-="; //$NON-NLS-1$ break; - case TokenNameLEFT_SHIFT_EQUAL: // <<= (15.25.2) + case LEFT_SHIFT_EQUAL: // <<= (15.25.2) operatorString = "<<="; //$NON-NLS-1$ break; - case TokenNameRIGHT_SHIFT_EQUAL: // >>= (15.25.2) + case RIGHT_SHIFT_EQUAL: // >>= (15.25.2) operatorString = ">>="; //$NON-NLS-1$ break; - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) + // case UNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2) // operatorString=">>>="; //$NON-NLS-1$ // break; - case TokenNameAND_EQUAL: // &= (15.25.2) + case AND_EQUAL: // &= (15.25.2) operatorString = "&="; //$NON-NLS-1$ break; - case TokenNameXOR_EQUAL: // ^= (15.25.2) + case XOR_EQUAL: // ^= (15.25.2) operatorString = "^="; //$NON-NLS-1$ break; - case TokenNameOR_EQUAL: // |= (15.25.2) + case OR_EQUAL: // |= (15.25.2) operatorString = "|="; //$NON-NLS-1$ break; - case TokenNameDOT_EQUAL: // .= + case DOT_EQUAL: // .= operatorString = ".="; //$NON-NLS-1$ break; - case TokenNameDOT: // . + case DOT: // . operatorString = "."; //$NON-NLS-1$ break; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java new file mode 100644 index 0000000..c9da1a5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java @@ -0,0 +1,762 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +/** + * Help context ids for the Java UI. + *

+ * This interface contains constants only; it is not intended to be implemented + * or extended. + *

+ * + */ +public interface IJavaHelpContextIds { + public static final String PREFIX = PHPeclipsePlugin.PLUGIN_ID + '.'; + + // Actions + public static final String GETTERSETTER_ACTION = PREFIX + + "getter_setter_action_context"; //$NON-NLS-1$ + + public static final String ADD_METHODSTUB_ACTION = PREFIX + + "add_methodstub_action_context"; //$NON-NLS-1$ + + public static final String ADD_UNIMPLEMENTED_METHODS_ACTION = PREFIX + + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ + + public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION = PREFIX + + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ + + public static final String SHOW_IN_PACKAGEVIEW_ACTION = PREFIX + + "show_in_packageview_action_context"; //$NON-NLS-1$ + + public static final String SHOW_IN_HIERARCHYVIEW_ACTION = PREFIX + + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ + + public static final String FOCUS_ON_SELECTION_ACTION = PREFIX + + "focus_on_selection_action"; //$NON-NLS-1$ + + public static final String FOCUS_ON_TYPE_ACTION = PREFIX + + "focus_on_type_action"; //$NON-NLS-1$ + + public static final String TYPEHIERARCHY_HISTORY_ACTION = PREFIX + + "typehierarchy_history_action"; //$NON-NLS-1$ + + public static final String FILTER_PUBLIC_ACTION = PREFIX + + "filter_public_action"; //$NON-NLS-1$ + + public static final String FILTER_FIELDS_ACTION = PREFIX + + "filter_fields_action"; //$NON-NLS-1$ + + public static final String FILTER_STATIC_ACTION = PREFIX + + "filter_static_action"; //$NON-NLS-1$ + + public static final String SHOW_INHERITED_ACTION = PREFIX + + "show_inherited_action"; //$NON-NLS-1$ + + public static final String SHOW_SUPERTYPES = PREFIX + + "show_supertypes_action"; //$NON-NLS-1$ + + public static final String SHOW_SUBTYPES = PREFIX + "show_subtypes_action"; //$NON-NLS-1$ + + public static final String SHOW_HIERARCHY = PREFIX + + "show_hierarchy_action"; //$NON-NLS-1$ + + public static final String ENABLE_METHODFILTER_ACTION = PREFIX + + "enable_methodfilter_action"; //$NON-NLS-1$ + + public static final String ADD_IMPORT_ON_SELECTION_ACTION = PREFIX + + "add_imports_on_selection_action_context"; //$NON-NLS-1$ + + public static final String ORGANIZE_IMPORTS_ACTION = PREFIX + + "organize_imports_action_context"; //$NON-NLS-1$ + + public static final String ADD_TO_CLASSPATH_ACTION = PREFIX + + "addjtoclasspath_action_context"; //$NON-NLS-1$ + + public static final String REMOVE_FROM_CLASSPATH_ACTION = PREFIX + + "removefromclasspath_action_context"; //$NON-NLS-1$ + + public static final String TOGGLE_PRESENTATION_ACTION = PREFIX + + "toggle_presentation_action_context"; //$NON-NLS-1$ + + public static final String TOGGLE_TEXTHOVER_ACTION = PREFIX + + "toggle_texthover_action_context"; //$NON-NLS-1$ + + public static final String OPEN_CLASS_WIZARD_ACTION = PREFIX + + "open_class_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_INTERFACE_WIZARD_ACTION = PREFIX + + "open_interface_wizard_action"; //$NON-NLS-1$ + + public static final String SORT_MEMBERS_ACTION = PREFIX + + "sort_members_action"; //$NON-NLS-1$ + + public static final String OPEN_PACKAGE_WIZARD_ACTION = PREFIX + + "open_package_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_PROJECT_WIZARD_ACTION = PREFIX + + "open_project_wizard_action"; //$NON-NLS-1$ + + public static final String OPEN_SNIPPET_WIZARD_ACTION = PREFIX + + "open_snippet_wizard_action"; //$NON-NLS-1$ + + public static final String EDIT_WORKING_SET_ACTION = PREFIX + + "edit_working_set_action"; //$NON-NLS-1$ + + public static final String CLEAR_WORKING_SET_ACTION = PREFIX + + "clear_working_set_action"; //$NON-NLS-1$ + + public static final String GOTO_MARKER_ACTION = PREFIX + + "goto_marker_action"; //$NON-NLS-1$ + + public static final String GOTO_PACKAGE_ACTION = PREFIX + + "goto_package_action"; //$NON-NLS-1$ + + public static final String GOTO_TYPE_ACTION = PREFIX + "goto_type_action"; //$NON-NLS-1$ + + public static final String GOTO_MATCHING_BRACKET_ACTION = PREFIX + + "goto_matching_bracket_action"; //$NON-NLS-1$ + + public static final String GOTO_NEXT_MEMBER_ACTION = PREFIX + + "goto_next_member_action"; //$NON-NLS-1$ + + public static final String GOTO_PREVIOUS_MEMBER_ACTION = PREFIX + + "goto_previous_member_action"; //$NON-NLS-1$ + + public static final String HISTORY_ACTION = PREFIX + "history_action"; //$NON-NLS-1$ + + public static final String HISTORY_LIST_ACTION = PREFIX + + "history_list_action"; //$NON-NLS-1$ + + public static final String LEXICAL_SORTING_OUTLINE_ACTION = PREFIX + + "lexical_sorting_outline_action"; //$NON-NLS-1$ + + public static final String LEXICAL_SORTING_BROWSING_ACTION = PREFIX + + "lexical_sorting_browsing_action"; //$NON-NLS-1$ + + public static final String OPEN_JAVA_PERSPECTIVE_ACTION = PREFIX + + "open_java_perspective_action"; //$NON-NLS-1$ + + public static final String ADD_DELEGATE_METHODS_ACTION = PREFIX + + "add_delegate_methods_action"; //$NON-NLS-1$ + + public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION = PREFIX + + "open_java_browsing_perspective_action"; //$NON-NLS-1$ + + public static final String OPEN_PROJECT_ACTION = PREFIX + + "open_project_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_ACTION = PREFIX + "open_type_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_IN_HIERARCHY_ACTION = PREFIX + + "open_type_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String ADD_JAVADOC_STUB_ACTION = PREFIX + + "add_javadoc_stub_action"; //$NON-NLS-1$ + + public static final String ADD_TASK_ACTION = PREFIX + "add_task_action"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_STRINGS_ACTION = PREFIX + + "externalize_strings_action"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_ACTION = PREFIX + + "extract_method_action"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_ACTION = PREFIX + + "extract_temp_action"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_ACTION = PREFIX + + "promote_temp_to_field_action"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION = PREFIX + + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_ACTION = PREFIX + + "extract_constant_action"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_ACTION = PREFIX + + "extract_interface_action"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_ACTION = PREFIX + + "move_inner_to_top_level_action"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_ACTION = PREFIX + + "use_supertype_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION = PREFIX + + "find_declarations_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION = PREFIX + + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION = PREFIX + + "find_declarations_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION = PREFIX + + "find_implementors_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION = PREFIX + + "find_implementors_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_read_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_read_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION = PREFIX + + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION = PREFIX + + "find_write_references_in_working_set_action"; //$NON-NLS-1$ + + public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION = PREFIX + + "find_write_references_in_workspace_action"; //$NON-NLS-1$ + + public static final String FIND_OCCURRENCES_IN_FILE_ACTION = PREFIX + + "find_occurrences_in_file_action"; //$NON-NLS-1$ + + public static final String WORKING_SET_FIND_ACTION = PREFIX + + "working_set_find_action"; //$NON-NLS-1$ + + public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION = PREFIX + + "find_strings_to_externalize_action"; //$NON-NLS-1$ + + public static final String INLINE_ACTION = PREFIX + "inline_action"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_ACTION = PREFIX + + "modify_parameters_action"; //$NON-NLS-1$ + + public static final String MOVE_ACTION = PREFIX + "move_action"; //$NON-NLS-1$ + + public static final String OPEN_ACTION = PREFIX + "open_action"; //$NON-NLS-1$ + + public static final String OPEN_EXTERNAL_JAVADOC_ACTION = PREFIX + + "open_external_javadoc_action"; //$NON-NLS-1$ + + public static final String OPEN_SUPER_IMPLEMENTATION_ACTION = PREFIX + + "open_super_implementation_action"; //$NON-NLS-1$ + + public static final String PULL_UP_ACTION = PREFIX + "pull_up_action"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_ACTION = PREFIX + "push_down_action"; //$NON-NLS-1$ + + public static final String REFRESH_ACTION = PREFIX + "refresh_action"; //$NON-NLS-1$ + + public static final String RENAME_ACTION = PREFIX + "rename_action"; //$NON-NLS-1$ + + public static final String SELF_ENCAPSULATE_ACTION = PREFIX + + "self_encapsulate_action"; //$NON-NLS-1$ + + public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION = PREFIX + + "show_in_navigator_action"; //$NON-NLS-1$ + + public static final String SURROUND_WITH_TRY_CATCH_ACTION = PREFIX + + "surround_with_try_catch_action"; //$NON-NLS-1$ + + public static final String OPEN_RESOURCE_ACTION = PREFIX + + "open_resource_action"; //$NON-NLS-1$ + + public static final String SELECT_WORKING_SET_ACTION = PREFIX + + "select_working_set_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECTION_HISTORY_ACTION = PREFIX + + "structured_selection_history_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_ENCLOSING_ACTION = PREFIX + + "structured_select_enclosing_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_NEXT_ACTION = PREFIX + + "structured_select_next_action"; //$NON-NLS-1$ + + public static final String STRUCTURED_SELECT_PREVIOUS_ACTION = PREFIX + + "structured_select_previous_action"; //$NON-NLS-1$ + + public static final String TOGGLE_ORIENTATION_ACTION = PREFIX + + "toggle_orientations_action"; //$NON-NLS-1$ + + public static final String CUT_ACTION = PREFIX + "cut_action"; //$NON-NLS-1$ + + public static final String COPY_ACTION = PREFIX + "copy_action"; //$NON-NLS-1$ + + public static final String PASTE_ACTION = PREFIX + "paste_action"; //$NON-NLS-1$ + + public static final String DELETE_ACTION = PREFIX + "delete_action"; //$NON-NLS-1$ + + public static final String SELECT_ALL_ACTION = PREFIX + "select_all_action"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_HIERARCHY_ACTION = PREFIX + + "open_type_hierarchy_action"; //$NON-NLS-1$ + + public static final String COLLAPSE_ALL_ACTION = PREFIX + + "open_type_hierarchy_action"; //$NON-NLS-1$ + + public static final String GOTO_RESOURCE_ACTION = PREFIX + + "goto_resource_action"; //$NON-NLS-1$ + + public static final String LINK_EDITOR_ACTION = PREFIX + + "link_editor_action"; //$NON-NLS-1$ + + public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION = PREFIX + + "go_into_top_level_type_action"; //$NON-NLS-1$ + + public static final String COMPARE_WITH_HISTORY_ACTION = PREFIX + + "compare_with_history_action"; //$NON-NLS-1$ + + public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION = PREFIX + + "replace_with_previous_from_history_action"; //$NON-NLS-1$ + + public static final String REPLACE_WITH_HISTORY_ACTION = PREFIX + + "replace_with_history_action"; //$NON-NLS-1$ + + public static final String ADD_FROM_HISTORY_ACTION = PREFIX + + "add_from_history_action"; //$NON-NLS-1$ + + public static final String LAYOUT_FLAT_ACTION = PREFIX + + "layout_flat_action"; //$NON-NLS-1$ + + public static final String LAYOUT_HIERARCHICAL_ACTION = PREFIX + + "layout_hierarchical_action"; //$NON-NLS-1$ + + public static final String NEXT_CHANGE_ACTION = PREFIX + + "next_change_action"; //$NON-NLS-1$ + + public static final String PREVIOUS_CHANGE_ACTION = PREFIX + + "previous_change_action"; //$NON-NLS-1$ + + public static final String NEXT_PROBLEM_ACTION = PREFIX + + "next_problem_action"; //$NON-NLS-1$ + + public static final String PREVIOUS_PROBLEM_ACTION = PREFIX + + "previous_problem_action"; //$NON-NLS-1$ + + public static final String JAVA_SELECT_MARKER_RULER_ACTION = PREFIX + + "java_select_marker_ruler_action"; //$NON-NLS-1$ + + public static final String GOTO_NEXT_ERROR_ACTION = PREFIX + + "goto_next_error_action"; //$NON-NLS-1$ + + public static final String GOTO_PREVIOUS_ERROR_ACTION = PREFIX + + "goto_previous_error_action"; //$NON-NLS-1$ + + public static final String SHOW_QUALIFIED_NAMES_ACTION = PREFIX + + "show_qualified_names_action"; //$NON-NLS-1$ + + public static final String SORT_BY_DEFINING_TYPE_ACTION = PREFIX + + "sort_by_defining_type_action"; //$NON-NLS-1$ + + public static final String FORMAT_ACTION = PREFIX + "format_action"; //$NON-NLS-1$ + + public static final String COMMENT_ACTION = PREFIX + "comment_action"; //$NON-NLS-1$ + + public static final String UNCOMMENT_ACTION = PREFIX + "uncomment_action"; //$NON-NLS-1$ + + public static final String QUICK_FIX_ACTION = PREFIX + "quick_fix_action"; //$NON-NLS-1$ + + public static final String CONTENT_ASSIST_ACTION = PREFIX + + "content_assist_action"; //$NON-NLS-1$ + + public static final String PARAMETER_HINTS_ACTION = PREFIX + + "parameter_hints_action"; //$NON-NLS-1$ + + public static final String SHOW_JAVADOC_ACTION = PREFIX + + "show_javadoc_action"; //$NON-NLS-1$ + + public static final String SHOW_OUTLINE_ACTION = PREFIX + + "show_outline_action"; //$NON-NLS-1$ + + public static final String OPEN_STRUCTURE_ACTION = PREFIX + + "open_structure_action"; //$NON-NLS-1$ + + // Dialogs + public static final String MAINTYPE_SELECTION_DIALOG = PREFIX + + "maintype_selection_dialog_context"; //$NON-NLS-1$ + + public static final String OPEN_TYPE_DIALOG = PREFIX + + "open_type_dialog_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_DIALOG = PREFIX + + "source_attachment_dialog_context"; //$NON-NLS-1$ + + public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG = PREFIX + + "advanced_dialog_context"; //$NON-NLS-1$ + + public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG = PREFIX + + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ + + public static final String NEW_VARIABLE_ENTRY_DIALOG = PREFIX + + "new_variable_dialog_context"; //$NON-NLS-1$ + + public static final String NONNLS_DIALOG = PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ + + public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG = PREFIX + + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ + + public static final String MULTI_TYPE_SELECTION_DIALOG = PREFIX + + "multi_type_selection_dialog_context"; //$NON-NLS-1$ + + public static final String SUPER_INTERFACE_SELECTION_DIALOG = PREFIX + + "super_interface_selection_dialog_context"; //$NON-NLS-1$ + + public static final String OVERRIDE_TREE_SELECTION_DIALOG = PREFIX + + "override_tree_selection_dialog_context"; //$NON-NLS-1$ + + public static final String MOVE_DESTINATION_DIALOG = PREFIX + + "move_destination_dialog_context"; //$NON-NLS-1$ + + public static final String CHOOSE_VARIABLE_DIALOG = PREFIX + + "choose_variable_dialog_context"; //$NON-NLS-1$ + + public static final String EDIT_TEMPLATE_DIALOG = PREFIX + + "edit_template_dialog_context"; //$NON-NLS-1$ + + public static final String HISTORY_LIST_DIALOG = PREFIX + + "history_list_dialog_context"; //$NON-NLS-1$ + + public static final String IMPORT_ORGANIZE_INPUT_DIALOG = PREFIX + + "import_organize_input_dialog_context"; //$NON-NLS-1$ + + public static final String TODO_TASK_INPUT_DIALOG = PREFIX + + "todo_task_input_dialog_context"; //$NON-NLS-1$ + + public static final String JAVADOC_PROPERTY_DIALOG = PREFIX + + "javadoc_property_dialog_context"; //$NON-NLS-1$ + + public static final String NEW_CONTAINER_DIALOG = PREFIX + + "new_container_dialog_context"; //$NON-NLS-1$ + + public static final String EXCLUSION_PATTERN_DIALOG = PREFIX + + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ + + public static final String OUTPUT_LOCATION_DIALOG = PREFIX + + "output_location_dialog_context"; //$NON-NLS-1$ + + public static final String VARIABLE_CREATION_DIALOG = PREFIX + + "variable_creation_dialog_context"; //$NON-NLS-1$ + + public static final String JAVA_SEARCH_PAGE = PREFIX + + "java_search_page_context"; //$NON-NLS-1$ + + public static final String NLS_SEARCH_PAGE = PREFIX + + "nls_search_page_context"; //$NON-NLS-1$ + + public static final String JAVA_EDITOR = PREFIX + "java_editor_context"; //$NON-NLS-1$ + + public static final String GOTO_RESOURCE_DIALOG = PREFIX + + "goto_resource_dialog"; //$NON-NLS-1$ + + public static final String COMPARE_DIALOG = PREFIX + + "compare_dialog_context"; //$NON-NLS-1$ + + public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG = PREFIX + + "add_element_from_history_dialog_context"; //$NON-NLS-1$ + + public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ + + public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG = PREFIX + + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ + + // view parts + public static final String TYPE_HIERARCHY_VIEW = PREFIX + + "type_hierarchy_view_context"; //$NON-NLS-1$ + + public static final String PACKAGES_VIEW = PREFIX + "package_view_context"; //$NON-NLS-1$ + + public static final String PROJECTS_VIEW = PREFIX + "projects_view_context"; //$NON-NLS-1$ + + public static final String PACKAGES_BROWSING_VIEW = PREFIX + + "packages_browsing_view_context"; //$NON-NLS-1$ + + public static final String TYPES_VIEW = PREFIX + "types_view_context"; //$NON-NLS-1$ + + public static final String MEMBERS_VIEW = PREFIX + "members_view_context"; //$NON-NLS-1$ + + // Preference/Property pages + public static final String APPEARANCE_PREFERENCE_PAGE = PREFIX + + "appearance_preference_page_context"; //$NON-NLS-1$ + + public static final String SORT_ORDER_PREFERENCE_PAGE = PREFIX + + "sort_order_preference_page_context"; //$NON-NLS-1$ + + public static final String BUILD_PATH_PROPERTY_PAGE = PREFIX + + "build_path_property_page_context"; //$NON-NLS-1$ + + public static final String CP_VARIABLES_PREFERENCE_PAGE = PREFIX + + "cp_variables_preference_page_context"; //$NON-NLS-1$ + + public static final String CODEFORMATTER_PREFERENCE_PAGE = PREFIX + + "codeformatter_preference_page_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE = PREFIX + + "source_attachment_property_page_context"; //$NON-NLS-1$ + + public static final String COMPILER_PROPERTY_PAGE = PREFIX + + "compiler_property_page_context"; //$NON-NLS-1$ + + public static final String TODOTASK_PROPERTY_PAGE = PREFIX + + "tasktags_property_page_context"; //$NON-NLS-1$ + + public static final String CODE_MANIPULATION_PREFERENCE_PAGE = PREFIX + + "code_manipulation_preference_context"; //$NON-NLS-1$ + + public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE = PREFIX + + "organizeimports_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_BASE_PREFERENCE_PAGE = PREFIX + + "java_base_preference_page_context"; //$NON-NLS-1$ + + public static final String REFACTORING_PREFERENCE_PAGE = PREFIX + + "refactoring_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_EDITOR_PREFERENCE_PAGE = PREFIX + + "java_editor_preference_page_context"; //$NON-NLS-1$ + + public static final String COMPILER_PREFERENCE_PAGE = PREFIX + + "compiler_preference_page_context"; //$NON-NLS-1$ + + public static final String TODOTASK_PREFERENCE_PAGE = PREFIX + + "tasktags_preference_page_context"; //$NON-NLS-1$ + + public static final String TEMPLATE_PREFERENCE_PAGE = PREFIX + + "template_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_PREFERENCE_PAGE = PREFIX + + "javadoc_preference_page_context"; //$NON-NLS-1$ + + public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE = PREFIX + + "new_java_project_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE = PREFIX + + "new_java_project_preference_page_context"; //$NON-NLS-1$ + + public static final String JAVA_ELEMENT_INFO_PAGE = PREFIX + + "java_element_info_page_context"; //$NON-NLS-1$ + + // Wizard pages + public static final String NEW_JAVAPROJECT_WIZARD_PAGE = PREFIX + + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_SNIPPET_WIZARD_PAGE = PREFIX + + "new_snippet_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_PACKAGE_WIZARD_PAGE = PREFIX + + "new_package_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_CLASS_WIZARD_PAGE = PREFIX + + "new_class_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_INTERFACE_WIZARD_PAGE = PREFIX + + "new_interface_wizard_page_context"; //$NON-NLS-1$ + + public static final String NEW_PACKAGEROOT_WIZARD_PAGE = PREFIX + + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ + + public static final String JARPACKAGER_WIZARD_PAGE = PREFIX + + "jar_packager_wizard_page_context"; //$NON-NLS-1$ + + public static final String JARMANIFEST_WIZARD_PAGE = PREFIX + + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ + + public static final String JAROPTIONS_WIZARD_PAGE = PREFIX + + "jar_options_wizard_page_context"; //$NON-NLS-1$ + + public static final String JAVA_WORKING_SET_PAGE = PREFIX + + "java_working_set_page_context"; //$NON-NLS-1$ + + public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE = PREFIX + + "classpath_container_default_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_STANDARD_PAGE = PREFIX + + "javadoc_standard_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_SPECIFICS_PAGE = PREFIX + + "javadoc_specifics_page_context"; //$NON-NLS-1$ + + public static final String JAVADOC_TREE_PAGE = PREFIX + + "javadoc_tree_page_context"; //$NON-NLS-1$ + + // same help for all refactoring preview pages + public static final String REFACTORING_PREVIEW_WIZARD_PAGE = PREFIX + + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_CU_ERROR_WIZARD_PAGE = PREFIX + + "move_cu_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PARAMS_WIZARD_PAGE = PREFIX + + "rename_params_wizard_page"; //$NON-NLS-1$ + + public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE = PREFIX + + "rename_params_error_wizard_page"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE = PREFIX + + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE = PREFIX + + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ + + public static final String EXTERNALIZE_ERROR_WIZARD_PAGE = PREFIX + + "externalize_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_WIZARD_PAGE = PREFIX + + "extract_interface_temp_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE = PREFIX + + "extract_interface_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_WIZARD_PAGE = PREFIX + + "extract_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "extract_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_WIZARD_PAGE = PREFIX + + "extract_temp_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_WIZARD_PAGE = PREFIX + + "extract_constant_page_context"; //$NON-NLS-1$ + + public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE = PREFIX + + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE = PREFIX + + "promote_temp_to_field_page_context"; //$NON-NLS-1$ + + public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE = PREFIX + + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE = PREFIX + + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ + + public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE = PREFIX + + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_WIZARD_PAGE = PREFIX + + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ + + public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE = PREFIX + + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_MEMBERS_WIZARD_PAGE = PREFIX + + "move_members_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE = PREFIX + + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE = PREFIX + + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ + + public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE = PREFIX + + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PULL_UP_WIZARD_PAGE = PREFIX + + "pull_up_wizard_page_context"; //$NON-NLS-1$ + + public static final String PULL_UP_ERROR_WIZARD_PAGE = PREFIX + + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_WIZARD_PAGE = PREFIX + + "push_down_wizard_page_context"; //$NON-NLS-1$ + + public static final String PUSH_DOWN_ERROR_WIZARD_PAGE = PREFIX + + "push_down_error_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PACKAGE_WIZARD_PAGE = PREFIX + + "rename_package_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE = PREFIX + + "rename_package_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TEMP_WIZARD_PAGE = PREFIX + + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_CU_WIZARD_PAGE = PREFIX + + "rename_cu_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_CU_ERROR_WIZARD_PAGE = PREFIX + + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_METHOD_WIZARD_PAGE = PREFIX + + "rename_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "rename_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TYPE_WIZARD_PAGE = PREFIX + + "rename_type_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_TYPE_ERROR_WIZARD_PAGE = PREFIX + + "rename_type_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_FIELD_WIZARD_PAGE = PREFIX + + "rename_field_wizard_page_context"; //$NON-NLS-1$ + + public static final String RENAME_FIELD_ERROR_WIZARD_PAGE = PREFIX + + "rename_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String SEF_WIZARD_PAGE = PREFIX + + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ + + public static final String SEF_ERROR_WIZARD_PAGE = PREFIX + + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_WIZARD_PAGE = PREFIX + + "use_supertype_wizard_page_context"; //$NON-NLS-1$ + + public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE = PREFIX + + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_METHOD_WIZARD_PAGE = PREFIX + + "inline_method_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_METHOD_ERROR_WIZARD_PAGE = PREFIX + + "inline_method_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_CONSTANT_WIZARD_PAGE = PREFIX + + "inline_constant_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_CONSTANT_ERROR_WIZARD_PAGE = PREFIX + + "inline_constant_error_wizard_page_context"; //$NON-NLS-1$ + + public static final String INLINE_TEMP_ERROR_WIZARD_PAGE = PREFIX + + "inline_temp_error_wizard_page_context"; //$NON-NLS-1$ + + // reused ui-blocks + public static final String BUILD_PATH_BLOCK = PREFIX + + "build_paths_context"; //$NON-NLS-1$ + + public static final String SOURCE_ATTACHMENT_BLOCK = PREFIX + + "source_attachment_context"; //$NON-NLS-1$ + + // Custom Filters + public static final String CUSTOM_FILTERS_DIALOG = PREFIX + + "open_custom_filters_dialog_context"; //$NON-NLS-1$ +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaStatusConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementAdapterFactory.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/JavaElementProperties.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIException.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java new file mode 100644 index 0000000..b4095fd --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java @@ -0,0 +1,923 @@ +package net.sourceforge.phpdt.internal.ui; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.resource.ImageRegistry; +import org.eclipse.swt.graphics.Image; + +public class PHPUiImages { + + protected static final String NAME_PREFIX = "net.sourceforge.phpdt.internal.ui."; + + protected static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); + + protected static URL fgIconBaseURL = null; + + // static { + // String pathSuffix = "icons/"; + // try { + // fgIconBaseURL = + // new URL( + // PHPeclipsePlugin + // .getDefault() + // .getDescriptor() + // .getInstallURL(), + // pathSuffix); + // } catch (MalformedURLException e) { + // PHPeclipsePlugin.log(e); + // } + // } + + // Determine display depth. If depth > 4 then we use high color images. + // Otherwise low color + // images are used + static { + fgIconBaseURL = PHPeclipsePlugin.getDefault().getBundle().getEntry( + "/icons/"); //$NON-NLS-1$ + } + + private static ImageRegistry fgImageRegistry = null; + + private static HashMap fgAvoidSWTErrorMap = null; + + protected static final String OBJ_PREFIX = "obj16"; + + protected static final String OVR_PREFIX = "ovr16"; + + protected static final String CTOOL_PREFIX = "ctool16"; + + public static final String IMG_CLASS = NAME_PREFIX + + "class_default_obj.gif"; + + public static final String IMG_DEFINE = NAME_PREFIX + "define_obj.gif"; + + public static final String IMG_BUILTIN = NAME_PREFIX + "builtin_obj.gif"; + + public static final String IMG_FUN = NAME_PREFIX + "fun_obj.gif"; + + public static final String IMG_INC = NAME_PREFIX + "impc_obj.gif"; + + public static final String IMG_VAR = NAME_PREFIX + "var_obj.gif"; + + public static final String IMG_TABLE = NAME_PREFIX + "table_obj.gif"; + + public static final String IMG_COLUMN = NAME_PREFIX + "column_obj.gif"; + + public static final String IMG_OBJS_WARNING = NAME_PREFIX + + "warning_obj.gif"; + + public static final String IMG_OBJS_INFO = NAME_PREFIX + "info_obj.gif"; + + public static final String IMG_CTOOLS_PHP_PAGE = NAME_PREFIX + + "php_page.gif"; + + public static final String IMG_CTOOLS_PHP = NAME_PREFIX + "php.gif"; + + public static final String IMG_CLEAR = NAME_PREFIX + "clear.gif"; + + public static final ImageDescriptor DESC_CLASS = createManaged(OBJ_PREFIX, + IMG_CLASS); + + public static final ImageDescriptor DESC_DEFINE = createManaged(OBJ_PREFIX, + IMG_DEFINE); + + public static final ImageDescriptor DESC_BUILTIN = createManaged( + OBJ_PREFIX, IMG_BUILTIN); + + public static final ImageDescriptor DESC_FUN = createManaged(OBJ_PREFIX, + IMG_FUN); + + public static final ImageDescriptor DESC_INC = createManaged(OBJ_PREFIX, + IMG_INC); + + public static final ImageDescriptor DESC_VAR = createManaged(OBJ_PREFIX, + IMG_VAR); + + public static final ImageDescriptor DESC_TABLE = createManaged(OBJ_PREFIX, + IMG_TABLE); + + public static final ImageDescriptor DESC_COLUMN = createManaged(OBJ_PREFIX, + IMG_COLUMN); + + public static final ImageDescriptor DESC_OBJS_WARNING = createManaged( + OBJ_PREFIX, IMG_OBJS_WARNING); + + public static final ImageDescriptor DESC_OBJS_INFO = createManaged( + OBJ_PREFIX, IMG_OBJS_INFO); + + public static final ImageDescriptor DESC_CTOOL_PHP_PAGE = createManaged( + CTOOL_PREFIX, IMG_CTOOLS_PHP_PAGE); + + public static final ImageDescriptor DESC_CTOOL_PHP = createManaged( + CTOOL_PREFIX, IMG_CTOOLS_PHP); + + public static final ImageDescriptor DESC_CLEAR = createManaged(OBJ_PREFIX, + IMG_CLEAR); + + /* + * Set of predefined Image Descriptors. + */ + private static final String T_OBJ = "obj16"; //$NON-NLS-1$ + + private static final String T_OVR = "ovr16"; //$NON-NLS-1$ + + private static final String T_WIZBAN = "wizban"; //$NON-NLS-1$ + + private static final String T_CLCL = "clcl16"; //$NON-NLS-1$ + + private static final String T_DLCL = "dlcl16"; //$NON-NLS-1$ + + private static final String T_ELCL = "elcl16"; //$NON-NLS-1$ + + private static final String T_CTOOL = "ctool16"; //$NON-NLS-1$ + + private static final String T_CVIEW = "cview16"; //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWCLASS = create(T_WIZBAN, + "newclass_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_ELCL_FILTER = create(T_ELCL, + "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_DLCL_FILTER = create(T_DLCL, + "filter_ps.gif"); //$NON-NLS-1$ + + /* + * Available cached Images in the Java plugin image registry. + */ + public static final String IMG_MISC_PUBLIC = NAME_PREFIX + + "methpub_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_PROTECTED = NAME_PREFIX + + "methpro_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_PRIVATE = NAME_PREFIX + + "methpri_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_MISC_DEFAULT = NAME_PREFIX + + "methdef_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PUBLIC = NAME_PREFIX + + "field_public_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PROTECTED = NAME_PREFIX + + "field_protected_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_PRIVATE = NAME_PREFIX + + "field_private_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_FIELD_DEFAULT = NAME_PREFIX + + "field_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_GHOST = NAME_PREFIX + "ghost.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_TSK = NAME_PREFIX + + "search_tsk.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_PACKDECL = NAME_PREFIX + + "packd_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_IMPDECL = NAME_PREFIX + "imp_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_IMPCONT = NAME_PREFIX + "impc_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JSEARCH = NAME_PREFIX + + "jsearch_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_DECL = NAME_PREFIX + + "search_decl_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_REF = NAME_PREFIX + + "search_ref_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASS = NAME_PREFIX + "class_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASSALT = NAME_PREFIX + + "classfo_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CLASS_DEFAULT = NAME_PREFIX + + "class_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACE = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACEALT = NAME_PREFIX + + "intf_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_INTERFACE_DEFAULT = NAME_PREFIX + + "int_default_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CUNIT = NAME_PREFIX + "phpedit.png"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CUNIT_RESOURCE = NAME_PREFIX + + "jcu_resource_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILE = NAME_PREFIX + "classf_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILECLASS = NAME_PREFIX + + "class_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_CFILEINT = NAME_PREFIX + "int_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_LOGICAL_PACKAGE = NAME_PREFIX + + "logical_package_obj.gif";//$NON-NLS-1$ + + public static final String IMG_OJS_EMPTY_LOGICAL_PACKAGE = NAME_PREFIX + + "empty_logical_package_obj.gif";//$NON-NLS-1$ + + public static final String IMG_OBJS_PACKAGE = NAME_PREFIX + + "package_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EMPTY_PACK_RESOURCE = NAME_PREFIX + + "empty_pack_fldr_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EMPTY_PACKAGE = NAME_PREFIX + + "empty_pack_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_PACKFRAG_ROOT = NAME_PREFIX + + "packagefolder_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_PACKFRAG_ROOT = NAME_PREFIX + + "packagefolder_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_JAR = NAME_PREFIX + + "jar_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAR = NAME_PREFIX + "jar_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXTJAR = NAME_PREFIX + "jar_l_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAR_WSRC = NAME_PREFIX + + "jar_src_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXTJAR_WSRC = NAME_PREFIX + + "jar_lsrc_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_ENV_VAR = NAME_PREFIX + + "envvar_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_MISSING_ENV_VAR = NAME_PREFIX + + "envvar_nonexist_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAVA_MODEL = NAME_PREFIX + + "java_model_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_UNKNOWN = NAME_PREFIX + + "unknown_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_LIBRARY = NAME_PREFIX + + "library_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_JAVADOCTAG = NAME_PREFIX + + "jdoc_tag_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_HTMLTAG = NAME_PREFIX + + "html_tag_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_TEMPLATE = NAME_PREFIX + + "template_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_EXCEPTION = NAME_PREFIX + + "jexception_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_ERROR = NAME_PREFIX + + "jrtexception_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_BREAKPOINT_INSTALLED = NAME_PREFIX + + "brkpi_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_FIXABLE_PROBLEM = NAME_PREFIX + + "quickfix_warning_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_FIXABLE_ERROR = NAME_PREFIX + + "quickfix_error_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SNIPPET_EVALUATING = NAME_PREFIX + + "jsbook_run_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_FATAL = NAME_PREFIX + + "fatalerror_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_ERROR = NAME_PREFIX + + "error_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_WARNING = NAME_PREFIX + + "warning_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_REFACTORING_INFO = NAME_PREFIX + + "info_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_TRANSLATE = NAME_PREFIX + + "translate.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_NEVER_TRANSLATE = NAME_PREFIX + + "never_translate.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_NLS_SKIP = NAME_PREFIX + "skip.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_READACCESS = NAME_PREFIX + + "occ_read.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_WRITEACCESS = NAME_PREFIX + + "occ_write.gif"; //$NON-NLS-1$ + + public static final String IMG_OBJS_SEARCH_OCCURRENCE = NAME_PREFIX + + "occ_match.gif"; //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_ERRORWARNING_TAB = create( + T_CVIEW, "errorwarning_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_CLASSFILEGENERATION_TAB = create( + T_CVIEW, "classfilegeneration_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_VIEW_JDKCOMPLIANCE_TAB = create( + T_CVIEW, "jdkcompliance_tab.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLCL_FILTER = create(T_CLCL, + "filter_ps.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_CLCL_CODE_ASSIST = create(T_CLCL, + "metharg_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_DLCL_CODE_ASSIST = create(T_DLCL, + "metharg_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MISC_PUBLIC = createManaged(T_OBJ, + IMG_MISC_PUBLIC); + + public static final ImageDescriptor DESC_MISC_PROTECTED = createManaged( + T_OBJ, IMG_MISC_PROTECTED); + + public static final ImageDescriptor DESC_MISC_PRIVATE = createManaged( + T_OBJ, IMG_MISC_PRIVATE); + + public static final ImageDescriptor DESC_MISC_DEFAULT = createManaged( + T_OBJ, IMG_MISC_DEFAULT); + + public static final ImageDescriptor DESC_FIELD_PUBLIC = createManaged( + T_OBJ, IMG_FIELD_PUBLIC); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_PROTECTED = createManaged( + T_OBJ, IMG_FIELD_PROTECTED); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_PRIVATE = createManaged( + T_OBJ, IMG_FIELD_PRIVATE); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_FIELD_DEFAULT = createManaged( + T_OBJ, IMG_FIELD_DEFAULT); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MENU_SHIFT_RIGHT = create(T_CTOOL, + "shift_r_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_MENU_SHIFT_LEFT = create(T_CTOOL, + "shift_l_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_GHOST = createManaged(T_OBJ, + IMG_OBJS_GHOST); + + public static final ImageDescriptor DESC_OBJS_PACKDECL = createManaged( + T_OBJ, IMG_OBJS_PACKDECL); + + public static final ImageDescriptor DESC_OBJS_IMPDECL = createManaged( + T_OBJ, IMG_OBJS_IMPDECL); + + public static final ImageDescriptor DESC_OBJS_IMPCONT = createManaged( + T_OBJ, IMG_OBJS_IMPCONT); + + public static final ImageDescriptor DESC_OBJS_JSEARCH = createManaged( + T_OBJ, IMG_OBJS_JSEARCH); + + public static final ImageDescriptor DESC_OBJS_SEARCH_DECL = createManaged( + T_OBJ, IMG_OBJS_SEARCH_DECL); + + public static final ImageDescriptor DESC_OBJS_SEARCH_REF = createManaged( + T_OBJ, IMG_OBJS_SEARCH_REF); + + public static final ImageDescriptor DESC_OBJS_CUNIT = createManaged(T_OBJ, + IMG_OBJS_CUNIT); + + public static final ImageDescriptor DESC_OBJS_CUNIT_RESOURCE = createManaged( + T_OBJ, IMG_OBJS_CUNIT_RESOURCE); + + public static final ImageDescriptor DESC_OBJS_CFILE = createManaged(T_OBJ, + IMG_OBJS_CFILE); + + public static final ImageDescriptor DESC_OBJS_CFILECLASS = createManaged( + T_OBJ, IMG_OBJS_CFILECLASS); + + public static final ImageDescriptor DESC_OBJS_CFILEINT = createManaged( + T_OBJ, IMG_OBJS_CFILEINT); + + public static final ImageDescriptor DESC_OBJS_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_LOGICAL_PACKAGE = createManaged( + T_OBJ, IMG_OJS_EMPTY_LOGICAL_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_LOGICAL_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_LOGICAL_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE_RESOURCES = createManaged( + T_OBJ, IMG_OBJS_EMPTY_PACK_RESOURCE); + + public static final ImageDescriptor DESC_OBJS_EMPTY_PACKAGE = createManaged( + T_OBJ, IMG_OBJS_EMPTY_PACKAGE); + + public static final ImageDescriptor DESC_OBJS_PACKFRAG_ROOT = createManaged( + T_OBJ, IMG_OBJS_PACKFRAG_ROOT); + + public static final ImageDescriptor DESC_OBJS_MISSING_PACKFRAG_ROOT = createManaged( + T_OBJ, IMG_OBJS_MISSING_PACKFRAG_ROOT); + + public static final ImageDescriptor DESC_OBJS_JAVA_MODEL = createManaged( + T_OBJ, IMG_OBJS_JAVA_MODEL); + + public static final ImageDescriptor DESC_OBJS_CLASS = createManaged(T_OBJ, + IMG_OBJS_CLASS); + + public static final ImageDescriptor DESC_OBJS_CLASS_DEFAULT = createManaged( + T_OBJ, IMG_OBJS_CLASS_DEFAULT); + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PUBLIC = create( + T_OBJ, "innerclass_public_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_DEFAULT = create( + T_OBJ, "innerclass_default_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PROTECTED = create( + T_OBJ, "innerclass_protected_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_CLASS_PRIVATE = create( + T_OBJ, "innerclass_private_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_CLASSALT = createManaged( + T_OBJ, IMG_OBJS_CLASSALT); + + public static final ImageDescriptor DESC_OBJS_INTERFACE = createManaged( + T_OBJ, IMG_OBJS_INTERFACE); + + public static final ImageDescriptor DESC_OBJS_INTERFACE_DEFAULT = createManaged( + T_OBJ, IMG_OBJS_INTERFACE_DEFAULT); + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PUBLIC = create( + T_OBJ, "innerinterface_public_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_DEFAULT = create( + T_OBJ, "innerinterface_default_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PROTECTED = create( + T_OBJ, "innerinterface_protected_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INNER_INTERFACE_PRIVATE = create( + T_OBJ, "innerinterface_private_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_INTERFACEALT = createManaged( + T_OBJ, IMG_OBJS_INTERFACEALT); + + public static final ImageDescriptor DESC_OBJS_JAR = createManaged(T_OBJ, + IMG_OBJS_JAR); + + public static final ImageDescriptor DESC_OBJS_MISSING_JAR = createManaged( + T_OBJ, IMG_OBJS_MISSING_JAR); + + public static final ImageDescriptor DESC_OBJS_EXTJAR = createManaged(T_OBJ, + IMG_OBJS_EXTJAR); + + public static final ImageDescriptor DESC_OBJS_JAR_WSRC = createManaged( + T_OBJ, IMG_OBJS_JAR_WSRC); + + public static final ImageDescriptor DESC_OBJS_EXTJAR_WSRC = createManaged( + T_OBJ, IMG_OBJS_EXTJAR_WSRC); + + public static final ImageDescriptor DESC_OBJS_ENV_VAR = createManaged( + T_OBJ, IMG_OBJS_ENV_VAR); + + public static final ImageDescriptor DESC_OBJS_MISSING_ENV_VAR = createManaged( + T_OBJ, IMG_OBJS_MISSING_ENV_VAR); + + public static final ImageDescriptor DESC_OBJS_LIBRARY = createManaged( + T_OBJ, IMG_OBJS_LIBRARY); + + public static final ImageDescriptor DESC_OBJS_JAVADOCTAG = createManaged( + T_OBJ, IMG_OBJS_JAVADOCTAG); + + public static final ImageDescriptor DESC_OBJS_HTMLTAG = createManaged( + T_OBJ, IMG_OBJS_HTMLTAG); + + public static final ImageDescriptor DESC_OBJS_TEMPLATE = createManaged( + T_OBJ, IMG_OBJS_TEMPLATE); + + public static final ImageDescriptor DESC_OBJS_EXCEPTION = createManaged( + T_OBJ, IMG_OBJS_EXCEPTION); + + public static final ImageDescriptor DESC_OBJS_BREAKPOINT_INSTALLED = createManaged( + T_OBJ, IMG_OBJS_BREAKPOINT_INSTALLED); + + public static final ImageDescriptor DESC_OBJS_ERROR = createManaged(T_OBJ, + IMG_OBJS_ERROR); + + public static final ImageDescriptor DESC_OBJS_FIXABLE_PROBLEM = createManaged( + T_OBJ, IMG_OBJS_FIXABLE_PROBLEM); + + public static final ImageDescriptor DESC_OBJS_FIXABLE_ERROR = createManaged( + T_OBJ, IMG_OBJS_FIXABLE_ERROR); + + public static final ImageDescriptor DESC_OBJS_SNIPPET_EVALUATING = createManaged( + T_OBJ, IMG_OBJS_SNIPPET_EVALUATING); + + public static final ImageDescriptor DESC_OBJS_DEFAULT_CHANGE = create( + T_OBJ, "change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_COMPOSITE_CHANGE = create( + T_OBJ, "composite_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_CU_CHANGE = create(T_OBJ, + "cu_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_FILE_CHANGE = create(T_OBJ, + "file_change.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_TEXT_EDIT = create(T_OBJ, + "text_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_EXCLUSION_FILTER_ATTRIB = create( + T_OBJ, "exclusion_filter_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_OUTPUT_FOLDER_ATTRIB = create( + T_OBJ, "output_folder_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_SOURCE_ATTACH_ATTRIB = create( + T_OBJ, "source_attach_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_JAVADOC_LOCATION_ATTRIB = create( + T_OBJ, "javadoc_location_attrib.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OBJS_REFACTORING_FATAL = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_FATAL); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_ERROR = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_ERROR); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_WARNING = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_WARNING); + + public static final ImageDescriptor DESC_OBJS_REFACTORING_INFO = createManaged( + T_OBJ, IMG_OBJS_REFACTORING_INFO); + + public static final ImageDescriptor DESC_OBJS_NLS_TRANSLATE = createManaged( + T_OBJ, IMG_OBJS_NLS_TRANSLATE); + + public static final ImageDescriptor DESC_OBJS_NLS_NEVER_TRANSLATE = createManaged( + T_OBJ, IMG_OBJS_NLS_NEVER_TRANSLATE); + + public static final ImageDescriptor DESC_OBJS_NLS_SKIP = createManaged( + T_OBJ, IMG_OBJS_NLS_SKIP); + + public static final ImageDescriptor DESC_OBJS_UNKNOWN = createManaged( + T_OBJ, IMG_OBJS_UNKNOWN); + + public static final ImageDescriptor DESC_OBJS_SEARCH_READACCESS = createManaged( + T_OBJ, IMG_OBJS_SEARCH_READACCESS); + + public static final ImageDescriptor DESC_OBJS_SEARCH_WRITEACCESS = createManaged( + T_OBJ, IMG_OBJS_SEARCH_WRITEACCESS); + + public static final ImageDescriptor DESC_OBJS_SEARCH_OCCURRENCE = createManaged( + T_OBJ, IMG_OBJS_SEARCH_OCCURRENCE); + + public static final ImageDescriptor DESC_OBJS_LOCAL_VARIABLE = create( + T_OBJ, "localvariable_obj.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_STATIC = create(T_OVR, + "static_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_FINAL = create(T_OVR, + "final_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_ABSTRACT = create(T_OVR, + "abstract_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_SYNCH = create(T_OVR, + "synch_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_RUN = create(T_OVR, + "run_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_WARNING = create(T_OVR, + "warning_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_ERROR = create(T_OVR, + "error_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_OVERRIDES = create(T_OVR, + "over_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_IMPLEMENTS = create(T_OVR, + "implm_co.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_CONSTRUCTOR = create(T_OVR, + "constr_ovr.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_OVR_FOCUS = create(T_OVR, + "focus_ovr.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWFIELD = create(T_WIZBAN, + "newfield_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWINT = create(T_WIZBAN, + "newint_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWJPRJ = create(T_WIZBAN, + "newjprj_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWSRCFOLDR = create( + T_WIZBAN, "newsrcfldr_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWMETH = create(T_WIZBAN, + "newmeth_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWPACK = create(T_WIZBAN, + "newpack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_NEWSCRAPPAGE = create( + T_WIZBAN, "newsbook_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_LAUNCH = create( + T_WIZBAN, "java_app_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_ATTACH = create( + T_WIZBAN, "java_attach_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR = create(T_WIZBAN, + "refactor_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_FIELD = create( + T_WIZBAN, "fieldrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_METHOD = create( + T_WIZBAN, "methrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_TYPE = create( + T_WIZBAN, "typerefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PACKAGE = create( + T_WIZBAN, "packrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CODE = create( + T_WIZBAN, "coderefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_CU = create( + T_WIZBAN, "compunitrefact_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_REFACTOR_PULL_UP = create( + T_WIZBAN, "pullup_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAR_PACKAGER = create( + T_WIZBAN, "jar_pack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_JAVA_WORKINGSET = create( + T_WIZBAN, "java_workingset_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_EXPORT_JAVADOC = create( + T_WIZBAN, "export_javadoc_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_EXTERNALIZE_STRINGS = create( + T_WIZBAN, "extstr_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_WIZBAN_ADD_LIBRARY = create( + T_WIZBAN, "addlibrary_wiz.gif");//$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_DISPLAYSNIPPET = create( + T_CTOOL, "disp_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_RUNSNIPPET = create(T_CTOOL, + "run_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_INSPSNIPPET = create(T_CTOOL, + "insp_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_PACKSNIPPET = create(T_CTOOL, + "pack_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_TERMSNIPPET = create(T_CTOOL, + "term_sbook.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_SHOW_EMPTY_PKG = create( + T_CTOOL, "show_empty_pkg.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_SHOW_SEGMENTS = create( + T_CTOOL, "segment_edit.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_GOTO_NEXT_ERROR = create( + T_CTOOL, "next_error_nav.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_GOTO_PREV_ERROR = create( + T_CTOOL, "prev_error_nav.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_OPENTYPE = create(T_CTOOL, + "opentype.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPROJECT = create(T_CTOOL, + "newjprj_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPACKAGE = create(T_CTOOL, + "newpack_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWCLASS = create(T_CTOOL, + "newclass_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWINTERFACE = create( + T_CTOOL, "newint_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWSNIPPET = create(T_CTOOL, + "newsbook_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_NEWPACKROOT = create(T_CTOOL, + "newpackfolder_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER = create( + T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$ + + // Keys for correction proposal. We have to put the image into the registry + // since "code assist" doesn't + // have a life cycle. So no change to dispose icons. + + public static final String IMG_CORRECTION_CHANGE = NAME_PREFIX + + "correction_change.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_MOVE = NAME_PREFIX + + "correction_move.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_RENAME = NAME_PREFIX + + "correction_rename.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_DELETE_IMPORT = NAME_PREFIX + + "correction_delete_import.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_LOCAL = NAME_PREFIX + + "localvariable_obj.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_REMOVE = NAME_PREFIX + + "remove_correction.gif"; //$NON-NLS-1$ + + public static final String IMG_CORRECTION_ADD = NAME_PREFIX + + "add_correction.gif"; //$NON-NLS-1$ + + static { + createManaged(T_OBJ, IMG_CORRECTION_CHANGE); + createManaged(T_OBJ, IMG_CORRECTION_MOVE); + createManaged(T_OBJ, IMG_CORRECTION_RENAME); + createManaged(T_OBJ, IMG_CORRECTION_DELETE_IMPORT); + createManaged(T_OBJ, IMG_CORRECTION_LOCAL); + createManaged(T_OBJ, IMG_CORRECTION_REMOVE); + createManaged(T_OBJ, IMG_CORRECTION_ADD); + } + + /** + * Returns the image managed under the given key in this registry. + * + * @param key + * the image's key + * @return the image managed under the given key + */ + public static Image get(String key) { + return getImageRegistry().get(key); + } + + /** + * Returns the image descriptor for the given key in this registry. Might be + * called in a non-UI thread. + * + * @param key + * the image's key + * @return the image descriptor for the given key + */ + public static ImageDescriptor getDescriptor(String key) { + if (fgImageRegistry == null) { + return (ImageDescriptor) fgAvoidSWTErrorMap.get(key); + } + return getImageRegistry().getDescriptor(key); + } + + /** + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *tool16 folders. + */ + public static void setToolImageDescriptors(IAction action, String iconName) { + setImageDescriptors(action, "tool16", iconName); + } + + /** + * Sets the three image descriptors for enabled, disabled, and hovered to an + * action. The actions are retrieved from the *lcl16 folders. + */ + public static void setLocalImageDescriptors(IAction action, String iconName) { + setImageDescriptors(action, "lcl16", iconName); + } + + /* + * Helper method to access the image registry from the JavaPlugin class. + */ + /* package */static ImageRegistry getImageRegistry() { + if (fgImageRegistry == null) { + fgImageRegistry = new ImageRegistry(); + for (Iterator iter = fgAvoidSWTErrorMap.keySet().iterator(); iter + .hasNext();) { + String key = (String) iter.next(); + fgImageRegistry.put(key, (ImageDescriptor) fgAvoidSWTErrorMap + .get(key)); + } + fgAvoidSWTErrorMap = null; + } + return fgImageRegistry; + } + + // ---- Helper methods to access icons on the file system + // -------------------------------------- + + protected static void setImageDescriptors(IAction action, String type, + String relPath) { + + try { + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "d" + type, relPath)); + if (id != null) + action.setDisabledImageDescriptor(id); + } catch (MalformedURLException e) { + } + + try { + ImageDescriptor id = ImageDescriptor.createFromURL(makeIconFileURL( + "c" + type, relPath)); + if (id != null) + action.setHoverImageDescriptor(id); + } catch (MalformedURLException e) { + } + + action.setImageDescriptor(create("e" + type, relPath)); + } + + private static ImageDescriptor createManaged(String prefix, String name) { + try { + ImageDescriptor result = ImageDescriptor + .createFromURL(makeIconFileURL(prefix, name + .substring(NAME_PREFIX_LENGTH))); + if (fgAvoidSWTErrorMap == null) { + fgAvoidSWTErrorMap = new HashMap(); + } + fgAvoidSWTErrorMap.put(name, result); + if (fgImageRegistry != null) { + PHPeclipsePlugin + .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ + } + return result; + } catch (MalformedURLException e) { + return ImageDescriptor.getMissingImageDescriptor(); + } + } + +// private static ImageDescriptor createManaged(String prefix, String name, +// String key) { +// try { +// ImageDescriptor result = ImageDescriptor +// .createFromURL(makeIconFileURL(prefix, name +// .substring(NAME_PREFIX_LENGTH))); +// if (fgAvoidSWTErrorMap == null) { +// fgAvoidSWTErrorMap = new HashMap(); +// } +// fgAvoidSWTErrorMap.put(key, result); +// if (fgImageRegistry != null) { +// PHPeclipsePlugin +// .logErrorMessage("Image registry already defined"); //$NON-NLS-1$ +// } +// return result; +// } catch (MalformedURLException e) { +// return ImageDescriptor.getMissingImageDescriptor(); +// } +// } + + protected static ImageDescriptor create(String prefix, String name) { + try { + return ImageDescriptor.createFromURL(makeIconFileURL(prefix, name)); + } catch (MalformedURLException e) { + return ImageDescriptor.getMissingImageDescriptor(); + } + } + + protected static URL makeIconFileURL(String prefix, String name) + throws MalformedURLException { + if (fgIconBaseURL == null) + throw new MalformedURLException(); + + StringBuffer buffer = new StringBuffer(prefix); + buffer.append('/'); + buffer.append(name); + return new URL(fgIconBaseURL, buffer.toString()); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/ResourceAdapterFactory.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java new file mode 100644 index 0000000..10a6348 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionUtil.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.actions; + +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +//import net.sourceforge.phpdt.core.IPackageFragment; +//import net.sourceforge.phpdt.core.IPackageFragmentRoot; +//import net.sourceforge.phpdt.internal.corext.refactoring.util.ResourceUtil; +//import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; + +//import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectNature; +//import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Shell; + +/* + * http://dev.eclipse.org/bugs/show_bug.cgi?id=19104 + */ +public class ActionUtil { + + private ActionUtil() { + } + + // bug 31998 we will have to disable renaming of linked packages (and cus) +// public static boolean mustDisableJavaModelAction(Shell shell, Object element) { +// if (!(element instanceof IPackageFragment) +// && !(element instanceof IPackageFragmentRoot)) +// return false; +// +// IResource resource = ResourceUtil.getResource(element); +// if ((resource == null) || (!(resource instanceof IFolder)) +// || (!resource.isLinked())) +// return false; +// +// MessageDialog +// .openInformation( +// shell, +// ActionMessages.getString("ActionUtil.not_possible"), ActionMessages.getString("ActionUtil.no_linked")); //$NON-NLS-1$ //$NON-NLS-2$ +// return true; +// } + + public static boolean isProcessable(Shell shell, PHPEditor editor) { + if (editor == null) + return true; + IJavaElement input = SelectionConverter.getInput(editor); + // if a Java editor doesn't have an input of type Java element + // then it is for sure not on the build path + if (input == null) { + MessageDialog.openInformation(shell, ActionMessages + .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ + ActionMessages + .getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ + return false; + } + return isProcessable(shell, input); + } + + public static boolean isProcessable(Shell shell, Object element) { + if (!(element instanceof IJavaElement)) + return true; + + if (isOnBuildPath((IJavaElement) element)) + return true; + MessageDialog.openInformation(shell, ActionMessages + .getString("ActionUtil.notOnBuildPath.title"), //$NON-NLS-1$ + ActionMessages.getString("ActionUtil.notOnBuildPath.message")); //$NON-NLS-1$ + return false; + } + + public static boolean isOnBuildPath(IJavaElement element) { + // fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051 + if (element.getElementType() == IJavaElement.JAVA_PROJECT) + return true; + IJavaProject project = element.getJavaProject(); + try { + // if (!project.isOnClasspath(element)) + // return false; + IProject resourceProject = project.getProject(); + if (resourceProject == null) + return false; + IProjectNature nature = resourceProject + .getNature(PHPeclipsePlugin.PHP_NATURE_ID); + // We have a Java project + if (nature != null) + return true; + } catch (CoreException e) { + } + return false; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddBlockCommentAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AddTaskAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/BlockCommentAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/CompositeActionGroup.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingActionGroup.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingExpandAllRulerAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/FoldingToggleRulerAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java new file mode 100644 index 0000000..cf03914 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/IndentAction.java @@ -0,0 +1,574 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.actions; + +import java.util.ResourceBundle; + +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; +import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; +import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager; +import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager.UndoSpec; +import net.sourceforge.phpdt.internal.ui.text.phpdoc.JavaDocAutoIndentStrategy; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.IRewriteTarget; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.swt.widgets.Display; +import org.eclipse.text.edits.MalformedTreeException; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.ITextEditorExtension3; +import org.eclipse.ui.texteditor.TextEditorAction; + +/** + * Indents a line or range of lines in a Java document to its correct position. + * No complete AST must be present, the indentation is computed using + * heuristics. The algorith used is fast for single lines, but does not store + * any information and therefore not so efficient for large line ranges. + * + * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner + * @see net.sourceforge.phpdt.internal.ui.text.JavaIndenter + * @since 3.0 + */ +public class IndentAction extends TextEditorAction { + + /** The caret offset after an indent operation. */ + private int fCaretOffset; + + /** + * Whether this is the action invoked by TAB. When true, + * indentation behaves differently to accomodate normal TAB operation. + */ + private final boolean fIsTabAction; + + /** + * Creates a new instance. + * + * @param bundle + * the resource bundle + * @param prefix + * the prefix to use for keys in bundle + * @param editor + * the text editor + * @param isTabAction + * whether the action should insert tabs if over the indentation + */ + public IndentAction (ResourceBundle bundle, + String prefix, + ITextEditor editor, + boolean isTabAction) { + super (bundle, prefix, editor); + + fIsTabAction = isTabAction; + } + + /* + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + // update has been called by the framework + if (!isEnabled() || !validateEditorInputState()) + return; + + ITextSelection selection = getSelection(); + final IDocument document = getDocument(); + + if (document != null) { + + final int offset = selection.getOffset(); + final int length = selection.getLength(); + final Position end = new Position(offset + length); + final int firstLine, nLines; + fCaretOffset = -1; + + try { + document.addPosition(end); + firstLine = document.getLineOfOffset(offset); + // check for marginal (zero-length) lines + int minusOne = length == 0 ? 0 : 1; + nLines = document.getLineOfOffset(offset + length - minusOne) + - firstLine + 1; + } catch (BadLocationException e) { + // will only happen on concurrent modification + PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$ + return; + } + + Runnable runnable = new Runnable() { + public void run() { + IRewriteTarget target = (IRewriteTarget) getTextEditor() + .getAdapter(IRewriteTarget.class); + if (target != null) { + target.beginCompoundChange(); + target.setRedraw(false); + } + + try { + JavaHeuristicScanner scanner = new JavaHeuristicScanner( + document); + JavaIndenter indenter = new JavaIndenter(document, + scanner); + boolean hasChanged = false; + for (int i = 0; i < nLines; i++) { + hasChanged |= indentLine(document, firstLine + i, + offset, indenter, scanner); + } + + // update caret position: move to new position when + // indenting just one line + // keep selection when indenting multiple + int newOffset, newLength; + if (fIsTabAction) { + newOffset = fCaretOffset; + newLength = 0; + } else if (nLines > 1) { + newOffset = offset; + newLength = end.getOffset() - offset; + } else { + newOffset = fCaretOffset; + newLength = 0; + } + + // always reset the selection if anything was replaced + // but not when we had a singleline nontab invocation + if (newOffset != -1 + && (hasChanged || newOffset != offset || newLength != length)) + selectAndReveal(newOffset, newLength); + + document.removePosition(end); + } catch (BadLocationException e) { + // will only happen on concurrent modification + PHPeclipsePlugin.log(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, + "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$ + + } finally { + + if (target != null) { + target.endCompoundChange(); + target.setRedraw(true); + } + } + } + }; + + if (nLines > 50) { + Display display = getTextEditor().getEditorSite() + .getWorkbenchWindow().getShell().getDisplay(); + BusyIndicator.showWhile(display, runnable); + } else + runnable.run(); + + } + } + + /** + * Selects the given range on the editor. + * + * @param newOffset + * the selection offset + * @param newLength + * the selection range + */ + private void selectAndReveal(int newOffset, int newLength) { + Assert.isTrue(newOffset >= 0); + Assert.isTrue(newLength >= 0); + ITextEditor editor = getTextEditor(); + if (editor instanceof PHPEditor) { + ISourceViewer viewer = ((PHPEditor) editor).getViewer(); + if (viewer != null) + viewer.setSelectedRange(newOffset, newLength); + } else + // this is too intrusive, but will never get called anyway + getTextEditor().selectAndReveal(newOffset, newLength); + + } + + /** + * Indents a single line using the java heuristic scanner. Javadoc and + * multiline comments are indented as specified by the + * JavaDocAutoIndentStrategy. + * + * @param document + * the document + * @param line + * the line to be indented + * @param caret + * the caret position + * @param indenter + * the java indenter + * @param scanner + * the heuristic scanner + * @return true if document was modified, + * false otherwise + * @throws BadLocationException + * if the document got changed concurrently + */ + private boolean indentLine(IDocument document, int line, int caret, + JavaIndenter indenter, JavaHeuristicScanner scanner) + throws BadLocationException { + IRegion currentLine = document.getLineInformation(line); + int offset = currentLine.getOffset(); + int wsStart = offset; // where we start searching for non-WS; after + // the "//" in single line comments + + String indent = null; + if (offset < document.getLength()) { + ITypedRegion partition = TextUtilities.getPartition(document, + IPHPPartitions.PHP_PARTITIONING, offset, true); + String type = partition.getType(); + if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) + || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { + + // TODO this is a hack + // what I want to do + // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, + // offset); + // return; + + int start = 0; + if (line > 0) { + + IRegion previousLine = document + .getLineInformation(line - 1); + start = previousLine.getOffset() + previousLine.getLength(); + } + + DocumentCommand command = new DocumentCommand() { + }; + command.text = "\n"; //$NON-NLS-1$ + command.offset = start; + new JavaDocAutoIndentStrategy(IPHPPartitions.PHP_PARTITIONING) + .customizeDocumentCommand(document, command); + int to = 1; + while (to < command.text.length() + && Character.isWhitespace(command.text.charAt(to))) + to++; + indent = command.text.substring(1, to); + +// omit Java style +// } else if (!fIsTabAction && partition.getOffset() == offset +// && type.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { +// +// // line comment starting at position 0 -> indent inside +// int slashes = 2; +// while (slashes < document.getLength() - 1 +// && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$ +// slashes += 2; +// +// wsStart = offset + slashes; +// +// StringBuffer computed = indenter.computeIndentation(offset); +// int tabSize = PHPeclipsePlugin +// .getDefault() +// .getPreferenceStore() +// .getInt( +// AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); +// while (slashes > 0 && computed.length() > 0) { +// char c = computed.charAt(0); +// if (c == '\t') +// if (slashes > tabSize) +// slashes -= tabSize; +// else +// break; +// else if (c == ' ') +// slashes--; +// else +// break; +// +// computed.deleteCharAt(0); +// } +// +// indent = document.get(offset, wsStart - offset) + computed; + + } + } + + // standard java indentation + if (indent == null) { + StringBuffer computed = indenter.computeIndentation(offset); + if (computed != null) + indent = computed.toString(); + else + //indent = new String(); + return true; // prevent affecting html part + } + + // change document: + // get current white space + int lineLength = currentLine.getLength(); + int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart, + offset + lineLength); + if (end == JavaHeuristicScanner.NOT_FOUND) + end = offset + lineLength; + int length = end - offset; + String currentIndent = document.get(offset, length); + + // if we are right before the text start / line end, and already after + // the insertion point + // then just insert a tab. + if (fIsTabAction && caret == end + && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { + String tab = getTabEquivalent(); + document.replace(caret, 0, tab); + fCaretOffset = caret + tab.length(); + return true; + } + + // set the caret offset so it can be used when setting the selection + if (caret >= offset && caret <= end) + fCaretOffset = offset + indent.length(); + else + fCaretOffset = -1; + + // only change the document if it is a real change + if (!indent.equals(currentIndent)) { + String deletedText = document.get(offset, length); + document.replace(offset, length, indent); + + if (fIsTabAction + && indent.length() > currentIndent.length() + && PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_SMART_BACKSPACE)) { + ITextEditor editor = getTextEditor(); + if (editor != null) { + final SmartBackspaceManager manager = (SmartBackspaceManager) editor + .getAdapter(SmartBackspaceManager.class); + if (manager != null) { + try { + // restore smart portion + ReplaceEdit smart = new ReplaceEdit(offset, indent + .length(), deletedText); + + final UndoSpec spec = new UndoSpec(offset + + indent.length(), new Region(caret, 0), + new TextEdit[] { smart }, 2, null); + manager.register(spec); + } catch (MalformedTreeException e) { + // log & ignore + PHPeclipsePlugin.log(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, + "Illegal smart backspace action", e)); //$NON-NLS-1$ + } + } + } + } + + return true; + } else + return false; + } + + /** + * Returns the size in characters of a string. All characters count one, + * tabs count the editor's preference for the tab display + * + * @param indent + * the string to be measured. + * @return + */ + private int whiteSpaceLength(String indent) { + if (indent == null) + return 0; + else { + int size = 0; + int l = indent.length(); + int tabSize = PHPeclipsePlugin.getDefault().getPreferenceStore().getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + + for (int i = 0; i < l; i++) + size += indent.charAt(i) == '\t' ? tabSize : 1; + return size; + } + } + + /** + * Returns a tab equivalent, either as a tab character or as spaces, + * depending on the editor and formatter preferences. + * + * @return a string representing one tab in the editor, never + * null + */ + private String getTabEquivalent() { + String tab; + if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { + int size = JavaCore.getPlugin().getPluginPreferences().getInt( + DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE); + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < size; i++) + buf.append(' '); + tab = buf.toString(); + } else + tab = "\t"; //$NON-NLS-1$ + + return tab; + } + + /** + * Returns the editor's selection provider. + * + * @return the editor's selection provider or null + */ + private ISelectionProvider getSelectionProvider() { + ITextEditor editor = getTextEditor(); + if (editor != null) { + return editor.getSelectionProvider(); + } + return null; + } + + /* + * @see org.eclipse.ui.texteditor.IUpdate#update() + */ + public void update() { + super.update(); + + if (isEnabled()) + if (fIsTabAction) + setEnabled(canModifyEditor() && isSmartMode() + && isValidSelection()); + else + setEnabled(canModifyEditor() && !getSelection().isEmpty()); + } + + /** + * Returns if the current selection is valid, i.e. whether it is empty and + * the caret in the whitespace at the start of a line, or covers multiple + * lines. + * + * @return true if the selection is valid for an indent + * operation + */ + private boolean isValidSelection() { + ITextSelection selection = getSelection(); + + if (selection.isEmpty()) { + return false; + } + + int offset = selection.getOffset(); + int length = selection.getLength(); + + IDocument document = getDocument(); + + if (document == null) { + return false; + } + + try { + IRegion firstLine = document.getLineInformationOfOffset(offset); + int lineOffset = firstLine.getOffset(); + + // either the selection has to be empty and the caret in the WS at + // the line start + // or the selection has to extend over multiple lines + if (length == 0) { + boolean bRet; + + bRet = document.get (lineOffset, offset - lineOffset).trim().length() == 0; + + return bRet; + } + else { + // return lineOffset + firstLine.getLength() < offset + length; + return false; // only enable for empty selections for now + } + + } catch (BadLocationException e) { + } + + return false; + } + + /** + * Returns the smart preference state. + * + * @return true if smart mode is on, false + * otherwise + */ + private boolean isSmartMode() { + ITextEditor editor = getTextEditor(); + + if (editor instanceof ITextEditorExtension3) + return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; + + return false; + } + + /** + * Returns the document currently displayed in the editor, or + * null if none can be obtained. + * + * @return the current document or null + */ + private IDocument getDocument() { ITextEditor editor = getTextEditor(); + if (editor != null) { + IDocumentProvider provider = editor.getDocumentProvider(); + IEditorInput input = editor.getEditorInput(); + + if (provider != null && input != null) { + return provider.getDocument(input); + } + } + + return null; + } + + /** + * Returns the selection on the editor or an invalid selection if none can + * be obtained. Returns never null. + * + * @return the current selection, never null + */ + private ITextSelection getSelection() { + ISelectionProvider provider = getSelectionProvider(); + if (provider != null) { + + ISelection selection = provider.getSelection(); + if (selection instanceof ITextSelection) + return (ITextSelection) selection; + } + + // null object + return TextSelection.emptySelection(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/OpenActionUtil.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/RemoveBlockCommentAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java new file mode 100644 index 0000000..b5e1428 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionConverter.java @@ -0,0 +1,262 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.actions; + +//import java.util.Iterator; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +//import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaModelException; +//import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; + +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IWorkbenchPart; + +public class SelectionConverter { + + private static final IJavaElement[] EMPTY_RESULT = new IJavaElement[0]; + + private SelectionConverter() { + // no instance + } + + /** + * Converts the selection provided by the given part into a structured + * selection. The following conversion rules are used: + *
    + *
  • part instanceof PHPEditor: returns a structured + * selection using code resolve to convert the editor's text selection.
  • + *
  • part instanceof IWorkbenchPart: returns the part's + * selection if it is a structured selection.
  • + *
  • default: returns an empty structured selection.
  • + *
+ */ + public static IStructuredSelection getStructuredSelection( + IWorkbenchPart part) throws JavaModelException { + if (part instanceof PHPEditor) + return new StructuredSelection(codeResolve((PHPEditor) part)); + ISelectionProvider provider = part.getSite().getSelectionProvider(); + if (provider != null) { + ISelection selection = provider.getSelection(); + if (selection instanceof IStructuredSelection) + return (IStructuredSelection) selection; + } + return StructuredSelection.EMPTY; + } + + /** + * Converts the given structured selection into an array of Java elements. + * An empty array is returned if one of the elements stored in the + * structured selection is not of tupe IJavaElement + */ +// public static IJavaElement[] getElements(IStructuredSelection selection) { +// if (!selection.isEmpty()) { +// IJavaElement[] result = new IJavaElement[selection.size()]; +// int i = 0; +// for (Iterator iter = selection.iterator(); iter.hasNext(); i++) { +// Object element = (Object) iter.next(); +// if (!(element instanceof IJavaElement)) +// return EMPTY_RESULT; +// result[i] = (IJavaElement) element; +// } +// return result; +// } +// return EMPTY_RESULT; +// } + + public static boolean canOperateOn(PHPEditor editor) { + if (editor == null) + return false; + return getInput(editor) != null; + + } + + /** + * Converts the text selection provided by the given editor into an array of + * Java elements. If the selection doesn't cover a Java element and the + * selection's length is greater than 0 the methods returns the editor's + * input element. + */ + public static IJavaElement[] codeResolveOrInput(PHPEditor editor) + throws JavaModelException { + IJavaElement input = getInput(editor); + ITextSelection selection = (ITextSelection) editor + .getSelectionProvider().getSelection(); + IJavaElement[] result = codeResolve(input, selection); + if (result.length == 0) { + result = new IJavaElement[] { input }; + } + return result; + } + +// public static IJavaElement[] codeResolveOrInputHandled(PHPEditor editor, +// Shell shell, String title) { +// try { +// return codeResolveOrInput(editor); +// } catch (JavaModelException e) { +// ExceptionHandler.handle(e, shell, title, ActionMessages +// .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ +// } +// return null; +// } + + /** + * Converts the text selection provided by the given editor a Java element + * by asking the user if code reolve returned more than one result. If the + * selection doesn't cover a Java element and the selection's length is + * greater than 0 the methods returns the editor's input element. + */ + public static IJavaElement codeResolveOrInput(PHPEditor editor, + Shell shell, String title, String message) + throws JavaModelException { + IJavaElement[] elements = codeResolveOrInput(editor); + if (elements == null || elements.length == 0) + return null; + IJavaElement candidate = elements[0]; + if (elements.length > 1) { + candidate = OpenActionUtil.selectJavaElement(elements, shell, + title, message); + } + return candidate; + } + +// public static IJavaElement codeResolveOrInputHandled(PHPEditor editor, +// Shell shell, String title, String message) { +// try { +// return codeResolveOrInput(editor, shell, title, message); +// } catch (JavaModelException e) { +// ExceptionHandler.handle(e, shell, title, ActionMessages +// .getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$ +// } +// return null; +// } + + public static IJavaElement[] codeResolve(PHPEditor editor) + throws JavaModelException { + return codeResolve(getInput(editor), (ITextSelection) editor + .getSelectionProvider().getSelection()); + } + + /** + * Converts the text selection provided by the given editor a Java element + * by asking the user if code reolve returned more than one result. If the + * selection doesn't cover a Java element null is returned. + */ +// public static IJavaElement codeResolve(PHPEditor editor, Shell shell, +// String title, String message) throws JavaModelException { +// IJavaElement[] elements = codeResolve(editor); +// if (elements == null || elements.length == 0) +// return null; +// IJavaElement candidate = elements[0]; +// if (elements.length > 1) { +// candidate = OpenActionUtil.selectJavaElement(elements, shell, +// title, message); +// } +// return candidate; +// } + +// public static IJavaElement[] codeResolveHandled(PHPEditor editor, +// Shell shell, String title) { +// try { +// return codeResolve(editor); +// } catch (JavaModelException e) { +// ExceptionHandler.handle(e, shell, title, ActionMessages +// .getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$ +// } +// return null; +// } + + public static IJavaElement getElementAtOffset(PHPEditor editor) + throws JavaModelException { + return getElementAtOffset(getInput(editor), (ITextSelection) editor + .getSelectionProvider().getSelection()); + } + +// public static IType getTypeAtOffset(PHPEditor editor) +// throws JavaModelException { +// IJavaElement element = SelectionConverter.getElementAtOffset(editor); +// IType type = (IType) element.getAncestor(IJavaElement.TYPE); +// if (type == null) { +// ICompilationUnit unit = SelectionConverter +// .getInputAsCompilationUnit(editor); +// if (unit != null) +// type = unit.findPrimaryType(); +// } +// return type; +// } + + public static IJavaElement getInput(PHPEditor editor) { + if (editor == null) + return null; + IEditorInput input = editor.getEditorInput(); + // if (input instanceof IClassFileEditorInput) + // return ((IClassFileEditorInput)input).getClassFile(); + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + return manager.getWorkingCopy(input); + } + +// public static ICompilationUnit getInputAsCompilationUnit(PHPEditor editor) { +// Object editorInput = SelectionConverter.getInput(editor); +// if (editorInput instanceof ICompilationUnit) +// return (ICompilationUnit) editorInput; +// else +// return null; +// } + + private static IJavaElement[] codeResolve(IJavaElement input, + ITextSelection selection) throws JavaModelException { + // if (input instanceof ICodeAssist) { + // IJavaElement[] elements= + // ((ICodeAssist)input).codeSelect(selection.getOffset(), + // selection.getLength()); + // if (elements != null && elements.length > 0) + // return elements; + // } + return EMPTY_RESULT; + } + + private static IJavaElement getElementAtOffset(IJavaElement input, + ITextSelection selection) throws JavaModelException { + if (input instanceof ICompilationUnit) { + ICompilationUnit cunit = (ICompilationUnit) input; + if (cunit.isWorkingCopy()) { + synchronized (cunit) { + cunit.reconcile(); + } + } + IJavaElement ref = cunit.getElementAt(selection.getOffset()); + if (ref == null) + return input; + else + return ref; + } + // else if (input instanceof IClassFile) { + // IJavaElement ref= + // ((IClassFile)input).getElementAt(selection.getOffset()); + // if (ref == null) + // return input; + // else + // return ref; + // } + return null; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/SelectionDispatchAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java new file mode 100644 index 0000000..88a0d3e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/WorkbenchRunnableAdapter.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.actions; + +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.jface.operation.IRunnableWithProgress; + +/** + * An IRunnableWithProgress that adapts and + * IWorkspaceRunnable so that is can be executed inside + * IRunnableContext. OperationCanceledException + * thrown by the apapted runnabled are cought and rethrown as a + * InterruptedException. + */ +public class WorkbenchRunnableAdapter implements IRunnableWithProgress { + + private IWorkspaceRunnable fWorkspaceRunnable; + + public WorkbenchRunnableAdapter(IWorkspaceRunnable runnable) { + fWorkspaceRunnable = runnable; + } + + /* + * @see IRunnableWithProgress#run(IProgressMonitor) + */ + public void run(IProgressMonitor monitor) throws InvocationTargetException, + InterruptedException { + try { + PHPeclipsePlugin.run(fWorkspaceRunnable, monitor); + } catch (OperationCanceledException e) { + throw new InterruptedException(e.getMessage()); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/CheckedTreeSelectionDialog.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ElementListSelectionDialog.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/ISelectionValidator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ISelectionValidator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/ISelectionValidator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/ISelectionValidator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/MessageLine.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/SelectionStatusDialog.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusDialog.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java new file mode 100644 index 0000000..f665d3b --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusInfo.java @@ -0,0 +1,177 @@ +package net.sourceforge.phpdt.internal.ui.dialogs; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; + +/** + * A settable IStatus. Can be an error, warning, info or ok. For error, info and + * warning states, a message describes the problem. + */ +public class StatusInfo implements IStatus { + + private String fStatusMessage; + + private int fSeverity; + + /** + * Creates a status set to OK (no message) + */ + public StatusInfo() { + this(OK, null); + } + + /** + * Creates a status . + * + * @param severity + * The status severity: ERROR, WARNING, INFO and OK. + * @param message + * The message of the status. Applies only for ERROR, WARNING and + * INFO. + */ + public StatusInfo(int severity, String message) { + fStatusMessage = message; + fSeverity = severity; + } + + /** + * Returns if the status' severity is OK. + */ + public boolean isOK() { + return fSeverity == IStatus.OK; + } + + /** + * Returns if the status' severity is WARNING. + */ + public boolean isWarning() { + return fSeverity == IStatus.WARNING; + } + + /** + * Returns if the status' severity is INFO. + */ + public boolean isInfo() { + return fSeverity == IStatus.INFO; + } + + /** + * Returns if the status' severity is ERROR. + */ + public boolean isError() { + return fSeverity == IStatus.ERROR; + } + + /** + * @see IStatus#getMessage + */ + public String getMessage() { + return fStatusMessage; + } + + /** + * Sets the status to ERROR. + * + * @param The + * error message (can be empty, but not null) + */ + public void setError(String errorMessage) { + Assert.isNotNull(errorMessage); + fStatusMessage = errorMessage; + fSeverity = IStatus.ERROR; + } + + /** + * Sets the status to WARNING. + * + * @param The + * warning message (can be empty, but not null) + */ + public void setWarning(String warningMessage) { + Assert.isNotNull(warningMessage); + fStatusMessage = warningMessage; + fSeverity = IStatus.WARNING; + } + + /** + * Sets the status to INFO. + * + * @param The + * info message (can be empty, but not null) + */ + public void setInfo(String infoMessage) { + Assert.isNotNull(infoMessage); + fStatusMessage = infoMessage; + fSeverity = IStatus.INFO; + } + + /** + * Sets the status to OK. + */ + public void setOK() { + fStatusMessage = null; + fSeverity = IStatus.OK; + } + + /* + * @see IStatus#matches(int) + */ + public boolean matches(int severityMask) { + return (fSeverity & severityMask) != 0; + } + + /** + * Returns always false. + * + * @see IStatus#isMultiStatus() + */ + public boolean isMultiStatus() { + return false; + } + + /* + * @see IStatus#getSeverity() + */ + public int getSeverity() { + return fSeverity; + } + + /* + * @see IStatus#getPlugin() + */ + public String getPlugin() { + return PHPeclipsePlugin.PLUGIN_ID; + } + + /** + * Returns always null. + * + * @see IStatus#getException() + */ + public Throwable getException() { + return null; + } + + /** + * Returns always the error severity. + * + * @see IStatus#getCode() + */ + public int getCode() { + return fSeverity; + } + + /** + * Returns always null. + * + * @see IStatus#getChildren() + */ + public IStatus[] getChildren() { + return new IStatus[0]; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dialogs/StatusUtil.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java new file mode 100644 index 0000000..6a870fd --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.dnd; + +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.swt.dnd.ByteArrayTransfer; +import org.eclipse.swt.dnd.TransferData; + +public class LocalSelectionTransfer extends ByteArrayTransfer { + + // First attempt to create a UUID for the type name to make sure that + // different Eclipse applications use different "types" of + // LocalSelectionTransfer + private static final String TYPE_NAME = "local-selection-transfer-format" + (new Long(System.currentTimeMillis())).toString(); //$NON-NLS-1$; + + private static final int TYPEID = registerType(TYPE_NAME); + + private static final LocalSelectionTransfer INSTANCE = new LocalSelectionTransfer(); + + private ISelection fSelection; + + private int fSelectionSetTime; + + private LocalSelectionTransfer() { + } + + /** + * Returns the singleton. + */ + public static LocalSelectionTransfer getInstance() { + return INSTANCE; + } + + /** + * Sets the transfer data for local use. + */ + public void setSelection(ISelection s) { + fSelection = s; + } + + /** + * Returns the local transfer data. + */ + public ISelection getSelection() { + return fSelection; + } + + public void javaToNative(Object object, TransferData transferData) { + // No encoding needed since this is a hardcoded string read and written + // in the same process. + // See nativeToJava below + byte[] check = TYPE_NAME.getBytes(); + super.javaToNative(check, transferData); + } + + public Object nativeToJava(TransferData transferData) { + Object result = super.nativeToJava(transferData); + if (isInvalidNativeType(result)) { + PHPeclipsePlugin.log(IStatus.ERROR, PHPUIMessages + .getString("LocalSelectionTransfer.errorMessage")); //$NON-NLS-1$ + } + return fSelection; + } + + private boolean isInvalidNativeType(Object result) { + // No encoding needed since this is a hardcoded string read and written + // in the same process. + // See javaToNative above + return !(result instanceof byte[]) + || !TYPE_NAME.equals(new String((byte[]) result)); + } + + /** + * The type id used to identify this transfer. + */ + protected int[] getTypeIds() { + return new int[] { TYPEID }; + } + + protected String[] getTypeNames() { + return new String[] { TYPE_NAME }; + } + + public int getSelectionSetTime() { + return fSelectionSetTime; + } + + public void setSelectionSetTime(int time) { + fSelectionSetTime = time; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java new file mode 100644 index 0000000..d8c6e9c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.dnd; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants; +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpdt.internal.ui.util.SWTUtil; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.jface.dialogs.ErrorDialog; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.dnd.DND; +import org.eclipse.swt.dnd.DragSourceAdapter; +import org.eclipse.swt.dnd.DragSourceEvent; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.part.ResourceTransfer; + +/** + * A drag adapter that transfers the current selection as
IResource
. + * Only those elements in the selection are part of the transfer which can be + * converted into an IResource . + */ +public class ResourceTransferDragAdapter extends DragSourceAdapter implements + TransferDragSourceListener { + + private ISelectionProvider fProvider; + + private static final List EMPTY_LIST = new ArrayList(0); + + /** + * Creates a new ResourceTransferDragAdapter for the given selection + * provider. + * + * @param provider + * the selection provider to access the viewer's selection + */ + public ResourceTransferDragAdapter(ISelectionProvider provider) { + fProvider = provider; + Assert.isNotNull(fProvider); + } + + public Transfer getTransfer() { + return ResourceTransfer.getInstance(); + } + + public void dragStart(DragSourceEvent event) { + event.doit = convertSelection().size() > 0; + } + + public void dragSetData(DragSourceEvent event) { + List resources = convertSelection(); + event.data = (IResource[]) resources.toArray(new IResource[resources + .size()]); + } + + public void dragFinished(DragSourceEvent event) { + if (!event.doit) + return; + + if (event.detail == DND.DROP_MOVE) { + handleFinishedDropMove(event); + } + } + + private List convertSelection() { + ISelection s = fProvider.getSelection(); + if (!(s instanceof IStructuredSelection)) + return EMPTY_LIST; + IStructuredSelection selection = (IStructuredSelection) s; + List result = new ArrayList(selection.size()); + for (Iterator iter = selection.iterator(); iter.hasNext();) { + Object element = iter.next(); + if (element instanceof IAdaptable) { + IAdaptable adaptable = (IAdaptable) element; + IResource resource = (IResource) adaptable + .getAdapter(IResource.class); + if (resource != null) + result.add(resource); + } + } + return result; + } + + private void handleFinishedDropMove(DragSourceEvent event) { + MultiStatus status = new MultiStatus( + PHPeclipsePlugin.getPluginId(), + IJavaStatusConstants.INTERNAL_ERROR, + PHPUIMessages + .getString("ResourceTransferDragAdapter.cannot_delete_resource"), //$NON-NLS-1$ + null); + List resources = convertSelection(); + for (Iterator iter = resources.iterator(); iter.hasNext();) { + IResource resource = (IResource) iter.next(); + try { + resource.delete(true, null); + } catch (CoreException e) { + status.add(e.getStatus()); + } + } + if (status.getChildren().length > 0) { + Shell parent = SWTUtil.getShell(event.widget); + ErrorDialog error = new ErrorDialog( + parent, + PHPUIMessages + .getString("ResourceTransferDragAdapter.moving_resource"), //$NON-NLS-1$ + PHPUIMessages + .getString("ResourceTransferDragAdapter.cannot_delete_files"), //$NON-NLS-1$ + status, IStatus.ERROR); + error.open(); + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/CustomFiltersDialog.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java new file mode 100644 index 0000000..3214384 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterDescriptor.java @@ -0,0 +1,309 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.filters; + +import java.text.Collator; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.ISafeRunnable; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.SafeRunner; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.util.SafeRunnable; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.ui.IPluginContribution; +import org.eclipse.ui.activities.WorkbenchActivityHelper; + +/** + * Represents a custom filter which is provided by the + * "net.sourceforge.phpdt.ui.javaElementFilters" extension point. + * + * since 2.0 + */ +public class FilterDescriptor implements Comparable, IPluginContribution { + + private static String PATTERN_FILTER_ID_PREFIX = "_patternFilterId_"; //$NON-NLS-1$ + + private static final String EXTENSION_POINT_NAME = "phpElementFilters"; //$NON-NLS-1$ + + private static final String FILTER_TAG = "filter"; //$NON-NLS-1$ + + private static final String PATTERN_ATTRIBUTE = "pattern"; //$NON-NLS-1$ + + private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$ + + /** + * @deprecated as of 3.0 use {@link FilterDescriptor#TARGET_ID_ATTRIBUTE} + */ + private static final String VIEW_ID_ATTRIBUTE = "viewId"; //$NON-NLS-1$ + + private static final String TARGET_ID_ATTRIBUTE = "targetId"; //$NON-NLS-1$ + + private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$ + + private static final String NAME_ATTRIBUTE = "name"; //$NON-NLS-1$ + + private static final String ENABLED_ATTRIBUTE = "enabled"; //$NON-NLS-1$ + + private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ + + /** + * @deprecated use "enabled" instead + */ + private static final String SELECTED_ATTRIBUTE = "selected"; //$NON-NLS-1$ + + private static FilterDescriptor[] fgFilterDescriptors; + + private IConfigurationElement fElement; + + /** + * Returns all contributed Java element filters. + */ + public static FilterDescriptor[] getFilterDescriptors() { + if (fgFilterDescriptors == null) { + IExtensionRegistry registry = Platform.getExtensionRegistry(); + IConfigurationElement[] elements = registry + .getConfigurationElementsFor(PHPeclipsePlugin.PLUGIN_ID, + EXTENSION_POINT_NAME); + fgFilterDescriptors = createFilterDescriptors(elements); + } + return fgFilterDescriptors; + } + + /** + * Returns all Java element filters which are contributed to the given view. + */ + public static FilterDescriptor[] getFilterDescriptors(String targetId) { + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(); + List result = new ArrayList(filterDescs.length); + for (int i = 0; i < filterDescs.length; i++) { + String tid = filterDescs[i].getTargetId(); + if (WorkbenchActivityHelper.filterItem(filterDescs[i])) + continue; + if (tid == null || tid.equals(targetId)) + result.add(filterDescs[i]); + } + return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result + .size()]); + } + + /** + * Creates a new filter descriptor for the given configuration element. + */ + private FilterDescriptor(IConfigurationElement element) { + fElement = element; + // it is either a pattern filter or a custom filter + Assert + .isTrue( + isPatternFilter() ^ isCustomFilter(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$ + Assert + .isNotNull( + getId(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$ + Assert + .isNotNull( + getName(), + "An extension for extension-point net.sourceforge.phpdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$ + } + + /** + * Creates a new ViewerFilter. This method is only valid for + * viewer filters. + */ + public ViewerFilter createViewerFilter() { + if (!isCustomFilter()) + return null; + + final ViewerFilter[] result = new ViewerFilter[1]; + String message = FilterMessages.getFormattedString( + "FilterDescriptor.filterCreationError.message", getId()); //$NON-NLS-1$ + ISafeRunnable code = new SafeRunnable(message) { + /* + * @see org.eclipse.core.runtime.ISafeRunnable#run() + */ + public void run() throws Exception { + result[0] = (ViewerFilter) fElement + .createExecutableExtension(CLASS_ATTRIBUTE); + } + + }; + SafeRunner.run(code); + return result[0]; + } + + // ---- XML Attribute accessors + // --------------------------------------------- + + /** + * Returns the filter's id. + *

+ * This attribute is mandatory for custom filters. The ID for pattern + * filters is PATTERN_FILTER_ID_PREFIX plus the pattern itself. + *

+ */ + public String getId() { + if (isPatternFilter()) { + String targetId = getTargetId(); + if (targetId == null) + return PATTERN_FILTER_ID_PREFIX + getPattern(); + else + return targetId + PATTERN_FILTER_ID_PREFIX + getPattern(); + } else + return fElement.getAttribute(ID_ATTRIBUTE); + } + + /** + * Returns the filter's name. + *

+ * If the name of a pattern filter is missing then the pattern is used as + * its name. + *

+ */ + public String getName() { + String name = fElement.getAttribute(NAME_ATTRIBUTE); + if (name == null && isPatternFilter()) + name = getPattern(); + return name; + } + + /** + * Returns the filter's pattern. + * + * @return the pattern string or null if it's not a pattern + * filter + */ + public String getPattern() { + return fElement.getAttribute(PATTERN_ATTRIBUTE); + } + + /** + * Returns the filter's viewId. + * + * @return the view ID or null if the filter is for all views + * @since 3.0 + */ + public String getTargetId() { + String tid = fElement.getAttribute(TARGET_ID_ATTRIBUTE); + + if (tid != null) + return tid; + + // Backwards compatibility code + return fElement.getAttribute(VIEW_ID_ATTRIBUTE); + + } + + /** + * Returns the filter's description. + * + * @return the description or null if no description is + * provided + */ + public String getDescription() { + String description = fElement.getAttribute(DESCRIPTION_ATTRIBUTE); + if (description == null) + description = ""; //$NON-NLS-1$ + return description; + } + + /** + * @return true if this filter is a custom filter. + */ + public boolean isPatternFilter() { + return getPattern() != null; + } + + /** + * @return true if this filter is a pattern filter. + */ + public boolean isCustomFilter() { + return fElement.getAttribute(CLASS_ATTRIBUTE) != null; + } + + /** + * Returns true if the filter is initially enabled. + * + * This attribute is optional and defaults to true. + */ + public boolean isEnabled() { + String strVal = fElement.getAttribute(ENABLED_ATTRIBUTE); + if (strVal == null) + // backward compatibility + strVal = fElement.getAttribute(SELECTED_ATTRIBUTE); + return strVal == null || Boolean.valueOf(strVal).booleanValue(); + } + + /* + * Implements a method from IComparable + */ + public int compareTo(Object o) { + if (o instanceof FilterDescriptor) + return Collator.getInstance().compare(getName(), + ((FilterDescriptor) o).getName()); + else + return Integer.MIN_VALUE; + } + + // ---- initialization --------------------------------------------------- + + /** + * Creates the filter descriptors. + */ + private static FilterDescriptor[] createFilterDescriptors( + IConfigurationElement[] elements) { + List result = new ArrayList(5); + Set descIds = new HashSet(5); + for (int i = 0; i < elements.length; i++) { + final IConfigurationElement element = elements[i]; + if (FILTER_TAG.equals(element.getName())) { + + final FilterDescriptor[] desc = new FilterDescriptor[1]; + SafeRunner + .run(new SafeRunnable( + FilterMessages + .getString("FilterDescriptor.filterDescriptionCreationError.message")) { //$NON-NLS-1$ + public void run() throws Exception { + desc[0] = new FilterDescriptor(element); + } + }); + + if (desc[0] != null && !descIds.contains(desc[0].getId())) { + result.add(desc[0]); + descIds.add(desc[0].getId()); + } + } + } + Collections.sort(result); + return (FilterDescriptor[]) result.toArray(new FilterDescriptor[result + .size()]); + } + + public String getLocalId() { + return fElement.getAttribute(ID_ATTRIBUTE); + } + + public String getPluginId() { + return fElement.getDeclaringExtension().getNamespace(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/FilterMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/ImportDeclarationFilter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/filters/NamePatternFilter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/phpdocexport/JavadocExportMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java new file mode 100644 index 0000000..2746a17 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/AbstractConfigurationBlockPreferencePage.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/** + * Abstract preference page which is used to wrap a + * {@link net.sourceforge.phpdt.internal.ui.preferences.IPreferenceConfigurationBlock}. + * + * @since 3.0 + */ +public abstract class AbstractConfigurationBlockPreferencePage extends + PreferencePage implements IWorkbenchPreferencePage { + + private IPreferenceConfigurationBlock fConfigurationBlock; + + private OverlayPreferenceStore fOverlayStore; + + /** + * Creates a new preference page. + */ + public AbstractConfigurationBlockPreferencePage() { + setDescription(); + setPreferenceStore(); + fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), + new OverlayPreferenceStore.OverlayKey[] {}); + fConfigurationBlock = createConfigurationBlock(fOverlayStore); + } + + protected abstract IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore); + + protected abstract String getHelpId(); + + protected abstract void setDescription(); + + protected abstract void setPreferenceStore(); + + /* + * @see IWorkbenchPreferencePage#init() + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + getHelpId()); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + + fOverlayStore.load(); + fOverlayStore.start(); + + fConfigurationBlock.createControl(parent); + + initialize(); + + Dialog.applyDialogFont(parent); + return parent; + } + + private void initialize() { + fConfigurationBlock.initialize(); + } + + /* + * @see PreferencePage#performOk() + */ + public boolean performOk() { + + fConfigurationBlock.performOk(); + + fOverlayStore.propagate(); + + PHPeclipsePlugin.getDefault().savePluginPreferences(); + + return true; + } + + /* + * @see PreferencePage#performDefaults() + */ + public void performDefaults() { + + fOverlayStore.loadDefaults(); + fConfigurationBlock.performDefaults(); + + super.performDefaults(); + } + + /* + * @see DialogPage#dispose() + */ + public void dispose() { + + fConfigurationBlock.dispose(); + + if (fOverlayStore != null) { + fOverlayStore.stop(); + fOverlayStore = null; + } + + super.dispose(); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java new file mode 100644 index 0000000..d471983 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeAssistPreferencePage.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +/** + * Code Assist preference page. + *

+ * Note: Must be public since it is referenced from plugin.xml + *

+ * + * @since 3.0 + */ +public class CodeAssistPreferencePage extends + AbstractConfigurationBlockPreferencePage { + + /* + * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#getHelpId() + */ + protected String getHelpId() { + return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setDescription() + */ + protected void setDescription() { + // This page has no description + } + + /* + * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigurationBlockPreferencePage#setPreferenceStore() + */ + protected void setPreferenceStore() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.preferences.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore) + */ + protected IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore) { + return new CodeAssistConfigurationBlock(this, overlayPreferenceStore); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java new file mode 100644 index 0000000..fbf6a9d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreferencePage.java @@ -0,0 +1,557 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Hashtable; + +import net.sourceforge.phpdt.core.ICodeFormatter; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.util.TabFolderLayout; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.swt.SWT; +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.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.TabFolder; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +/* + * The page for setting code formatter options + */ +public class CodeFormatterPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + + // Preference store keys, see PHPCore.getOptions + private static final String PREF_NEWLINE_OPENING_BRACES = JavaCore.FORMATTER_NEWLINE_OPENING_BRACE; + + private static final String PREF_NEWLINE_CONTROL_STATEMENT = JavaCore.FORMATTER_NEWLINE_CONTROL; + + private static final String PREF_NEWLINE_CLEAR_ALL = JavaCore.FORMATTER_CLEAR_BLANK_LINES; + + // private static final String PREF_NEWLINE_ELSE_IF= + // PHPCore.FORMATTER_NEWLINE_ELSE_IF; + private static final String PREF_NEWLINE_EMPTY_BLOCK = JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK; + + private static final String PREF_LINE_SPLIT = JavaCore.FORMATTER_LINE_SPLIT; + + private static final String PREF_STYLE_COMPACT_ASSIGNEMENT = JavaCore.FORMATTER_COMPACT_ASSIGNMENT; + + private static final String PREF_STYLE_COMPACT_STRING_CONCATENATION = JavaCore.FORMATTER_COMPACT_STRING_CONCATENATION; + + private static final String PREF_STYLE_COMPACT_ARRAYS = JavaCore.FORMATTER_COMPACT_ARRAYS; + + private static final String PREF_TAB_CHAR = JavaCore.FORMATTER_TAB_CHAR; + + private static final String PREF_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; + + // values + private static final String INSERT = JavaCore.INSERT; + + private static final String DO_NOT_INSERT = JavaCore.DO_NOT_INSERT; + + private static final String COMPACT = JavaCore.COMPACT; + + private static final String NORMAL = JavaCore.NORMAL; + + private static final String TAB = JavaCore.TAB; + + private static final String SPACE = JavaCore.SPACE; + + private static final String CLEAR_ALL = JavaCore.CLEAR_ALL; + + private static final String PRESERVE_ONE = JavaCore.PRESERVE_ONE; + + private static String[] getAllKeys() { + return new String[] { PREF_NEWLINE_OPENING_BRACES, + PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, + // PREF_NEWLINE_ELSE_IF, + PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT, + PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_STYLE_COMPACT_STRING_CONCATENATION, + PREF_STYLE_COMPACT_ARRAYS, + PREF_TAB_CHAR, PREF_TAB_SIZE }; + } + + /** + * Gets the currently configured tab size + * + * @deprecated Inline to avoid reference to preference page + */ + public static int getTabSize() { + String string = (String) JavaCore.getOptions().get(PREF_TAB_SIZE); + return getPositiveIntValue(string, 4); + } + + /** + * Gets the current compating assignement configuration + * + * @deprecated Inline to avoid reference to preference page + */ + public static boolean isCompactingAssignment() { + return COMPACT.equals(JavaCore.getOptions().get( + PREF_STYLE_COMPACT_ASSIGNEMENT)); + } + + /** + * Gets the current compating assignement configuration + * + * @deprecated Inline to avoid reference to preference page + */ + public static boolean useSpaces() { + return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR)); + } + + private static int getPositiveIntValue(String string, int dflt) { + try { + int i = Integer.parseInt(string); + if (i >= 0) { + return i; + } + } catch (NumberFormatException e) { + } + return dflt; + } + + private static class ControlData { + private String fKey; + + private String[] fValues; + + public ControlData(String key, String[] values) { + fKey = key; + fValues = values; + } + + public String getKey() { + return fKey; + } + + public String getValue(boolean selection) { + int index = selection ? 0 : 1; + return fValues[index]; + } + + public String getValue(int index) { + return fValues[index]; + } + + public int getSelection(String value) { + for (int i = 0; i < fValues.length; i++) { + if (value.equals(fValues[i])) { + return i; + } + } + throw new IllegalArgumentException(); + } + } + + private Hashtable fWorkingValues; + + private ArrayList fCheckBoxes; + + private ArrayList fTextBoxes; + + private SelectionListener fButtonSelectionListener; + + private ModifyListener fTextModifyListener; + + private String fPreviewText; + + private IDocument fPreviewDocument; + + private Text fTabSizeTextBox; + + // private SourceViewer fSourceViewer; + + public CodeFormatterPreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PHPUIMessages + .getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$ + + fWorkingValues = JavaCore.getOptions(); + fCheckBoxes = new ArrayList(); + fTextBoxes = new ArrayList(); + + fButtonSelectionListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + if (!e.widget.isDisposed()) { + controlChanged((Button) e.widget); + } + } + }; + + fTextModifyListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + if (!e.widget.isDisposed()) { + textChanged((Text) e.widget); + } + } + }; + + fPreviewDocument = new Document(); + fPreviewText = loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ + } + + /* + * @see IWorkbenchPreferencePage#init() + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + // WorkbenchHelp.setHelp(getControl(), + // IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(layout); + + TabFolder folder = new TabFolder(composite, SWT.NONE); + folder.setLayout(new TabFolderLayout()); + folder.setLayoutData(new GridData(GridData.FILL_BOTH)); + + String[] insertNotInsert = new String[] { INSERT, DO_NOT_INSERT }; + + layout = new GridLayout(); + layout.numColumns = 2; + + Composite newlineComposite = new Composite(folder, SWT.NULL); + newlineComposite.setLayout(layout); + + String label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, + insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, + insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, + new String[] { CLEAR_ALL, PRESERVE_ONE }); + + // label= + // PHPUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); + // //$NON-NLS-1$ + // addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, + // insertNotInsert); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ + addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, + insertNotInsert); + + layout = new GridLayout(); + layout.numColumns = 2; + + Composite lineSplittingComposite = new Composite(folder, SWT.NULL); + lineSplittingComposite.setLayout(layout); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$ + addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT); + + layout = new GridLayout(); + layout.numColumns = 2; + + Composite styleComposite = new Composite(folder, SWT.NULL); + styleComposite.setLayout(layout); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, + new String[] { COMPACT, NORMAL }); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.style_compact_string_concatenation.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_STRING_CONCATENATION, + new String[] { COMPACT, NORMAL }); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.style_compact_arrays.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ARRAYS, + new String[] { COMPACT, NORMAL }); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ + addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, + SPACE }); + + label = PHPUIMessages + .getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ + fTabSizeTextBox = addTextField(styleComposite, label, PREF_TAB_SIZE); + + TabItem item = new TabItem(folder, SWT.NONE); + item.setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ + item.setControl(newlineComposite); + + item = new TabItem(folder, SWT.NONE); + item + .setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ + item.setControl(lineSplittingComposite); + + item = new TabItem(folder, SWT.NONE); + item.setText(PHPUIMessages + .getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ + item.setControl(styleComposite); + + // fSourceViewer= createPreview(parent); + + updatePreview(); + + return composite; + } + + // private SourceViewer createPreview(Composite parent) { + // SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | + // SWT.H_SCROLL | SWT.BORDER); + // JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); + // previewViewer.configure(new PHPSourceViewerConfiguration(tools, null)); + // previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT)); + // previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) + // fWorkingValues.get(PREF_TAB_SIZE), 0)); + // previewViewer.setEditable(false); + // previewViewer.setDocument(fPreviewDocument); + // Control control= previewViewer.getControl(); + // GridData gdata= new GridData(GridData.FILL_BOTH); + // gdata.widthHint= convertWidthInCharsToPixels(30); + // gdata.heightHint= convertHeightInCharsToPixels(5); + // control.setLayoutData(gdata); + // return previewViewer; + // } + + private Button addCheckBox(Composite parent, String label, String key, + String[] values) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan = 2; + + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + checkBox.setData(data); + checkBox.setLayoutData(gd); + + String currValue = (String) fWorkingValues.get(key); + checkBox.setSelection(data.getSelection(currValue) == 0); + checkBox.addSelectionListener(fButtonSelectionListener); + + fCheckBoxes.add(checkBox); + return checkBox; + } + + private Text addTextField(Composite parent, String label, String key) { + Label labelControl = new Label(parent, SWT.NONE); + labelControl.setText(label); + labelControl.setLayoutData(new GridData()); + + Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); + textBox.setData(key); + textBox.setLayoutData(new GridData()); + + String currValue = (String) fWorkingValues.get(key); + textBox.setText(String.valueOf(getPositiveIntValue(currValue, 1))); + textBox.setTextLimit(3); + textBox.addModifyListener(fTextModifyListener); + + GridData gd = new GridData(); + gd.widthHint = convertWidthInCharsToPixels(5); + textBox.setLayoutData(gd); + + fTextBoxes.add(textBox); + return textBox; + } + + private void controlChanged(Button button) { + ControlData data = (ControlData) button.getData(); + boolean selection = button.getSelection(); + String newValue = data.getValue(selection); + fWorkingValues.put(data.getKey(), newValue); + updatePreview(); + + if (PREF_TAB_CHAR.equals(data.getKey())) { + updateStatus(new StatusInfo()); + if (selection) { + fTabSizeTextBox.setText((String) fWorkingValues + .get(PREF_TAB_SIZE)); + } + } + } + + private void textChanged(Text textControl) { + String key = (String) textControl.getData(); + String number = textControl.getText(); + IStatus status = validatePositiveNumber(number); + if (!status.matches(IStatus.ERROR)) { + fWorkingValues.put(key, number); + } + // if (PREF_TAB_SIZE.equals(key)) { + // fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(number, + // 0)); + // } + updateStatus(status); + updatePreview(); + } + + /* + * @see IPreferencePage#performOk() + */ + public boolean performOk() { + String[] allKeys = getAllKeys(); + // preserve other options + // store in JCore + Hashtable actualOptions = JavaCore.getOptions(); + for (int i = 0; i < allKeys.length; i++) { + String key = allKeys[i]; + String val = (String) fWorkingValues.get(key); + actualOptions.put(key, val); + } + JavaCore.setOptions(actualOptions); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + return super.performOk(); + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fWorkingValues = JavaCore.getDefaultOptions(); + updateControls(); + super.performDefaults(); + } + + private String loadPreviewFile(String filename) { + String separator = System.getProperty("line.separator"); //$NON-NLS-1$ + StringBuffer btxt = new StringBuffer(512); + BufferedReader rin = null; + try { + rin = new BufferedReader(new InputStreamReader(getClass() + .getResourceAsStream(filename))); + String line; + while ((line = rin.readLine()) != null) { + btxt.append(line); + btxt.append(separator); + } + } catch (IOException io) { + PHPeclipsePlugin.log(io); + } finally { + if (rin != null) { + try { + rin.close(); + } catch (IOException e) { + } + } + } + return btxt.toString(); + } + + private void updatePreview() { + ICodeFormatter formatter = ToolFactory + .createDefaultCodeFormatter(fWorkingValues); + fPreviewDocument.set(formatter.format(fPreviewText, 0, null, "\n")); //$NON-NLS-1$ + } + + private void updateControls() { + // update the UI + for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { + Button curr = (Button) fCheckBoxes.get(i); + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.setSelection(data.getSelection(currValue) == 0); + } + for (int i = fTextBoxes.size() - 1; i >= 0; i--) { + Text curr = (Text) fTextBoxes.get(i); + String key = (String) curr.getData(); + String currValue = (String) fWorkingValues.get(key); + curr.setText(currValue); + } + } + + private IStatus validatePositiveNumber(String number) { + StatusInfo status = new StatusInfo(); + if (number.length() == 0) { + status.setError(PHPUIMessages + .getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$ + } else { + try { + int value = Integer.parseInt(number); + if (value < 0) { + status + .setError(PHPUIMessages + .getFormattedString( + "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } + } catch (NumberFormatException e) { + status.setError(PHPUIMessages.getFormattedString( + "CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } + } + return status; + } + + private void updateStatus(IStatus status) { + if (!status.matches(IStatus.ERROR)) { + // look if there are more severe errors + for (int i = 0; i < fTextBoxes.size(); i++) { + Text curr = (Text) fTextBoxes.get(i); + if (!(curr == fTabSizeTextBox && usesTabs())) { + IStatus currStatus = validatePositiveNumber(curr.getText()); + status = StatusUtil.getMoreSevere(currStatus, status); + } + } + } + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } + + private boolean usesTabs() { + return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR)); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreviewCode.txt b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreviewCode.txt similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreviewCode.txt rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeFormatterPreviewCode.txt diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java new file mode 100644 index 0000000..d8dc004 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java @@ -0,0 +1,586 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; +import net.sourceforge.phpdt.internal.ui.util.PixelConverter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ITreeListAdapter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.TreeListDialogField; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData; +import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter; +import org.eclipse.jface.text.templates.persistence.TemplateStore; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +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.FileDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + */ +public class CodeTemplateBlock { + + private class CodeTemplateAdapter implements ITreeListAdapter, + IDialogFieldListener { + + private final Object[] NO_CHILDREN = new Object[0]; + + public void customButtonPressed(TreeListDialogField field, int index) { + doButtonPressed(index, field.getSelectedElements()); + } + + public void selectionChanged(TreeListDialogField field) { + List selected = field.getSelectedElements(); + field.enableButton(IDX_EDIT, canEdit(selected)); + field.enableButton(IDX_EXPORT, !selected.isEmpty()); + + updateSourceViewerInput(selected); + } + + public void doubleClicked(TreeListDialogField field) { + List selected = field.getSelectedElements(); + if (canEdit(selected)) { + doButtonPressed(IDX_EDIT, selected); + } + } + + public Object[] getChildren(TreeListDialogField field, Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return getTemplateOfCategory(element == COMMENT_NODE); + } + return NO_CHILDREN; + } + + public Object getParent(TreeListDialogField field, Object element) { + if (element instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) element; + if (data.getTemplate().getName().endsWith( + CodeTemplateContextType.COMMENT_SUFFIX)) { + return COMMENT_NODE; + } + return CODE_NODE; + } + return null; + } + + public boolean hasChildren(TreeListDialogField field, Object element) { + return (element == COMMENT_NODE || element == CODE_NODE); + } + + public void dialogFieldChanged(DialogField field) { + } + + public void keyPressed(TreeListDialogField field, KeyEvent event) { + } + + } + + private static class CodeTemplateLabelProvider extends LabelProvider { + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + return null; + + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return (String) element; + } + TemplatePersistenceData data = (TemplatePersistenceData) element; + Template template = data.getTemplate(); + String name = template.getName(); + if (CodeTemplateContextType.CATCHBLOCK.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERSTUB.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.NEWTYPE.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.TYPECOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.FIELDCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.fieldcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.OVERRIDECOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERCOMMENT.equals(name)) { + return PreferencesMessages + .getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ + } + return template.getDescription(); + } + + } + + private final static int IDX_EDIT = 0; + + private final static int IDX_IMPORT = 2; + + private final static int IDX_EXPORT = 3; + + private final static int IDX_EXPORTALL = 4; + + protected final static Object COMMENT_NODE = PreferencesMessages + .getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ + + protected final static Object CODE_NODE = PreferencesMessages + .getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ + + private static final String PREF_JAVADOC_STUBS = PreferenceConstants.CODEGEN_ADD_COMMENTS; + + private TreeListDialogField fCodeTemplateTree; + + private SelectionButtonDialogField fCreateJavaDocComments; + + protected TemplateStore fTemplates; + + private PixelConverter fPixelConverter; + + private SourceViewer fPatternViewer; + + private Control fSWTWidget; + + private TemplateVariableProcessor fTemplateProcessor; + + public CodeTemplateBlock() { + + fTemplates = PHPeclipsePlugin.getDefault().getCodeTemplateStore(); + fTemplateProcessor = new TemplateVariableProcessor(); + + CodeTemplateAdapter adapter = new CodeTemplateAdapter(); + + String[] buttonLabels = new String[] { + /* IDX_EDIT */PreferencesMessages + .getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ + /* */null, + /* IDX_IMPORT */PreferencesMessages + .getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ + /* IDX_EXPORT */PreferencesMessages + .getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ + /* IDX_EXPORTALL */PreferencesMessages + .getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ + + }; + fCodeTemplateTree = new TreeListDialogField(adapter, buttonLabels, + new CodeTemplateLabelProvider()); + fCodeTemplateTree.setDialogFieldListener(adapter); + fCodeTemplateTree.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ + + fCodeTemplateTree.enableButton(IDX_EXPORT, false); + fCodeTemplateTree.enableButton(IDX_EDIT, false); + + fCodeTemplateTree.addElement(COMMENT_NODE); + fCodeTemplateTree.addElement(CODE_NODE); + + fCreateJavaDocComments = new SelectionButtonDialogField(SWT.CHECK + | SWT.WRAP); + fCreateJavaDocComments.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ + fCreateJavaDocComments.setSelection(PreferenceConstants + .getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); + + fCodeTemplateTree.selectFirstElement(); + } + + protected Control createContents(Composite parent) { + fPixelConverter = new PixelConverter(parent); + fSWTWidget = parent; + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + composite.setLayout(layout); + + fCodeTemplateTree.doFillIntoGrid(composite, 3); + LayoutUtil + .setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); + LayoutUtil + .setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); + + fPatternViewer = createViewer(composite, 2); + + fCreateJavaDocComments.doFillIntoGrid(composite, 2); + + DialogField label = new DialogField(); + label.setLabelText(PreferencesMessages + .getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ + label.doFillIntoGrid(composite, 2); + + return composite; + + } + + private Shell getShell() { + if (fSWTWidget != null) { + return fSWTWidget.getShell(); + } + return PHPeclipsePlugin.getActiveWorkbenchShell(); + } + + private SourceViewer createViewer(Composite parent, int nColumns) { + Label label = new Label(parent, SWT.NONE); + label.setText(PreferencesMessages + .getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ + GridData data = new GridData(); + data.horizontalSpan = nColumns; + label.setLayoutData(data); + + IDocument document = new Document(); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, + SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( + tools.getColorManager(), store, null, fTemplateProcessor); + viewer.configure(configuration); + viewer.setEditable(false); + viewer.setDocument(document); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + viewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(viewer, configuration, store); + + Control control = viewer.getControl(); + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + data.horizontalSpan = nColumns; + data.heightHint = fPixelConverter.convertHeightInCharsToPixels(5); + control.setLayoutData(data); + + return viewer; + } + + protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) { + ArrayList res = new ArrayList(); + TemplatePersistenceData[] templates = fTemplates.getTemplateData(false); + for (int i = 0; i < templates.length; i++) { + TemplatePersistenceData curr = templates[i]; + if (isComment == curr.getTemplate().getName().endsWith( + CodeTemplateContextType.COMMENT_SUFFIX)) { + res.add(curr); + } + } + return (TemplatePersistenceData[]) res + .toArray(new TemplatePersistenceData[res.size()]); + } + + protected static boolean canEdit(List selected) { + return selected.size() == 1 + && (selected.get(0) instanceof TemplatePersistenceData); + } + + protected void updateSourceViewerInput(List selection) { + if (fPatternViewer == null + || fPatternViewer.getTextWidget().isDisposed()) { + return; + } + if (selection.size() == 1 + && selection.get(0) instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) selection + .get(0); + Template template = data.getTemplate(); + TemplateContextType type = PHPeclipsePlugin.getDefault() + .getCodeTemplateContextRegistry().getContextType( + template.getContextTypeId()); + fTemplateProcessor.setContextType(type); + fPatternViewer.getDocument().set(template.getPattern()); + } else { + fPatternViewer.getDocument().set(""); //$NON-NLS-1$ + } + } + + protected void doButtonPressed(int buttonIndex, List selected) { + if (buttonIndex == IDX_EDIT) { + edit((TemplatePersistenceData) selected.get(0)); + } else if (buttonIndex == IDX_EXPORT) { + export(selected); + } else if (buttonIndex == IDX_EXPORTALL) { + exportAll(); + } else if (buttonIndex == IDX_IMPORT) { + import_(); + } + } + + private void edit(TemplatePersistenceData data) { + Template newTemplate = new Template(data.getTemplate()); + EditTemplateDialog dialog = new EditTemplateDialog(getShell(), + newTemplate, true, false, PHPeclipsePlugin.getDefault() + .getCodeTemplateContextRegistry()); + if (dialog.open() == Window.OK) { + // changed + data.setTemplate(newTemplate); + fCodeTemplateTree.refresh(data); + fCodeTemplateTree.selectElements(new StructuredSelection(data)); + } + } + + private void import_() { + FileDialog dialog = new FileDialog(getShell()); + dialog.setText(PreferencesMessages + .getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages + .getString("CodeTemplateBlock.import.extension") }); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + try { + TemplateReaderWriter reader = new TemplateReaderWriter(); + File file = new File(path); + if (file.exists()) { + InputStream input = new BufferedInputStream( + new FileInputStream(file)); + TemplatePersistenceData[] datas = reader.read(input, null); + for (int i = 0; i < datas.length; i++) { + updateTemplate(datas[i]); + } + } + + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + + } catch (FileNotFoundException e) { + openReadErrorDialog(e); + } catch (IOException e) { + openReadErrorDialog(e); + } + + } + + private void updateTemplate(TemplatePersistenceData data) { + TemplatePersistenceData[] datas = fTemplates.getTemplateData(true); + for (int i = 0; i < datas.length; i++) { + String id = datas[i].getId(); + if (id != null && id.equals(data.getId())) { + datas[i].setTemplate(data.getTemplate()); + break; + } + } + } + + private void exportAll() { + export(fTemplates.getTemplateData(false)); + } + + private void export(List selected) { + List datas = new ArrayList(); + for (int i = 0; i < selected.size(); i++) { + Object curr = selected.get(i); + if (curr instanceof TemplatePersistenceData) { + datas.add(curr); + } else { + TemplatePersistenceData[] cat = getTemplateOfCategory(curr == COMMENT_NODE); + datas.addAll(Arrays.asList(cat)); + } + } + export((TemplatePersistenceData[]) datas + .toArray(new TemplatePersistenceData[datas.size()])); + } + + private void export(TemplatePersistenceData[] templates) { + FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); + dialog + .setText(PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.title", String.valueOf(templates.length))); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages + .getString("CodeTemplateBlock.export.extension") }); //$NON-NLS-1$ + dialog.setFileName(PreferencesMessages + .getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + File file = new File(path); + + if (file.isHidden()) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (file.exists() && !file.canWrite()) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (!file.exists() || confirmOverwrite(file)) { + try { + OutputStream output = new BufferedOutputStream( + new FileOutputStream(file)); + TemplateReaderWriter writer = new TemplateReaderWriter(); + writer.save(templates, output); + } catch (IOException e) { + openWriteErrorDialog(e); + } + } + + } + + private boolean confirmOverwrite(File file) { + return MessageDialog + .openQuestion( + getShell(), + PreferencesMessages + .getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ + PreferencesMessages + .getFormattedString( + "CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ + } + + public void performDefaults() { + IPreferenceStore prefs = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + fCreateJavaDocComments.setSelection(prefs + .getDefaultBoolean(PREF_JAVADOC_STUBS)); + + fTemplates.restoreDefaults(); + + // refresh + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + } + + public boolean performOk(boolean enabled) { + IPreferenceStore prefs = PreferenceConstants.getPreferenceStore(); + prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + + try { + fTemplates.save(); + } catch (IOException e) { + PHPeclipsePlugin.log(e); + openWriteErrorDialog(e); + } + return true; + } + + public void performCancel() { + try { + fTemplates.load(); + } catch (IOException e) { + openReadErrorDialog(e); + } + } + + private void openReadErrorDialog(Exception e) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ + + String message = e.getLocalizedMessage(); + if (message != null) + message = PreferencesMessages.getFormattedString( + "CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ + else + message = PreferencesMessages + .getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } + + private void openWriteErrorDialog(Exception e) { + String title = PreferencesMessages + .getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ + String message = PreferencesMessages + .getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java new file mode 100644 index 0000000..822f445 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/* + * The page to configure the code formatter options. + */ +public class CodeTemplatePreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { + + private CodeTemplateBlock fCodeTemplateConfigurationBlock; + + public CodeTemplatePreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + // setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); + // //$NON-NLS-1$ + + // only used when page is shown programatically + setTitle(PreferencesMessages + .getString("CodeTemplatesPreferencePage.title")); //$NON-NLS-1$ + + fCodeTemplateConfigurationBlock = new CodeTemplateBlock(); + } + + /* + * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + Control composite = fCodeTemplateConfigurationBlock + .createContents(parent); + Dialog.applyDialogFont(composite); + return composite; + } + + /* + * @see IPreferencePage#performOk() + */ + public boolean performOk() { + if (!fCodeTemplateConfigurationBlock.performOk(true)) { + return false; + } + return super.performOk(); + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fCodeTemplateConfigurationBlock.performDefaults(); + super.performDefaults(); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.preference.IPreferencePage#performCancel() + */ + public boolean performCancel() { + fCodeTemplateConfigurationBlock.performCancel(); + + return super.performCancel(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorEditor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/ColorSettingPreviewCode.txt b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorSettingPreviewCode.txt similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/ColorSettingPreviewCode.txt rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/ColorSettingPreviewCode.txt diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java new file mode 100644 index 0000000..bcc2c91 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPreferencePage.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/* + * The page to configure the compiler options. + */ +public class CompilerPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { + + private CompilerConfigurationBlock fConfigurationBlock; + + public CompilerPreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PreferencesMessages + .getString("CompilerPreferencePage.description")); //$NON-NLS-1$ + + // only used when page is shown programatically + setTitle(PreferencesMessages.getString("CompilerPreferencePage.title")); //$NON-NLS-1$ + + fConfigurationBlock = new CompilerConfigurationBlock(this, null); + } + + /* + * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + Control result = fConfigurationBlock.createContents(parent); + Dialog.applyDialogFont(result); + return result; + } + + /* + * @see IPreferencePage#performOk() + */ + public boolean performOk() { + if (!fConfigurationBlock.performOk(true)) { + return false; + } + return super.performOk(); + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fConfigurationBlock.performDefaults(); + super.performDefaults(); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CompilerPropertyPage.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java new file mode 100644 index 0000000..d8e8299 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditTemplateDialog.java @@ -0,0 +1,637 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusDialog; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; +import net.sourceforge.phpdt.internal.ui.util.SWTUtil; +import net.sourceforge.phpdt.ui.IContextMenuConstants; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.GroupMarker; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.IMenuListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextListener; +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.TextEvent; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.templates.ContextTypeRegistry; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.custom.VerifyKeyListener; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +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.events.VerifyEvent; +import org.eclipse.swt.graphics.Font; +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.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Widget; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.texteditor.ITextEditorActionConstants; +import org.eclipse.ui.texteditor.IUpdate; + +/** + * Dialog to edit a template. + */ +public class EditTemplateDialog extends StatusDialog { + + private static class TextViewerAction extends Action implements IUpdate { + + private int fOperationCode = -1; + + private ITextOperationTarget fOperationTarget; + + /** + * Creates a new action. + * + * @param viewer + * the viewer + * @param operationCode + * the opcode + */ + public TextViewerAction(ITextViewer viewer, int operationCode) { + fOperationCode = operationCode; + fOperationTarget = viewer.getTextOperationTarget(); + update(); + } + + /** + * Updates the enabled state of the action. Fires a property change if + * the enabled state changes. + * + * @see Action#firePropertyChange(String, Object, Object) + */ + public void update() { + + boolean wasEnabled = isEnabled(); + boolean isEnabled = (fOperationTarget != null && fOperationTarget + .canDoOperation(fOperationCode)); + setEnabled(isEnabled); + + if (wasEnabled != isEnabled) { + firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE + : Boolean.FALSE, isEnabled ? Boolean.TRUE + : Boolean.FALSE); + } + } + + /** + * @see Action#run() + */ + public void run() { + if (fOperationCode != -1 && fOperationTarget != null) { + fOperationTarget.doOperation(fOperationCode); + } + } + } + + private final Template fTemplate; + + private Text fNameText; + + private Text fDescriptionText; + + private Combo fContextCombo; + + private SourceViewer fPatternEditor; + + private Button fInsertVariableButton; + + private boolean fIsNameModifiable; + + private StatusInfo fValidationStatus; + + private boolean fSuppressError = true; // #4354 + + private Map fGlobalActions = new HashMap(10); + + private List fSelectionActions = new ArrayList(3); + + private String[][] fContextTypes; + + private ContextTypeRegistry fContextTypeRegistry; + + private final TemplateVariableProcessor fTemplateProcessor = new TemplateVariableProcessor(); + + /** + * Creates a new dialog. + * + * @param parent + * the shell parent of the dialog + * @param template + * the template to edit + * @param edit + * whether this is a new template or an existing being edited + * @param isNameModifiable + * whether the name of the template may be modified + * @param registry + * the context type registry to use + */ + public EditTemplateDialog(Shell parent, Template template, boolean edit, + boolean isNameModifiable, ContextTypeRegistry registry) { + super(parent); + + setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); + + String title = edit ? PreferencesMessages + .getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ + : PreferencesMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ + setTitle(title); + + fTemplate = template; + fIsNameModifiable = isNameModifiable; + + // XXX workaround for bug 63313 - disabling prefix until fixed. + // String delim= new Document().getLegalLineDelimiters()[0]; + + List contexts = new ArrayList(); + for (Iterator it = registry.contextTypes(); it.hasNext();) { + TemplateContextType type = (TemplateContextType) it.next(); + // if (type.getId().equals("javadoc")) //$NON-NLS-1$ + // contexts.add(new String[] { type.getId(), type.getName(), "/**" + + // delim }); //$NON-NLS-1$ + // else + contexts.add(new String[] { type.getId(), type.getName(), "" }); //$NON-NLS-1$ + } + fContextTypes = (String[][]) contexts.toArray(new String[contexts + .size()][]); + + fValidationStatus = new StatusInfo(); + + fContextTypeRegistry = registry; + + TemplateContextType type = fContextTypeRegistry.getContextType(template + .getContextTypeId()); + fTemplateProcessor.setContextType(type); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.dialogs.StatusDialog#create() + */ + public void create() { + super.create(); + // update initial ok button to be disabled for new templates + boolean valid = fNameText == null + || fNameText.getText().trim().length() != 0; + if (!valid) { + StatusInfo status = new StatusInfo(); + status.setError(PreferencesMessages + .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ + updateButtonsEnableState(status); + } + } + + /* + * @see Dialog#createDialogArea(Composite) + */ + protected Control createDialogArea(Composite ancestor) { + Composite parent = new Composite(ancestor, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + parent.setLayout(layout); + parent.setLayoutData(new GridData(GridData.FILL_BOTH)); + + ModifyListener listener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + doTextWidgetChanged(e.widget); + } + }; + + if (fIsNameModifiable) { + createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.name")); //$NON-NLS-1$ + + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + layout = new GridLayout(); + layout.numColumns = 3; + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + fNameText = createText(composite); + fNameText.addFocusListener(new FocusListener() { + + public void focusGained(FocusEvent e) { + } + + public void focusLost(FocusEvent e) { + if (fSuppressError) { + fSuppressError = false; + updateButtons(); + } + } + }); + + createLabel(composite, PreferencesMessages + .getString("EditTemplateDialog.context")); //$NON-NLS-1$ + fContextCombo = new Combo(composite, SWT.READ_ONLY); + + for (int i = 0; i < fContextTypes.length; i++) { + fContextCombo.add(fContextTypes[i][1]); + } + + fContextCombo.addModifyListener(listener); + } + + createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.description")); //$NON-NLS-1$ + + int descFlags = fIsNameModifiable ? SWT.BORDER : SWT.BORDER + | SWT.READ_ONLY; + fDescriptionText = new Text(parent, descFlags); + fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + fDescriptionText.addModifyListener(listener); + + Label patternLabel = createLabel(parent, PreferencesMessages + .getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ + patternLabel.setLayoutData(new GridData( + GridData.VERTICAL_ALIGN_BEGINNING)); + fPatternEditor = createEditor(parent); + + Label filler = new Label(parent, SWT.NONE); + filler.setLayoutData(new GridData()); + + Composite composite = new Composite(parent, SWT.NONE); + layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + composite.setLayoutData(new GridData()); + + fInsertVariableButton = new Button(composite, SWT.NONE); + fInsertVariableButton + .setLayoutData(getButtonGridData(fInsertVariableButton)); + fInsertVariableButton.setText(PreferencesMessages + .getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ + fInsertVariableButton.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + fPatternEditor.getTextWidget().setFocus(); + fPatternEditor + .doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + fDescriptionText.setText(fTemplate.getDescription()); + if (fIsNameModifiable) { + fNameText.setText(fTemplate.getName()); + fNameText.addModifyListener(listener); + fContextCombo.select(getIndex(fTemplate.getContextTypeId())); + } else { + fPatternEditor.getControl().setFocus(); + } + initializeActions(); + + applyDialogFont(parent); + return composite; + } + + protected void doTextWidgetChanged(Widget w) { + if (w == fNameText) { + fSuppressError = false; + String name = fNameText.getText(); + fTemplate.setName(name); + updateButtons(); + } else if (w == fContextCombo) { + String name = fContextCombo.getText(); + String contextId = getContextId(name); + fTemplate.setContextTypeId(contextId); + fTemplateProcessor.setContextType(fContextTypeRegistry + .getContextType(contextId)); + } else if (w == fDescriptionText) { + String desc = fDescriptionText.getText(); + fTemplate.setDescription(desc); + } + } + + private String getContextId(String name) { + if (name == null) + return name; + + for (int i = 0; i < fContextTypes.length; i++) { + if (name.equals(fContextTypes[i][1])) { + return fContextTypes[i][0]; + } + } + return name; + } + + protected void doSourceChanged(IDocument document) { + String text = document.get(); + String prefix = getPrefix(); + fTemplate.setPattern(text.substring(prefix.length(), text.length())); + fValidationStatus.setOK(); + TemplateContextType contextType = fContextTypeRegistry + .getContextType(fTemplate.getContextTypeId()); + if (contextType != null) { + try { + contextType.validate(text); + } catch (TemplateException e) { + fValidationStatus.setError(e.getLocalizedMessage()); + } + } + + updateUndoAction(); + updateButtons(); + } + + private static GridData getButtonGridData(Button button) { + GridData data = new GridData(GridData.FILL_HORIZONTAL); + data.heightHint = SWTUtil.getButtonHeightHint(button); + + return data; + } + + private static Label createLabel(Composite parent, String name) { + Label label = new Label(parent, SWT.NULL); + label.setText(name); + label.setLayoutData(new GridData()); + + return label; + } + + private static Text createText(Composite parent) { + Text text = new Text(parent, SWT.BORDER); + text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + return text; + } + + private SourceViewer createEditor(Composite parent) { + String prefix = getPrefix(); + IDocument document = new Document(prefix + fTemplate.getPattern()); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, + SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( + tools.getColorManager(), store, null, fTemplateProcessor); + viewer.configure(configuration); + viewer.setEditable(true); + // XXX workaround for bug 63313 - disabling prefix until fixed. + // viewer.setDocument(document, prefix.length(), document.getLength() - + // prefix.length()); + viewer.setDocument(document); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + viewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(viewer, configuration, store); + + int nLines = document.getNumberOfLines(); + if (nLines < 5) { + nLines = 5; + } else if (nLines > 12) { + nLines = 12; + } + + Control control = viewer.getControl(); + GridData data = new GridData(GridData.FILL_BOTH); + data.widthHint = convertWidthInCharsToPixels(80); + data.heightHint = convertHeightInCharsToPixels(nLines); + control.setLayoutData(data); + + viewer.addTextListener(new ITextListener() { + public void textChanged(TextEvent event) { + if (event.getDocumentEvent() != null) + doSourceChanged(event.getDocumentEvent().getDocument()); + } + }); + + viewer.addSelectionChangedListener(new ISelectionChangedListener() { + public void selectionChanged(SelectionChangedEvent event) { + updateSelectionDependentActions(); + } + }); + + viewer.prependVerifyKeyListener(new VerifyKeyListener() { + public void verifyKey(VerifyEvent event) { + handleVerifyKeyPressed(event); + } + }); + + return viewer; + } + + private String getPrefix() { + String prefix; + int idx = getIndex(fTemplate.getContextTypeId()); + if (idx != -1) + prefix = fContextTypes[idx][2]; + else + prefix = ""; //$NON-NLS-1$ + + return prefix; + } + + private void handleVerifyKeyPressed(VerifyEvent event) { + if (!event.doit) + return; + + if (event.stateMask != SWT.MOD1) + return; + + switch (event.character) { + case ' ': + fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); + event.doit = false; + break; + + // CTRL-Z + case 'z' - 'a' + 1: + fPatternEditor.doOperation(ITextOperationTarget.UNDO); + event.doit = false; + break; + } + } + + private void initializeActions() { + TextViewerAction action = new TextViewerAction(fPatternEditor, + SourceViewer.UNDO); + action + .setText(PreferencesMessages + .getString("EditTemplateDialog.undo")); //$NON-NLS-1$ + fGlobalActions.put(ITextEditorActionConstants.UNDO, action); + + action = new TextViewerAction(fPatternEditor, SourceViewer.CUT); + action.setText(PreferencesMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ + fGlobalActions.put(ITextEditorActionConstants.CUT, action); + + action = new TextViewerAction(fPatternEditor, SourceViewer.COPY); + action + .setText(PreferencesMessages + .getString("EditTemplateDialog.copy")); //$NON-NLS-1$ + fGlobalActions.put(ITextEditorActionConstants.COPY, action); + + action = new TextViewerAction(fPatternEditor, SourceViewer.PASTE); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.paste")); //$NON-NLS-1$ + fGlobalActions.put(ITextEditorActionConstants.PASTE, action); + + action = new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ + fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); + + action = new TextViewerAction(fPatternEditor, + SourceViewer.CONTENTASSIST_PROPOSALS); + action.setText(PreferencesMessages + .getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ + fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ + + fSelectionActions.add(ITextEditorActionConstants.CUT); + fSelectionActions.add(ITextEditorActionConstants.COPY); + fSelectionActions.add(ITextEditorActionConstants.PASTE); + + // create context menu + MenuManager manager = new MenuManager(null, null); + manager.setRemoveAllWhenShown(true); + manager.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager mgr) { + fillContextMenu(mgr); + } + }); + + StyledText text = fPatternEditor.getTextWidget(); + Menu menu = manager.createContextMenu(text); + text.setMenu(menu); + } + + private void fillContextMenu(IMenuManager menu) { + menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, + (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); + + menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, + (IAction) fGlobalActions + .get(ITextEditorActionConstants.SELECT_ALL)); + + menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); + menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, + (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ + } + + protected void updateSelectionDependentActions() { + Iterator iterator = fSelectionActions.iterator(); + while (iterator.hasNext()) + updateAction((String) iterator.next()); + } + + protected void updateUndoAction() { + IAction action = (IAction) fGlobalActions + .get(ITextEditorActionConstants.UNDO); + if (action instanceof IUpdate) + ((IUpdate) action).update(); + } + + protected void updateAction(String actionId) { + IAction action = (IAction) fGlobalActions.get(actionId); + if (action instanceof IUpdate) + ((IUpdate) action).update(); + } + + private int getIndex(String contextid) { + + if (contextid == null) + return -1; + + for (int i = 0; i < fContextTypes.length; i++) { + if (contextid.equals(fContextTypes[i][0])) { + return i; + } + } + return -1; + } + + protected void okPressed() { + super.okPressed(); + } + + private void updateButtons() { + StatusInfo status; + + boolean valid = fNameText == null + || fNameText.getText().trim().length() != 0; + if (!valid) { + status = new StatusInfo(); + if (!fSuppressError) { + status.setError(PreferencesMessages + .getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ + } + } else { + status = fValidationStatus; + } + updateStatus(status); + } + + /* + * @see org.eclipse.jface.window.Window#configureShell(Shell) + */ + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, + IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditorConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditorConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/EditorConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditorConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java new file mode 100644 index 0000000..c93b9cc --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/EditorPreferencePage.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/** + * Preference page for spell checking preferences. + * + * @since 3.0 + */ +public class EditorPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { + + /** The spelling configuration block */ + private final EditorConfigurationBlock fBlock = new EditorConfigurationBlock( + this, null); + + /** + * Creates a new spelling preference page. + */ + public EditorPreferencePage() { + + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PreferencesMessages + .getString("EditorPreferencePage.description")); //$NON-NLS-1$ + setTitle(PreferencesMessages.getString("EditorPreferencePage.title")); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) + */ + protected Control createContents(final Composite parent) { + + final Control control = fBlock.createContents(parent); + Dialog.applyDialogFont(control); + + return control; + } + + /* + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(final Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + } + + /* + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(final IWorkbench workbench) { + // Do nothing + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + fBlock.performDefaults(); + + super.performDefaults(); + } + + /* + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + + if (!fBlock.performOk(true)) + return false; + + return super.performOk(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(final IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + + StatusUtil.applyToStatusLine(this, status); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java new file mode 100644 index 0000000..cac7948 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/FoldingConfigurationBlock.java @@ -0,0 +1,399 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderDescriptor; +import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry; +import net.sourceforge.phpdt.internal.ui.util.PixelConverter; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StackLayout; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +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.Control; +import org.eclipse.swt.widgets.Label; + +/** + * Configures Java Editor folding preferences. + * + * @since 3.0 + */ +class FoldingConfigurationBlock { + + private static class ErrorPreferences implements + IJavaFoldingPreferenceBlock { + private String fMessage; + + protected ErrorPreferences(String message) { + fMessage = message; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) + */ + public Control createControl(Composite composite) { + Composite inner = new Composite(composite, SWT.NONE); + inner.setLayout(new FillLayout(SWT.VERTICAL)); + + Label label = new Label(inner, SWT.CENTER); + label.setText(fMessage); + + return inner; + } + + public void initialize() { + } + + public void performOk() { + } + + public void performDefaults() { + } + + public void dispose() { + } + + } + + /** The overlay preference store. */ + private final OverlayPreferenceStore fStore; + + /* The controls */ + private Combo fProviderCombo; + + private Button fFoldingCheckbox; + + private ComboViewer fProviderViewer; + + private Map fProviderDescriptors; + + private Composite fGroup; + + private Map fProviderPreferences; + + private Map fProviderControls; + + private StackLayout fStackLayout; + + public FoldingConfigurationBlock(OverlayPreferenceStore store) { + Assert.isNotNull(store); + fStore = store; + fStore.addKeys(createOverlayStoreKeys()); + fProviderDescriptors = createListModel(); + fProviderPreferences = new HashMap(); + fProviderControls = new HashMap(); + } + + private Map createListModel() { + JavaFoldingStructureProviderRegistry reg = PHPeclipsePlugin + .getDefault().getFoldingStructureProviderRegistry(); + reg.reloadExtensions(); + JavaFoldingStructureProviderDescriptor[] descs = reg + .getFoldingProviderDescriptors(); + Map map = new HashMap(); + for (int i = 0; i < descs.length; i++) { + map.put(descs[i].getId(), descs[i]); + } + return map; + } + + private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { + + ArrayList overlayKeys = new ArrayList(); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_ENABLED)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FOLDING_PROVIDER)); + + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; + overlayKeys.toArray(keys); + return keys; + } + + /** + * Creates page for folding preferences. + * + * @param parent + * the parent composite + * @return the control for the preference page + */ + Control createControl(Composite parent) { + + Composite composite = new Composite(parent, SWT.NULL); + // assume parent page uses griddata + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_CENTER + | GridData.VERTICAL_ALIGN_FILL); + composite.setLayoutData(gd); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + PixelConverter pc = new PixelConverter(composite); + layout.verticalSpacing = pc.convertHeightInCharsToPixels(1) / 2; + composite.setLayout(layout); + + /* check box for new editors */ + fFoldingCheckbox = new Button(composite, SWT.CHECK); + fFoldingCheckbox.setText(PreferencesMessages + .getString("FoldingConfigurationBlock.enable")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING); + fFoldingCheckbox.setLayoutData(gd); + fFoldingCheckbox.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean enabled = fFoldingCheckbox.getSelection(); + fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, + enabled); + updateCheckboxDependencies(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + Label label = new Label(composite, SWT.CENTER); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); + label.setLayoutData(gd); + + /* list */ + Composite comboComp = new Composite(composite, SWT.NONE); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); + GridLayout gridLayout = new GridLayout(2, false); + gridLayout.marginWidth = 0; + comboComp.setLayout(gridLayout); + + Label comboLabel = new Label(comboComp, SWT.CENTER); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_CENTER); + comboLabel.setLayoutData(gd); + comboLabel.setText(PreferencesMessages + .getString("FoldingConfigurationBlock.combo_caption")); //$NON-NLS-1$ + + label = new Label(composite, SWT.CENTER); + gd = new GridData(GridData.FILL_HORIZONTAL + | GridData.VERTICAL_ALIGN_BEGINNING); + label.setLayoutData(gd); + + fProviderCombo = new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN); + gd = new GridData(GridData.HORIZONTAL_ALIGN_END + | GridData.VERTICAL_ALIGN_CENTER); + fProviderCombo.setLayoutData(gd); + + /* list viewer */ + fProviderViewer = new ComboViewer(fProviderCombo); + fProviderViewer.setContentProvider(new IStructuredContentProvider() { + + /* + * @see org.eclipse.jface.viewers.IContentProvider#dispose() + */ + public void dispose() { + } + + /* + * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, + * java.lang.Object, java.lang.Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, + Object newInput) { + } + + /* + * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) + */ + public Object[] getElements(Object inputElement) { + return fProviderDescriptors.values().toArray(); + } + }); + fProviderViewer.setLabelProvider(new LabelProvider() { + /* + * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + return null; + } + + /* + * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + return ((JavaFoldingStructureProviderDescriptor) element) + .getName(); + } + }); + fProviderViewer + .addSelectionChangedListener(new ISelectionChangedListener() { + + public void selectionChanged(SelectionChangedEvent event) { + IStructuredSelection sel = (IStructuredSelection) event + .getSelection(); + if (!sel.isEmpty()) { + fStore + .setValue( + PreferenceConstants.EDITOR_FOLDING_PROVIDER, + ((JavaFoldingStructureProviderDescriptor) sel + .getFirstElement()).getId()); + updateListDependencies(); + } + } + }); + fProviderViewer.setInput(fProviderDescriptors); + fProviderViewer.refresh(); + + Composite groupComp = new Composite(composite, SWT.NONE); + gd = new GridData(GridData.FILL_BOTH); + gd.horizontalSpan = 2; + groupComp.setLayoutData(gd); + gridLayout = new GridLayout(1, false); + gridLayout.marginWidth = 0; + groupComp.setLayout(gridLayout); + + /* contributed provider preferences. */ + fGroup = new Composite(groupComp, SWT.NONE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING); + fGroup.setLayoutData(gd); + fStackLayout = new StackLayout(); + fGroup.setLayout(fStackLayout); + + return composite; + } + + private void updateCheckboxDependencies() { + } + + void updateListDependencies() { + String id = fStore + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + JavaFoldingStructureProviderDescriptor desc = (JavaFoldingStructureProviderDescriptor) fProviderDescriptors + .get(id); + IJavaFoldingPreferenceBlock prefs; + + if (desc == null) { + // safety in case there is no such descriptor + String message = PreferencesMessages + .getString("FoldingConfigurationBlock.error.not_exist"); //$NON-NLS-1$ + PHPeclipsePlugin.log(new Status(IStatus.WARNING, PHPeclipsePlugin + .getPluginId(), IStatus.OK, message, null)); + prefs = new ErrorPreferences(message); + } else { + prefs = (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id); + if (prefs == null) { + try { + prefs = desc.createPreferences(); + fProviderPreferences.put(id, prefs); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + prefs = new ErrorPreferences(e.getLocalizedMessage()); + } + } + } + + Control control = (Control) fProviderControls.get(id); + if (control == null) { + control = prefs.createControl(fGroup); + if (control == null) { + String message = PreferencesMessages + .getString("FoldingConfigurationBlock.info.no_preferences"); //$NON-NLS-1$ + control = new ErrorPreferences(message).createControl(fGroup); + } else { + fProviderControls.put(id, control); + } + } + fStackLayout.topControl = control; + control.pack(); + fGroup.layout(); + fGroup.getParent().layout(); + + prefs.initialize(); + } + + void initialize() { + restoreFromPreferences(); + } + + void performOk() { + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); + prefs.performOk(); + } + } + + void performDefaults() { + restoreFromPreferences(); + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); + prefs.performDefaults(); + } + } + + void dispose() { + for (Iterator it = fProviderPreferences.values().iterator(); it + .hasNext();) { + IJavaFoldingPreferenceBlock prefs = (IJavaFoldingPreferenceBlock) it + .next(); + prefs.dispose(); + } + } + + private void restoreFromPreferences() { + boolean enabled = fStore + .getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); + fFoldingCheckbox.setSelection(enabled); + updateCheckboxDependencies(); + + String id = fStore + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + Object provider = fProviderDescriptors.get(id); + if (provider != null) { + fProviderViewer.setSelection(new StructuredSelection(provider), + true); + updateListDependencies(); + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/IPreferenceConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java new file mode 100644 index 0000000..5af3fbf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java @@ -0,0 +1,481 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.HashMap; +import java.util.StringTokenizer; + +import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; +import net.sourceforge.phpdt.internal.ui.util.PixelConverter; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +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.graphics.Point; +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.List; +import org.eclipse.swt.widgets.Text; + +/** + * Configures Java Editor hover preferences. + * + * @since 2.1 + */ +class JavaEditorHoverConfigurationBlock { + + private static final String DELIMITER = PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.delimiter"); //$NON-NLS-1$ + + // Data structure to hold the values which are edited by the user + private static class HoverConfig { + + private String fModifierString; + + private boolean fIsEnabled; + + private int fStateMask; + + private HoverConfig(String modifier, int stateMask, boolean enabled) { + fModifierString = modifier; + fIsEnabled = enabled; + fStateMask = stateMask; + } + } + + private IPreferenceStore fStore; + + private HoverConfig[] fHoverConfigs; + + private Text fModifierEditor; + + private Button fEnableField; + + private List fHoverList; + + private Text fDescription; + + private Button fShowHoverAffordanceCheckbox; + + private JavaEditorPreferencePage fMainPreferencePage; + + private StatusInfo fStatus; + + public JavaEditorHoverConfigurationBlock( + JavaEditorPreferencePage mainPreferencePage, IPreferenceStore store) { + Assert.isNotNull(mainPreferencePage); + Assert.isNotNull(store); + fMainPreferencePage = mainPreferencePage; + fStore = store; + } + + /** + * Creates page for hover preferences. + */ + public Control createControl(Composite parent) { + + PixelConverter pixelConverter = new PixelConverter(parent); + + Composite hoverComposite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + hoverComposite.setLayout(layout); + GridData gd = new GridData(GridData.GRAB_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); + hoverComposite.setLayoutData(gd); + + Label label = new Label(hoverComposite, SWT.NONE); + label + .setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.hoverPreferences")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + label.setLayoutData(gd); + gd = new GridData(GridData.GRAB_HORIZONTAL + | GridData.VERTICAL_ALIGN_FILL); + + // Hover list + fHoverList = new List(hoverComposite, SWT.SINGLE | SWT.V_SCROLL + | SWT.BORDER); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL); + int listHeight = 10 * fHoverList.getItemHeight(); + gd.heightHint = listHeight; + fHoverList.setLayoutData(gd); + fHoverList.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + handleHoverListSelection(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + Composite stylesComposite = new Composite(hoverComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.heightHint = listHeight + (2 * fHoverList.getBorderWidth()); + stylesComposite.setLayoutData(gd); + + // Enabled checkbox + fEnableField = new Button(stylesComposite, SWT.CHECK); + fEnableField.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.enabled")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + fEnableField.setLayoutData(gd); + fEnableField.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + int i = fHoverList.getSelectionIndex(); + boolean state = fEnableField.getSelection(); + fModifierEditor.setEnabled(state); + fHoverConfigs[i].fIsEnabled = state; + handleModifierModified(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + + // Text field for modifier string + label = new Label(stylesComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.keyModifier")); //$NON-NLS-1$ + fModifierEditor = new Text(stylesComposite, SWT.BORDER); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + fModifierEditor.setLayoutData(gd); + + fModifierEditor.addKeyListener(new KeyListener() { + private boolean isModifierCandidate; + + public void keyPressed(KeyEvent e) { + isModifierCandidate = e.keyCode > 0 && e.character == 0 + && e.stateMask == 0; + } + + public void keyReleased(KeyEvent e) { + if (isModifierCandidate && e.stateMask > 0 + && e.stateMask == e.stateMask && e.character == 0) {// && + // e.time + // -time + // < + // 1000) + // { + String text = fModifierEditor.getText(); + Point selection = fModifierEditor.getSelection(); + int i = selection.x - 1; + while (i > -1 && Character.isWhitespace(text.charAt(i))) { + i--; + } + boolean needsPrefixDelimiter = i > -1 + && !String.valueOf(text.charAt(i)) + .equals(DELIMITER); + + i = selection.y; + while (i < text.length() + && Character.isWhitespace(text.charAt(i))) { + i++; + } + boolean needsPostfixDelimiter = i < text.length() + && !String.valueOf(text.charAt(i)) + .equals(DELIMITER); + + String insertString; + + if (needsPrefixDelimiter && needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPrefixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertDelimiterAndModifier", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.insertModifierAndDelimiter", new String[] { Action.findModifierString(e.stateMask) }); //$NON-NLS-1$ + else + insertString = Action.findModifierString(e.stateMask); + + if (insertString != null) + fModifierEditor.insert(insertString); + } + } + }); + + fModifierEditor.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + handleModifierModified(); + } + }); + + // Description + Label descriptionLabel = new Label(stylesComposite, SWT.LEFT); + descriptionLabel.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.description")); //$NON-NLS-1$ + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING); + gd.horizontalSpan = 2; + descriptionLabel.setLayoutData(gd); + fDescription = new Text(stylesComposite, SWT.LEFT | SWT.WRAP + | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.horizontalSpan = 2; + fDescription.setLayoutData(gd); + + // Vertical filler + Label filler = new Label(hoverComposite, SWT.LEFT); + gd = new GridData(GridData.BEGINNING | GridData.VERTICAL_ALIGN_FILL); + gd.heightHint = pixelConverter.convertHeightInCharsToPixels(1) / 3; + filler.setLayoutData(gd); + + // Affordance checkbox + fShowHoverAffordanceCheckbox = new Button(hoverComposite, SWT.CHECK); + fShowHoverAffordanceCheckbox.setText(PreferencesMessages + .getString("JavaEditorHoverConfigurationBlock.showAffordance")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = 0; + gd.horizontalSpan = 2; + fShowHoverAffordanceCheckbox.setLayoutData(gd); + + initialize(); + + Dialog.applyDialogFont(hoverComposite); + return hoverComposite; + } + + private JavaEditorTextHoverDescriptor[] getContributedHovers() { + return PHPeclipsePlugin.getDefault() + .getJavaEditorTextHoverDescriptors(); + } + + void initialize() { + JavaEditorTextHoverDescriptor[] hoverDescs = getContributedHovers(); + fHoverConfigs = new HoverConfig[hoverDescs.length]; + for (int i = 0; i < hoverDescs.length; i++) { + fHoverConfigs[i] = new HoverConfig(hoverDescs[i] + .getModifierString(), hoverDescs[i].getStateMask(), + hoverDescs[i].isEnabled()); + fHoverList.add(hoverDescs[i].getLabel()); + } + initializeFields(); + } + + void initializeFields() { + fHoverList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (fHoverList != null && !fHoverList.isDisposed()) { + fHoverList.select(0); + handleHoverListSelection(); + } + } + }); + fShowHoverAffordanceCheckbox + .setSelection(fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + } + + void performOk() { + StringBuffer buf = new StringBuffer(); + StringBuffer maskBuf = new StringBuffer(); + for (int i = 0; i < fHoverConfigs.length; i++) { + buf.append(getContributedHovers()[i].getId()); + buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + if (!fHoverConfigs[i].fIsEnabled) + buf.append(JavaEditorTextHoverDescriptor.DISABLED_TAG); + String modifier = fHoverConfigs[i].fModifierString; + if (modifier == null || modifier.length() == 0) + modifier = JavaEditorTextHoverDescriptor.NO_MODIFIER; + buf.append(modifier); + buf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + + maskBuf.append(getContributedHovers()[i].getId()); + maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + maskBuf.append(fHoverConfigs[i].fStateMask); + maskBuf.append(JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + } + fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, buf + .toString()); + fStore.setValue(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, + maskBuf.toString()); + + fStore.setValue(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, + fShowHoverAffordanceCheckbox.getSelection()); + + PHPeclipsePlugin.getDefault().resetJavaEditorTextHoverDescriptors(); + } + + void performDefaults() { + restoreFromPreferences(); + initializeFields(); + } + + private void restoreFromPreferences() { + + fShowHoverAffordanceCheckbox + .setSelection(fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + + String compiledTextHoverModifiers = fStore + .getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); + + StringTokenizer tokenizer = new StringTokenizer( + compiledTextHoverModifiers, + JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + HashMap idToModifier = new HashMap(tokenizer.countTokens() / 2); + + while (tokenizer.hasMoreTokens()) { + String id = tokenizer.nextToken(); + if (tokenizer.hasMoreTokens()) + idToModifier.put(id, tokenizer.nextToken()); + } + + String compiledTextHoverModifierMasks = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getString( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); + + tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, + JavaEditorTextHoverDescriptor.VALUE_SEPARATOR); + HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); + + while (tokenizer.hasMoreTokens()) { + String id = tokenizer.nextToken(); + if (tokenizer.hasMoreTokens()) + idToModifierMask.put(id, tokenizer.nextToken()); + } + + for (int i = 0; i < fHoverConfigs.length; i++) { + String modifierString = (String) idToModifier + .get(getContributedHovers()[i].getId()); + boolean enabled = true; + if (modifierString == null) + modifierString = JavaEditorTextHoverDescriptor.DISABLED_TAG; + + if (modifierString + .startsWith(JavaEditorTextHoverDescriptor.DISABLED_TAG)) { + enabled = false; + modifierString = modifierString.substring(1); + } + + if (modifierString + .equals(JavaEditorTextHoverDescriptor.NO_MODIFIER)) + modifierString = ""; //$NON-NLS-1$ + + fHoverConfigs[i].fModifierString = modifierString; + fHoverConfigs[i].fIsEnabled = enabled; + fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor + .computeStateMask(modifierString); + + if (fHoverConfigs[i].fStateMask == -1) { + try { + fHoverConfigs[i].fStateMask = Integer + .parseInt((String) idToModifierMask + .get(getContributedHovers()[i].getId())); + } catch (NumberFormatException ex) { + fHoverConfigs[i].fStateMask = -1; + } + } + } + } + + private void handleModifierModified() { + int i = fHoverList.getSelectionIndex(); + String modifiers = fModifierEditor.getText(); + fHoverConfigs[i].fModifierString = modifiers; + fHoverConfigs[i].fStateMask = JavaEditorTextHoverDescriptor + .computeStateMask(modifiers); + if (fHoverConfigs[i].fIsEnabled && fHoverConfigs[i].fStateMask == -1) + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.modifierIsNotValid", fHoverConfigs[i].fModifierString)); //$NON-NLS-1$ + else + fStatus = new StatusInfo(); + updateStatus(); + } + + private void handleHoverListSelection() { + int i = fHoverList.getSelectionIndex(); + boolean enabled = fHoverConfigs[i].fIsEnabled; + fEnableField.setSelection(enabled); + fModifierEditor.setEnabled(enabled); + fModifierEditor.setText(fHoverConfigs[i].fModifierString); + String description = getContributedHovers()[i].getDescription(); + if (description == null) + description = ""; //$NON-NLS-1$ + fDescription.setText(description); + } + + IStatus getStatus() { + if (fStatus == null) + fStatus = new StatusInfo(); + return fStatus; + } + + private void updateStatus() { + int i = 0; + HashMap stateMasks = new HashMap(fHoverConfigs.length); + while (fStatus.isOK() && i < fHoverConfigs.length) { + if (fHoverConfigs[i].fIsEnabled) { + String label = getContributedHovers()[i].getLabel(); + Integer stateMask = new Integer(fHoverConfigs[i].fStateMask); + if (fHoverConfigs[i].fStateMask == -1) + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover", new String[] { fHoverConfigs[i].fModifierString, label })); //$NON-NLS-1$ + else if (stateMasks.containsKey(stateMask)) + fStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorHoverConfigurationBlock.duplicateModifier", new String[] { label, (String) stateMasks.get(stateMask) })); //$NON-NLS-1$ + else + stateMasks.put(stateMask, label); + } + i++; + } + + if (fStatus.isOK()) + fMainPreferencePage.updateStatus(fStatus); + else { + fMainPreferencePage.setValid(false); + StatusUtil.applyToStatusLine(fMainPreferencePage, fStatus); + } + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java new file mode 100644 index 0000000..f6e9da8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaEditorPreferencePage.java @@ -0,0 +1,2049 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +//import java.text.Collator; +import java.util.ArrayList; +//import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +//import java.util.SortedSet; +import java.util.StringTokenizer; +//import java.util.TreeSet; + +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter; +import net.sourceforge.phpdt.internal.ui.util.TabFolderLayout; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.EditorUtility; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; +import net.sourceforge.phpeclipse.preferences.ColorEditor; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Preferences; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +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.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.layout.RowLayout; +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.Event; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Link; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.TabFolder; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.dialogs.PreferencesUtil; +import org.eclipse.ui.editors.text.EditorsUI; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.ChainedPreferenceStore; +import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; + + +/** + * The page for setting the editor options. + */ +public class JavaEditorPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + private static final String BOLD = PreferenceConstants.EDITOR_BOLD_SUFFIX; + + private static final String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; + + private static final String DELIMITER = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.delimiter"); //$NON-NLS-1$ + + /** The keys of the overlay store. */ + public final OverlayPreferenceStore.OverlayKey[] fKeys; + + private final String[][] fSyntaxColorListModel = new String[][] { + { + PreferencesMessages + .getString("JavaEditorPreferencePage.multiLineComment"), + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.singleLineComment"), + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, + //$NON-NLS-1$ + { PreferencesMessages.getString("JavaEditorPreferencePage.tags"), + PreferenceConstants.EDITOR_PHP_TAG_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.keywords"), + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, + { + PreferencesMessages + .getString("JavaEditorPreferencePage.functionNames"), + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.variables"), + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.variables_dollar"), + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.constants"), + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR }, + //$NON-NLS-1$ + { PreferencesMessages.getString("JavaEditorPreferencePage.types"), + PreferenceConstants.EDITOR_PHP_TYPE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.strings_dq"), + PreferenceConstants.EDITOR_STRING_COLOR_DQ }, + { + PreferencesMessages + .getString("JavaEditorPreferencePage.strings_sq"), + PreferenceConstants.EDITOR_STRING_COLOR_SQ }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.operators"), + PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.returnKeyword"), + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR }, + { PreferencesMessages.getString("JavaEditorPreferencePage.braces"), + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocKeywords"), + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocHtmlTags"), + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocLinks"), + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.phpDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$ + }; + + private final String[][] fAppearanceColorListModel = new String[][] { + { + PreferencesMessages + .getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.currentLineHighlighColor"), + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.printMarginColor2"), + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.findScopeColor2"), + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR }, + //$NON-NLS-1$ + { + PreferencesMessages + .getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR }, //$NON-NLS-1$ + }; + + // private final String[][] fAnnotationColorListModel; + + // private final String[][] fAnnotationDecorationListModel = new String[][]{ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"), + // AnnotationPreference.STYLE_NONE}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"), + // AnnotationPreference.STYLE_SQUIGGLIES}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"), + // AnnotationPreference.STYLE_UNDERLINE}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"), + // AnnotationPreference.STYLE_BOX}, + // //$NON-NLS-1$ + // { + // PreferencesMessages + // .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"), + // AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$ + // }; + private OverlayPreferenceStore fOverlayStore; + + private JavaTextTools fJavaTextTools; + + private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock; + + private FoldingConfigurationBlock fFoldingConfigurationBlock; + + private Map fColorButtons = new HashMap(); + + private Map fCheckBoxes = new HashMap(); + + private SelectionListener fCheckBoxListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + Button button = (Button) e.widget; + fOverlayStore.setValue((String) fCheckBoxes.get(button), button + .getSelection()); + } + }; + + private Map fTextFields = new HashMap(); + + private ModifyListener fTextFieldListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + Text text = (Text) e.widget; + fOverlayStore.setValue((String) fTextFields.get(text), text + .getText()); + } + }; + + private ArrayList fNumberFields = new ArrayList(); + + private ModifyListener fNumberFieldListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + numberFieldChanged((Text) e.widget); + } + }; + + private List fSyntaxColorList; + + private List fAppearanceColorList; + + // private List fContentAssistColorList; + //private List fAnnotationList; + + private ColorEditor fSyntaxForegroundColorEditor; + + private ColorEditor fAppearanceColorEditor; + + //private ColorEditor fAnnotationForegroundColorEditor; + + //private ColorEditor fContentAssistColorEditor; + + private ColorEditor fBackgroundColorEditor; + + private Button fBackgroundDefaultRadioButton; + + private Button fBackgroundCustomRadioButton; + + private Button fBackgroundColorButton; + + private Button fBoldCheckBox; + + // private Button fAddJavaDocTagsButton; + + private Button fEscapeStringsButtonDQ; + + private Button fEscapeStringsButtonSQ; + + // private Button fGuessMethodArgumentsButton; + private SourceViewer fPreviewViewer; + + private Color fBackgroundColor; + + //private Control fAutoInsertDelayText; + + //private Control fAutoInsertJavaTriggerText; + + //private Control fAutoInsertJavaDocTriggerText; + + //private Label fAutoInsertDelayLabel; + + //private Label fAutoInsertJavaTriggerLabel; + + //private Label fAutoInsertJavaDocTriggerLabel; + + //private Button; + + //private Combo fDecorationStyleCombo; + + //private Button fHighlightInTextCheckBox; + + //private Button fShowInOverviewRulerCheckBox; + + //private Button fShowInVerticalRulerCheckBox; + + private Text fBrowserLikeLinksKeyModifierText; + + private Button fBrowserLikeLinksCheckBox; + + private StatusInfo fBrowserLikeLinksKeyModifierStatus; + + // private Button fCompletionInsertsRadioButton; + // private Button fCompletionOverwritesRadioButton; + // private Button fStickyOccurrencesButton; + /** + * Creates a new preference page. + */ + public JavaEditorPreferencePage() { + setDescription(PreferencesMessages + .getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$ + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + MarkerAnnotationPreferences markerAnnotationPreferences = new MarkerAnnotationPreferences(); + fKeys = createOverlayStoreKeys(markerAnnotationPreferences); + fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), fKeys); + // fAnnotationColorListModel = + // createAnnotationTypeListModel(markerAnnotationPreferences); + } + + private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys( + MarkerAnnotationPreferences preferences) { + ArrayList overlayKeys = new ArrayList(); + Iterator e = preferences.getAnnotationPreferences().iterator(); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FOREGROUND_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BACKGROUND_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + PreferenceConstants.EDITOR_TAB_WIDTH)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_TAG_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_TYPE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_TYPE_BOLD)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_STRING_COLOR_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_STRING_BOLD_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_STRING_COLOR_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_STRING_BOLD_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TASK_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_TASK_TAG_BOLD)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING_DQ, + // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_OPERATOR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_OPERATOR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_KEYWORD_RETURN_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_PHP_BRACE_OPERATOR_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_MATCHING_BRACKETS)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_MARK_OCCURRENCES)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_STICKY_OCCURRENCES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_LINK_COLOR)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CORRECTION_INDICATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SPACES_FOR_TABS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOACTIVATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.INT, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_AUTOINSERT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ORDER_PROPOSALS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_CASE_SENSITIVITY)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_ADDIMPORT)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_INSERT_COMPLETION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SMART_PASTE)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP)); + // overlayKeys + // .add(new OverlayPreferenceStore.OverlayKey( + // OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_CLOSE_BRACES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_CLOSE_JAVADOCS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_WORDS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SMART_HOME_END)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK)); + while (e.hasNext()) { + AnnotationPreference info = (AnnotationPreference) e.next(); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, info + .getColorPreferenceKey())); + overlayKeys + .add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getTextPreferenceKey())); + if (info.getHighlightPreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getHighlightPreferenceKey())); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getOverviewRulerPreferenceKey())); + if (info.getVerticalRulerPreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, info + .getVerticalRulerPreferenceKey())); + if (info.getTextStylePreferenceKey() != null) + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.STRING, info + .getTextStylePreferenceKey())); + } + OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys + .size()]; + overlayKeys.toArray(keys); + return keys; + } /* + * @see IWorkbenchPreferencePage#init() + */ + + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + } + + private void handleSyntaxColorListSelection() { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + fSyntaxForegroundColorEditor.setColorValue(rgb); + fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD)); + } + + private void handleAppearanceColorListSelection() { + int i = fAppearanceColorList.getSelectionIndex(); + String key = fAppearanceColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + fAppearanceColorEditor.setColorValue(rgb); + } + + // private void handleAnnotationListSelection() { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][1]; + // RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + // fAnnotationForegroundColorEditor.setColorValue(rgb); + // key = fAnnotationColorListModel[i][2]; + // boolean showInText = fOverlayStore.getBoolean(key); + // fShowInTextCheckBox.setSelection(showInText); + // key = fAnnotationColorListModel[i][6]; + // if (key != null) { + // fDecorationStyleCombo.setEnabled(showInText); + // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { + // String value = fOverlayStore.getString(key); + // if (fAnnotationDecorationListModel[j][1].equals(value)) { + // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]); + // break; + // } + // } + // } else { + // fDecorationStyleCombo.setEnabled(false); + // fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // + // set + // // selection + // // to + // // squigglies + // // if + // // the + // // key + // // is + // // not + // // there + // // (legacy + // // support) + // } + // key = fAnnotationColorListModel[i][3]; + // fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // key = fAnnotationColorListModel[i][4]; + // if (key != null) { + // fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // fHighlightInTextCheckBox.setEnabled(true); + // } else + // fHighlightInTextCheckBox.setEnabled(false); + // key = fAnnotationColorListModel[i][5]; + // if (key != null) { + // fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key)); + // fShowInVerticalRulerCheckBox.setEnabled(true); + // } else { + // fShowInVerticalRulerCheckBox.setSelection(true); + // fShowInVerticalRulerCheckBox.setEnabled(false); + // } + // } + private Control createSyntaxPage(Composite parent) { + Composite colorComposite = new Composite(parent, SWT.NULL); + colorComposite.setLayout(new GridLayout()); + Group backgroundComposite = new Group(colorComposite, + SWT.SHADOW_ETCHED_IN); + backgroundComposite.setLayout(new RowLayout()); + backgroundComposite.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$ + SelectionListener backgroundSelectionListener = new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean custom = fBackgroundCustomRadioButton.getSelection(); + fBackgroundColorButton.setEnabled(custom); + fOverlayStore.setValue( + PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, + !custom); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }; + fBackgroundDefaultRadioButton = new Button(backgroundComposite, + SWT.RADIO | SWT.LEFT); + fBackgroundDefaultRadioButton.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$ + fBackgroundDefaultRadioButton + .addSelectionListener(backgroundSelectionListener); + fBackgroundCustomRadioButton = new Button(backgroundComposite, + SWT.RADIO | SWT.LEFT); + fBackgroundCustomRadioButton.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$ + fBackgroundCustomRadioButton + .addSelectionListener(backgroundSelectionListener); + fBackgroundColorEditor = new ColorEditor(backgroundComposite); + fBackgroundColorButton = fBackgroundColorEditor.getButton(); + Label label = new Label(colorComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Composite editorComposite = new Composite(colorComposite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + editorComposite.setLayoutData(gd); + fSyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL + | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(5); + fSyntaxColorList.setLayoutData(gd); + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + label = new Label(stylesComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + label.setLayoutData(gd); + fSyntaxForegroundColorEditor = new ColorEditor(stylesComposite); + Button foregroundColorButton = fSyntaxForegroundColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + foregroundColorButton.setLayoutData(gd); + fBoldCheckBox = new Button(stylesComposite, SWT.CHECK); + fBoldCheckBox.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + fBoldCheckBox.setLayoutData(gd); + label = new Label(colorComposite, SWT.LEFT); + label.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Control previewer = createPreviewer(colorComposite); + gd = new GridData(GridData.FILL_BOTH); + gd.widthHint = convertWidthInCharsToPixels(20); + gd.heightHint = convertHeightInCharsToPixels(5); + previewer.setLayoutData(gd); + fSyntaxColorList.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + handleSyntaxColorListSelection(); + } + }); + foregroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + PreferenceConverter.setValue(fOverlayStore, key, + fSyntaxForegroundColorEditor.getColorValue()); + } + }); + fBackgroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + PreferenceConverter.setValue(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR, + fBackgroundColorEditor.getColorValue()); + } + }); + fBoldCheckBox.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fSyntaxColorList.getSelectionIndex(); + String key = fSyntaxColorListModel[i][1]; + fOverlayStore + .setValue(key + BOLD, fBoldCheckBox.getSelection()); + } + }); + return colorComposite; + } + + private Control createPreviewer(Composite parent) { + Preferences coreStore = createTemporaryCorePreferenceStore(); + fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false); + IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + IPreferenceStore store = new ChainedPreferenceStore( + new IPreferenceStore[] { + fOverlayStore, + new PreferencesAdapter( + createTemporaryCorePreferenceStore()), + generalTextStore }); + + fPreviewViewer = new JavaSourceViewer(parent, null, null, false, + SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + PHPSourceViewerConfiguration configuration = new PHPSourceViewerConfiguration( + tools.getColorManager(), store, null, + IPHPPartitions.PHP_PARTITIONING); + // PHPSourceViewerConfiguration configuration =new + // PHPSourceViewerConfiguration(fJavaTextTools, null, + // IPHPPartitions.PHP_PARTITIONING); + fPreviewViewer.configure(configuration); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + fPreviewViewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); + fPreviewViewer.setEditable(false); + String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$ + IDocument document = new Document(content); + fJavaTextTools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + fPreviewViewer.setDocument(document); + return fPreviewViewer.getControl(); + } + + private Preferences createTemporaryCorePreferenceStore() { + Preferences result = new Preferences(); + result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$ + return result; + } + + private Control createAppearancePage(Composite parent) { + Composite appearanceComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + appearanceComposite.setLayout(layout); + + // Inserts a hyper-link to the General Editor preferences page + // TODO Can probably be removed post 1.5.0? + String label = PreferencesMessages + .getString("JavaEditorPreferencePage.appearanceTabLink"); + Link link = new Link(appearanceComposite, SWT.NONE); + GridData gridPosition = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gridPosition.horizontalSpan = 2; + link.setLayoutData(gridPosition); + + link.setText(label); + link.addListener(SWT.Selection, new Listener () { + public void handleEvent(Event event) { + String u = event.text; + PreferencesUtil.createPreferenceDialogOn(getShell(), u, null, null); + } + }); + String tooltip = PreferencesMessages + .getString("JavaEditorPreferencePage.appearanceTabTooltip"); + link.setToolTipText(tooltip); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$ + addTextField(appearanceComposite, label, + PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$ + addTextField( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, + 3, 0, true); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$ + addCheckBox(appearanceComposite, label, + PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$ + addCheckBox( + appearanceComposite, + label, + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, + 0); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.markOccurrences"); //$NON-NLS-1$ + // Button master= addCheckBox(appearanceComposite, label, + // PreferenceConstants.EDITOR_MARK_OCCURRENCES, 0); //$NON-NLS-1$ + label = PreferencesMessages + .getString("JavaEditorPreferencePage.stickyOccurrences"); //$NON-NLS-1$ + // fStickyOccurrencesButton= addCheckBox(appearanceComposite, label, + // PreferenceConstants.EDITOR_STICKY_OCCURRENCES, 0); //$NON-NLS-1$ + // createDependency(master, fStickyOccurrencesButton); + Label l = new Label(appearanceComposite, SWT.LEFT); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + gd.heightHint = convertHeightInCharsToPixels(1) / 2; + l.setLayoutData(gd); + l = new Label(appearanceComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$ + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 2; + l.setLayoutData(gd); + Composite editorComposite = new Composite(appearanceComposite, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + gd.horizontalSpan = 2; + editorComposite.setLayoutData(gd); + fAppearanceColorList = new List(editorComposite, SWT.SINGLE + | SWT.V_SCROLL | SWT.BORDER); + gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + | GridData.FILL_HORIZONTAL); + gd.heightHint = convertHeightInCharsToPixels(8); + fAppearanceColorList.setLayoutData(gd); + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + l = new Label(stylesComposite, SWT.LEFT); + l.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + l.setLayoutData(gd); + fAppearanceColorEditor = new ColorEditor(stylesComposite); + Button foregroundColorButton = fAppearanceColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + foregroundColorButton.setLayoutData(gd); + fAppearanceColorList.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + handleAppearanceColorListSelection(); + } + }); + foregroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + public void widgetSelected(SelectionEvent e) { + int i = fAppearanceColorList.getSelectionIndex(); + String key = fAppearanceColorListModel[i][1]; + PreferenceConverter.setValue(fOverlayStore, key, + fAppearanceColorEditor.getColorValue()); + } + }); + return appearanceComposite; + } + + // private Control createAnnotationsPage(Composite parent) { + // Composite composite = new Composite(parent, SWT.NULL); + // GridLayout layout = new GridLayout(); + // layout.numColumns = 2; + // composite.setLayout(layout); + // String text = PreferencesMessages + // .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); + // //$NON-NLS-1$ + // addCheckBox(composite, text, + // PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0); + // text = PreferencesMessages + // .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$ + // addCheckBox(composite, text, + // PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0); + // addFiller(composite); + // Label label = new Label(composite, SWT.LEFT); + // label.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotationPresentationOptions")); + // //$NON-NLS-1$ + // GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + // gd.horizontalSpan = 2; + // label.setLayoutData(gd); + // Composite editorComposite = new Composite(composite, SWT.NONE); + // layout = new GridLayout(); + // layout.numColumns = 2; + // layout.marginHeight = 0; + // layout.marginWidth = 0; + // editorComposite.setLayout(layout); + // gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | + // GridData.FILL_VERTICAL); + // gd.horizontalSpan = 2; + // editorComposite.setLayoutData(gd); + // fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL + // | SWT.BORDER); + // gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING + // | GridData.FILL_HORIZONTAL); + // gd.heightHint = convertHeightInCharsToPixels(10); + // fAnnotationList.setLayoutData(gd); + // Composite optionsComposite = new Composite(editorComposite, SWT.NONE); + // layout = new GridLayout(); + // layout.marginHeight = 0; + // layout.marginWidth = 0; + // layout.numColumns = 2; + // optionsComposite.setLayout(layout); + // optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + // fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInTextCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInText")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInTextCheckBox.setLayoutData(gd); + // fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY); + // for (int i = 0; i < fAnnotationDecorationListModel.length; i++) + // fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]); + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // gd.horizontalIndent = 20; + // fDecorationStyleCombo.setLayoutData(gd); + // fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK); + // fHighlightInTextCheckBox.setText(PreferencesMessages + // .getString("TextEditorPreferencePage.annotations.highlightInText")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fHighlightInTextCheckBox.setLayoutData(gd); + // fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInOverviewRulerCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInOverviewRulerCheckBox.setLayoutData(gd); + // fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK); + // fShowInVerticalRulerCheckBox.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); + // //$NON-NLS-1$ + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // gd.horizontalSpan = 2; + // fShowInVerticalRulerCheckBox.setLayoutData(gd); + // label = new Label(optionsComposite, SWT.LEFT); + // label.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$ + // gd = new GridData(); + // gd.horizontalAlignment = GridData.BEGINNING; + // label.setLayoutData(gd); + // fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite); + // Button foregroundColorButton = + // fAnnotationForegroundColorEditor.getButton(); + // gd = new GridData(GridData.FILL_HORIZONTAL); + // gd.horizontalAlignment = GridData.BEGINNING; + // foregroundColorButton.setLayoutData(gd); + // fAnnotationList.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // handleAnnotationListSelection(); + // } + // }); + // fShowInTextCheckBox.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][2]; + // fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection()); + // String decorationKey = fAnnotationColorListModel[i][6]; + // fDecorationStyleCombo.setEnabled(decorationKey != null + // && fShowInTextCheckBox.getSelection()); + // } + // }); + // fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][4]; + // fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection()); + // } + // }); + // fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() + // { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][3]; + // fOverlayStore + // .setValue(key, fShowInOverviewRulerCheckBox.getSelection()); + // } + // }); + // fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() + // { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][5]; + // fOverlayStore + // .setValue(key, fShowInVerticalRulerCheckBox.getSelection()); + // } + // }); + // foregroundColorButton.addSelectionListener(new SelectionListener() { + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][1]; + // PreferenceConverter.setValue(fOverlayStore, key, + // fAnnotationForegroundColorEditor.getColorValue()); + // } + // }); + // fDecorationStyleCombo.addSelectionListener(new SelectionListener() { + // /** + // * {@inheritdoc} + // */ + // public void widgetDefaultSelected(SelectionEvent e) { + // // do nothing + // } + // /** + // * {@inheritdoc} + // */ + // public void widgetSelected(SelectionEvent e) { + // int i = fAnnotationList.getSelectionIndex(); + // String key = fAnnotationColorListModel[i][6]; + // if (key != null) { + // for (int j = 0; j < fAnnotationDecorationListModel.length; j++) { + // if (fAnnotationDecorationListModel[j][0] + // .equals(fDecorationStyleCombo.getText())) { + // fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]); + // break; + // } + // } + // } + // } + // }); + // return composite; + // } +// private String[][] createAnnotationTypeListModel( +// MarkerAnnotationPreferences preferences) { +// ArrayList listModelItems = new ArrayList(); +// SortedSet sortedPreferences = new TreeSet(new Comparator() { +// /* +// * @see java.util.Comparator#compare(java.lang.Object, +// * java.lang.Object) +// */ +// public int compare(Object o1, Object o2) { +// if (!(o2 instanceof AnnotationPreference)) +// return -1; +// if (!(o1 instanceof AnnotationPreference)) +// return 1; +// AnnotationPreference a1 = (AnnotationPreference) o1; +// AnnotationPreference a2 = (AnnotationPreference) o2; +// return Collator.getInstance().compare(a1.getPreferenceLabel(), +// a2.getPreferenceLabel()); +// } +// }); +// sortedPreferences.addAll(preferences.getAnnotationPreferences()); +// Iterator e = sortedPreferences.iterator(); +// while (e.hasNext()) { +// AnnotationPreference info = (AnnotationPreference) e.next(); +// listModelItems.add(new String[] { info.getPreferenceLabel(), +// info.getColorPreferenceKey(), info.getTextPreferenceKey(), +// info.getOverviewRulerPreferenceKey(), +// info.getHighlightPreferenceKey(), +// info.getVerticalRulerPreferenceKey(), +// info.getTextStylePreferenceKey() }); +// } +// String[][] items = new String[listModelItems.size()][]; +// listModelItems.toArray(items); +// return items; +// } + + private Control createTypingPage(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + composite.setLayout(layout); + String label; + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.overwriteMode"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, 1); + // addFiller(composite); + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.smartHomeEnd"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_SMART_HOME_END, 1); + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.subWordNavigation"); + // //$NON-NLS-1$ + // addCheckBox(composite, label, + // PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, 1); + // addFiller(composite); + Group group = new Group(composite, SWT.NONE); + layout = new GridLayout(); + layout.numColumns = 2; + group.setLayout(layout); + group.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$ + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapWords");//$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_WORDS, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapStringsDQ");//$NON-NLS-1$ + Button button = addCheckBox(group, label, + PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.escapeStringsDQ");//$NON-NLS-1$ + fEscapeStringsButtonDQ = addCheckBox(group, label, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, 1); + createDependency(button, fEscapeStringsButtonDQ); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.wrapStringsSQ");//$NON-NLS-1$ + button = addCheckBox(group, label, + PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.escapeStringsSQ"); + //$NON-NLS-1$ + fEscapeStringsButtonSQ = addCheckBox(group, label, + PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, 1); + createDependency(button, fEscapeStringsButtonSQ); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.smartPaste"); + //$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.insertSpaceForTabs"); + //$NON-NLS-1$ + addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeStringsDQ"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, 1); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeStringsSQ"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeBrackets"); + //$NON-NLS-1$ + addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1); + + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.closeBraces"); + // //$NON-NLS-1$ + // addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, + // 1); + + label = PreferencesMessages + .getString("JavaEditorPreferencePage.closeJavaDocs"); + //$NON-NLS-1$ + button = addCheckBox(group, label, + PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1); + label = PreferencesMessages + .getString("JavaEditorPreferencePage.formatJavaDocs"); + //$NON-NLS-1$ + button = addCheckBox(group, label, + PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1); + + // + // label = PreferencesMessages + // .getString("JavaEditorPreferencePage.addJavaDocTags"); + // //$NON-NLS-1$ + // fAddJavaDocTagsButton = addCheckBox(group, label, + // PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1); + // createDependency(button, fAddJavaDocTagsButton); + return composite; + } + +// private void addFiller(Composite composite) { +// Label filler = new Label(composite, SWT.LEFT); +// GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); +// gd.horizontalSpan = 2; +// gd.heightHint = convertHeightInCharsToPixels(1) / 2; +// filler.setLayoutData(gd); +// } + + private static void indent(Control control) { + GridData gridData = new GridData(); + gridData.horizontalIndent = 20; + control.setLayoutData(gridData); + } + + private static void createDependency(final Button master, + final Control slave) { + indent(slave); + master.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + slave.setEnabled(master.getSelection()); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + +// private void addCompletionRadioButtons(Composite contentAssistComposite) { +// Composite completionComposite = new Composite(contentAssistComposite, +// SWT.NONE); +// GridData ccgd = new GridData(); +// ccgd.horizontalSpan = 2; +// completionComposite.setLayoutData(ccgd); +// GridLayout ccgl = new GridLayout(); +// ccgl.marginWidth = 0; +// ccgl.numColumns = 2; +// completionComposite.setLayout(ccgl); +// // SelectionListener completionSelectionListener= new SelectionAdapter() +// // { +// // public void widgetSelected(SelectionEvent e) { +// // boolean insert= fCompletionInsertsRadioButton.getSelection(); +// // fOverlayStore.setValue(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, +// // insert); +// // } +// // }; +// // +// // fCompletionInsertsRadioButton= new Button(completionComposite, +// // SWT.RADIO +// // | SWT.LEFT); +// // fCompletionInsertsRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionInserts")); +// // //$NON-NLS-1$ +// // fCompletionInsertsRadioButton.setLayoutData(new GridData()); +// // fCompletionInsertsRadioButton.addSelectionListener(completionSelectionListener); +// // +// // fCompletionOverwritesRadioButton= new Button(completionComposite, +// // SWT.RADIO | SWT.LEFT); +// // fCompletionOverwritesRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.completionOverwrites")); +// // //$NON-NLS-1$ +// // fCompletionOverwritesRadioButton.setLayoutData(new GridData()); +// // fCompletionOverwritesRadioButton.addSelectionListener(completionSelectionListener); +// } + + private Control createNavigationPage(Composite parent) { + Composite composite = new Composite(parent, SWT.NULL); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + composite.setLayout(layout); + String text = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.browserLikeLinks"); + //$NON-NLS-1$ + fBrowserLikeLinksCheckBox = addCheckBox(composite, text, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, 0); + fBrowserLikeLinksCheckBox.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + boolean state = fBrowserLikeLinksCheckBox.getSelection(); + fBrowserLikeLinksKeyModifierText.setEnabled(state); + handleBrowserLikeLinksKeyModifierModified(); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + // Text field for modifier string + text = PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier"); + //$NON-NLS-1$ + fBrowserLikeLinksKeyModifierText = addTextField(composite, text, + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, 20, + 0, false); + fBrowserLikeLinksKeyModifierText.setTextLimit(Text.LIMIT); + + if (computeStateMask(fOverlayStore + .getString(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER)) == -1) { + // Fix possible illegal modifier string + int stateMask = fOverlayStore + .getInt(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); + if (stateMask == -1) + fBrowserLikeLinksKeyModifierText.setText(""); //$NON-NLS-1$ + else + fBrowserLikeLinksKeyModifierText.setText(EditorUtility + .getModifierString(stateMask)); + } + fBrowserLikeLinksKeyModifierText.addKeyListener(new KeyListener() { + private boolean isModifierCandidate; + + public void keyPressed(KeyEvent e) { + isModifierCandidate = e.keyCode > 0 && e.character == 0 + && e.stateMask == 0; + } + + public void keyReleased(KeyEvent e) { + if (isModifierCandidate && e.stateMask > 0 + && e.stateMask == e.stateMask && e.character == 0) {// && + // e.time + // -time + // < + // 1000) + // { + String modifierString = fBrowserLikeLinksKeyModifierText + .getText(); + Point selection = fBrowserLikeLinksKeyModifierText + .getSelection(); + int i = selection.x - 1; + while (i > -1 + && Character.isWhitespace(modifierString.charAt(i))) { + i--; + } + boolean needsPrefixDelimiter = i > -1 + && !String.valueOf(modifierString.charAt(i)) + .equals(DELIMITER); + + i = selection.y; + while (i < modifierString.length() + && Character.isWhitespace(modifierString.charAt(i))) { + i++; + } + boolean needsPostfixDelimiter = i < modifierString.length() + && !String.valueOf(modifierString.charAt(i)) + .equals(DELIMITER); + + String insertString; + + if (needsPrefixDelimiter && needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPrefixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertDelimiterAndModifier", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else if (needsPostfixDelimiter) + insertString = PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.insertModifierAndDelimiter", + new String[] { Action + .findModifierString(e.stateMask) }); //$NON-NLS-1$ + else + insertString = Action.findModifierString(e.stateMask); + + fBrowserLikeLinksKeyModifierText.insert(insertString); + } + } + }); + + fBrowserLikeLinksKeyModifierText + .addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + handleBrowserLikeLinksKeyModifierModified(); + } + }); + return composite; + } + + private void handleBrowserLikeLinksKeyModifierModified() { + String modifiers = fBrowserLikeLinksKeyModifierText.getText(); + int stateMask = computeStateMask(modifiers); + if (fBrowserLikeLinksCheckBox.getSelection() + && (stateMask == -1 || (stateMask & SWT.SHIFT) != 0)) { + if (stateMask == -1) + fBrowserLikeLinksKeyModifierStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getFormattedString( + "JavaEditorPreferencePage.navigation.modifierIsNotValid", modifiers)); //$NON-NLS-1$ + else + fBrowserLikeLinksKeyModifierStatus = new StatusInfo( + IStatus.ERROR, + PreferencesMessages + .getString("JavaEditorPreferencePage.navigation.shiftIsDisabled")); + //$NON-NLS-1$ + setValid(false); + StatusUtil.applyToStatusLine(this, + fBrowserLikeLinksKeyModifierStatus); + } else { + fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); + updateStatus(fBrowserLikeLinksKeyModifierStatus); + } + } + +// private IStatus getBrowserLikeLinksKeyModifierStatus() { +// if (fBrowserLikeLinksKeyModifierStatus == null) +// fBrowserLikeLinksKeyModifierStatus = new StatusInfo(); +// return fBrowserLikeLinksKeyModifierStatus; +// } + + /** + * Computes the state mask for the given modifier string. + * + * @param modifiers + * the string with the modifiers, separated by '+', '-', ';', ',' + * or '.' + * @return the state mask or -1 if the input is invalid + */ + private int computeStateMask(String modifiers) { + if (modifiers == null) + return -1; + if (modifiers.length() == 0) + return SWT.NONE; + int stateMask = 0; + StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + ",;.:+-* "); //$NON-NLS-1$ + while (modifierTokenizer.hasMoreTokens()) { + int modifier = EditorUtility + .findLocalizedModifier(modifierTokenizer.nextToken()); + if (modifier == 0 || (stateMask & modifier) == modifier) + return -1; + stateMask = stateMask | modifier; + } + return stateMask; + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + initializeDefaultColors(); + fFoldingConfigurationBlock = new FoldingConfigurationBlock( + fOverlayStore); + fOverlayStore.load(); + fOverlayStore.start(); + TabFolder folder = new TabFolder(parent, SWT.NONE); + folder.setLayout(new TabFolderLayout()); + folder.setLayoutData(new GridData(GridData.FILL_BOTH)); + TabItem item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$ + item.setControl(createAppearancePage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$ + item.setControl(createSyntaxPage(folder)); + + // item = new TabItem(folder, SWT.NONE); + // item.setText(PreferencesMessages + // .getString("JavaEditorPreferencePage.annotationsTab.title")); + // //$NON-NLS-1$ + // item.setControl(createAnnotationsPage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.typing.tabTitle")); + //$NON-NLS-1$ + item.setControl(createTypingPage(folder)); + + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.hoverTab.title")); + //$NON-NLS-1$ + fJavaEditorHoverConfigurationBlock = new JavaEditorHoverConfigurationBlock( + this, fOverlayStore); + item.setControl(fJavaEditorHoverConfigurationBlock + .createControl(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.navigationTab.title")); + // //$NON-NLS-1$ + item.setControl(createNavigationPage(folder)); + item = new TabItem(folder, SWT.NONE); + item.setText(PreferencesMessages + .getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$ + item.setControl(fFoldingConfigurationBlock.createControl(folder)); + + initialize(); + Dialog.applyDialogFont(folder); + return folder; + } + + private void initialize() { + initializeFields(); + for (int i = 0; i < fSyntaxColorListModel.length; i++) + fSyntaxColorList.add(fSyntaxColorListModel[i][0]); + fSyntaxColorList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) { + fSyntaxColorList.select(0); + handleSyntaxColorListSelection(); + } + } + }); + for (int i = 0; i < fAppearanceColorListModel.length; i++) + fAppearanceColorList.add(fAppearanceColorListModel[i][0]); + fAppearanceColorList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (fAppearanceColorList != null + && !fAppearanceColorList.isDisposed()) { + fAppearanceColorList.select(0); + handleAppearanceColorListSelection(); + } + } + }); + // for (int i = 0; i < fAnnotationColorListModel.length; i++) + // fAnnotationList.add(fAnnotationColorListModel[i][0]); + // fAnnotationList.getDisplay().asyncExec(new Runnable() { + // public void run() { + // if (fAnnotationList != null && !fAnnotationList.isDisposed()) { + // fAnnotationList.select(0); + // handleAnnotationListSelection(); + // } + // } + // }); + // for (int i= 0; i < fContentAssistColorListModel.length; i++) + // fContentAssistColorList.add(fContentAssistColorListModel[i][0]); + // fContentAssistColorList.getDisplay().asyncExec(new Runnable() { + // public void run() { + // if (fContentAssistColorList != null && + // !fContentAssistColorList.isDisposed()) { + // fContentAssistColorList.select(0); + // handleContentAssistColorListSelection(); + // } + // } + // }); + fFoldingConfigurationBlock.initialize(); + } + + private void initializeFields() { + Iterator e = fColorButtons.keySet().iterator(); + while (e.hasNext()) { + ColorEditor c = (ColorEditor) e.next(); + String key = (String) fColorButtons.get(c); + RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); + c.setColorValue(rgb); + } + e = fCheckBoxes.keySet().iterator(); + while (e.hasNext()) { + Button b = (Button) e.next(); + String key = (String) fCheckBoxes.get(b); + b.setSelection(fOverlayStore.getBoolean(key)); + } + e = fTextFields.keySet().iterator(); + while (e.hasNext()) { + Text t = (Text) e.next(); + String key = (String) fTextFields.get(t); + t.setText(fOverlayStore.getString(key)); + } + RGB rgb = PreferenceConverter.getColor(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR); + fBackgroundColorEditor.setColorValue(rgb); + boolean default_ = fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR); + fBackgroundDefaultRadioButton.setSelection(default_); + fBackgroundCustomRadioButton.setSelection(!default_); + fBackgroundColorButton.setEnabled(!default_); +// boolean closeJavaDocs = fOverlayStore +// .getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS); + // fAddJavaDocTagsButton.setEnabled(closeJavaDocs); + fEscapeStringsButtonDQ.setEnabled(fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ)); + fEscapeStringsButtonSQ.setEnabled(fOverlayStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ)); + // boolean fillMethodArguments= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES); + // fGuessMethodArgumentsButton.setEnabled(fillMethodArguments); + // boolean completionInserts= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); + // fCompletionInsertsRadioButton.setSelection(completionInserts); + // fCompletionOverwritesRadioButton.setSelection(! completionInserts); + // + fBrowserLikeLinksKeyModifierText.setEnabled(fBrowserLikeLinksCheckBox + .getSelection()); + // boolean markOccurrences= + // fOverlayStore.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); + // fStickyOccurrencesButton.setEnabled(markOccurrences); + updateAutoactivationControls(); + } + + private void initializeDefaultColors() { + if (!getPreferenceStore().contains( + PreferenceConstants.EDITOR_BACKGROUND_COLOR)) { + RGB rgb = getControl().getDisplay().getSystemColor( + SWT.COLOR_LIST_BACKGROUND).getRGB(); + PreferenceConverter.setDefault(fOverlayStore, + PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); + PreferenceConverter.setDefault(getPreferenceStore(), + PreferenceConstants.EDITOR_BACKGROUND_COLOR, rgb); + } + if (!getPreferenceStore().contains( + PreferenceConstants.EDITOR_FOREGROUND_COLOR)) { + RGB rgb = getControl().getDisplay().getSystemColor( + SWT.COLOR_LIST_FOREGROUND).getRGB(); + PreferenceConverter.setDefault(fOverlayStore, + PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); + PreferenceConverter.setDefault(getPreferenceStore(), + PreferenceConstants.EDITOR_FOREGROUND_COLOR, rgb); + } + } + + private void updateAutoactivationControls() { + // boolean autoactivation= + // fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION); + // fAutoInsertDelayText.setEnabled(autoactivation); + // fAutoInsertDelayLabel.setEnabled(autoactivation); + // fAutoInsertJavaTriggerText.setEnabled(autoactivation); + // fAutoInsertJavaTriggerLabel.setEnabled(autoactivation); + // + // fAutoInsertJavaDocTriggerText.setEnabled(autoactivation); + // fAutoInsertJavaDocTriggerLabel.setEnabled(autoactivation); + } + + /* + * @see PreferencePage#performOk() + */ + public boolean performOk() { + // fJavaEditorHoverConfigurationBlock.performOk(); + fFoldingConfigurationBlock.performOk(); + fOverlayStore + .setValue( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, + computeStateMask(fBrowserLikeLinksKeyModifierText + .getText())); + fOverlayStore.propagate(); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + return true; + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fOverlayStore.loadDefaults(); + initializeFields(); + handleSyntaxColorListSelection(); + handleAppearanceColorListSelection(); + // handleAnnotationListSelection(); + // handleContentAssistColorListSelection(); + // fJavaEditorHoverConfigurationBlock.performDefaults(); + fFoldingConfigurationBlock.performDefaults(); + super.performDefaults(); + fPreviewViewer.invalidateTextPresentation(); + } + + /* + * @see DialogPage#dispose() + */ + public void dispose() { + fFoldingConfigurationBlock.dispose(); + + if (fJavaTextTools != null) { + fJavaTextTools.dispose(); + fJavaTextTools = null; + } + if (fOverlayStore != null) { + fOverlayStore.stop(); + fOverlayStore = null; + } + if (fBackgroundColor != null && !fBackgroundColor.isDisposed()) + fBackgroundColor.dispose(); + super.dispose(); + } + + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 2; + checkBox.setLayoutData(gd); + checkBox.addSelectionListener(fCheckBoxListener); + fCheckBoxes.put(checkBox, key); + return checkBox; + } + + private Text addTextField(Composite composite, String label, String key, + int textLimit, int indentation, boolean isNumber) { + return getTextControl(addLabelledTextField(composite, label, key, + textLimit, indentation, isNumber)); + } + +// private static Label getLabelControl(Control[] labelledTextField) { +// return (Label) labelledTextField[0]; +// } + + private static Text getTextControl(Control[] labelledTextField) { + return (Text) labelledTextField[1]; + } + + /** + * Returns an array of size 2: - first element is of type Label- + * second element is of type Text Use + * getLabelControl and getTextControl to get + * the 2 controls. + */ + private Control[] addLabelledTextField(Composite composite, String label, + String key, int textLimit, int indentation, boolean isNumber) { + Label labelControl = new Label(composite, SWT.NONE); + labelControl.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + labelControl.setLayoutData(gd); + Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.widthHint = convertWidthInCharsToPixels(textLimit + 1); + textControl.setLayoutData(gd); + textControl.setTextLimit(textLimit); + fTextFields.put(textControl, key); + if (isNumber) { + fNumberFields.add(textControl); + textControl.setText("0"); + textControl.addModifyListener(fNumberFieldListener); + } else { + textControl.addModifyListener(fTextFieldListener); + } + return new Control[] { labelControl, textControl }; + } + + private String loadPreviewContentFromFile(String filename) { + String line; + String separator = System.getProperty("line.separator"); //$NON-NLS-1$ + StringBuffer buffer = new StringBuffer(512); + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(getClass() + .getResourceAsStream(filename))); + while ((line = reader.readLine()) != null) { + buffer.append(line); + buffer.append(separator); + } + } catch (IOException io) { + PHPeclipsePlugin.log(io); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + } + } + } + return buffer.toString(); + } + + private void numberFieldChanged(Text textControl) { + String number = textControl.getText(); + IStatus status = validatePositiveNumber(number); + if (!status.matches(IStatus.ERROR)) + fOverlayStore.setValue((String) fTextFields.get(textControl), + number); + updateStatus(status); + } + + private IStatus validatePositiveNumber(String number) { + StatusInfo status = new StatusInfo(); + if (number.length() == 0) { + status.setError(PreferencesMessages + .getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$ + } else { + try { + int value = Integer.parseInt(number); + if (value < 0) + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } catch (NumberFormatException e) { + status.setError(PreferencesMessages.getFormattedString( + "JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$ + } + } + return status; + } + + void updateStatus(IStatus status) { + if (!status.matches(IStatus.ERROR)) { + for (int i = 0; i < fNumberFields.size(); i++) { + Text text = (Text) fNumberFields.get(i); + IStatus s = validatePositiveNumber(text.getText()); + status = StatusUtil.getMoreSevere(s, status); + } + } + // status= + // StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), + // status); + // status= + // StatusUtil.getMoreSevere(getBrowserLikeLinksKeyModifierStatus(), + // status); + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaSourcePreviewerUpdater.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java new file mode 100644 index 0000000..9968a9d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/JavaTemplatePreferencePage.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.texteditor.templates.TemplatePreferencePage; + +public class JavaTemplatePreferencePage extends TemplatePreferencePage + implements IWorkbenchPreferencePage { + + private TemplateVariableProcessor fTemplateProcessor; + + public JavaTemplatePreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setTemplateStore(PHPeclipsePlugin.getDefault().getTemplateStore()); + setContextTypeRegistry(PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry()); + fTemplateProcessor = new TemplateVariableProcessor(); + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + } + + /* + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + boolean ok = super.performOk(); + + PHPeclipsePlugin.getDefault().savePluginPreferences(); + + return ok; + } + + /* + * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#getFormatterPreferenceKey() + */ + protected String getFormatterPreferenceKey() { + return PreferenceConstants.TEMPLATES_USE_CODEFORMATTER; + } + + /* + * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createTemplateEditDialog(org.eclipse.jface.text.templates.Template, + * boolean, boolean) + */ + protected Dialog createTemplateEditDialog(Template template, boolean edit, + boolean isNameModifiable) { + return new EditTemplateDialog(getShell(), template, edit, + isNameModifiable, getContextTypeRegistry()); + } + + /* + * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#createViewer(org.eclipse.swt.widgets.Composite) + */ + protected SourceViewer createViewer(Composite parent) { + GridData data = new GridData(); + IDocument document = new Document(); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, + SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration( + tools.getColorManager(), store, null, fTemplateProcessor); + viewer.configure(configuration); + viewer.setEditable(false); + viewer.setDocument(document); + + Font font = JFaceResources + .getFont(PreferenceConstants.EDITOR_TEXT_FONT); + viewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(viewer, configuration, store); + + Control control = viewer.getControl(); + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL + | GridData.FILL_VERTICAL); + control.setLayoutData(data); + + return viewer; + } + + /* + * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#updateViewerInput() + */ + protected void updateViewerInput() { + IStructuredSelection selection = (IStructuredSelection) getTableViewer() + .getSelection(); + SourceViewer viewer = getViewer(); + + if (selection.size() == 1 + && selection.getFirstElement() instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) selection + .getFirstElement(); + Template template = data.getTemplate(); + String contextId = template.getContextTypeId(); + TemplateContextType type = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType(contextId); + fTemplateProcessor.setContextType(type); + + IDocument doc = viewer.getDocument(); + + String start = null; + if ("javadoc".equals(contextId)) { //$NON-NLS-1$ + start = "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$ + } else + start = ""; //$NON-NLS-1$ + + doc.set(start + template.getPattern()); + int startLen = start.length(); + viewer.setDocument(doc, startLen, doc.getLength() - startLen); + + } else { + viewer.getDocument().set(""); //$NON-NLS-1$ + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java new file mode 100644 index 0000000..af8ee82 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MarkOccurrencesPreferencePage.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * 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 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; + +/** + * The page for setting the editor options. + */ +public final class MarkOccurrencesPreferencePage extends + AbstractConfigurationBlockPreferencePage { + + /* + * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#getHelpId() + */ + protected String getHelpId() { + return IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE; + } + + /* + * @see org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setDescription() + */ + protected void setDescription() { + String description = PreferencesMessages + .getString("MarkOccurrencesConfigurationBlock.title"); + setDescription(description); + } + + /* + * @see org.org.eclipse.ui.internal.editors.text.AbstractConfigurationBlockPreferencePage#setPreferenceStore() + */ + protected void setPreferenceStore() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + } + + protected Label createDescriptionLabel(Composite parent) { + return null; // no description for new look. + } + + /* + * @see org.eclipse.ui.internal.editors.text.AbstractConfigureationBlockPreferencePage#createConfigurationBlock(org.eclipse.ui.internal.editors.text.OverlayPreferenceStore) + */ + protected IPreferenceConfigurationBlock createConfigurationBlock( + OverlayPreferenceStore overlayPreferenceStore) { + return new MarkOccurrencesConfigurationBlock(overlayPreferenceStore); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java new file mode 100644 index 0000000..74e8649 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java @@ -0,0 +1,307 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; + +import net.sourceforge.phpdt.core.Flags; +import net.sourceforge.phpdt.internal.ui.util.SWTUtil; +import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField; +import net.sourceforge.phpdt.ui.JavaElementImageDescriptor; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.LabelProvider; +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.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +public class MembersOrderPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage { + + private static final String ALL_ENTRIES = "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$ + + private static final String PREF_OUTLINE_SORT_OPTION = PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER; + + public static final String CONSTRUCTORS = "C"; //$NON-NLS-1$ + + public static final String FIELDS = "F"; //$NON-NLS-1$ + + public static final String METHODS = "M"; //$NON-NLS-1$ + + public static final String STATIC_METHODS = "SM"; //$NON-NLS-1$ + + public static final String STATIC_FIELDS = "SF"; //$NON-NLS-1$ + + public static final String INIT = "I"; //$NON-NLS-1$ + + public static final String STATIC_INIT = "SI"; //$NON-NLS-1$ + + public static final String TYPES = "T"; //$NON-NLS-1$ + + private ListDialogField fSortOrderList; + + private static List getSortOrderList(String string) { + StringTokenizer tokenizer = new StringTokenizer(string, ","); //$NON-NLS-1$ + List entries = new ArrayList(); + for (int i = 0; tokenizer.hasMoreTokens(); i++) { + String token = tokenizer.nextToken(); + entries.add(token); + } + return entries; + } + + private static boolean isValidEntries(List entries) { + StringTokenizer tokenizer = new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$ + int i = 0; + for (; tokenizer.hasMoreTokens(); i++) { + String token = tokenizer.nextToken(); + if (!entries.contains(token)) + return false; + } + return i == entries.size(); + } + + public MembersOrderPreferencePage() { + // set the preference store + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + + setDescription(PreferencesMessages + .getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$ + + String string = getPreferenceStore() + .getString(PREF_OUTLINE_SORT_OPTION); + + String upLabel = PreferencesMessages + .getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$ + String downLabel = PreferencesMessages + .getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$ + String[] buttonlabels = new String[] { upLabel, downLabel }; + + fSortOrderList = new ListDialogField(null, buttonlabels, + new MemberSortLabelProvider()); + fSortOrderList.setDownButtonIndex(1); + fSortOrderList.setUpButtonIndex(0); + + // validate entries stored in store, false get defaults + List entries = getSortOrderList(string); + if (!isValidEntries(entries)) { + string = PHPeclipsePlugin.getDefault().getPreferenceStore() + .getDefaultString(PREF_OUTLINE_SORT_OPTION); + entries = getSortOrderList(string); + } + + fSortOrderList.setElements(entries); + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + // WorkbenchHelp.setHelp(getControl(), + // IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE); + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + + Composite composite = new Composite(parent, SWT.NONE); + + GridLayout layout = new GridLayout(); + layout.numColumns = 3; + layout.marginWidth = 0; + layout.marginHeight = 0; + composite.setLayout(layout); + + GridData data = new GridData(); + data.verticalAlignment = GridData.FILL; + data.horizontalAlignment = GridData.FILL_HORIZONTAL; + composite.setLayoutData(data); + + createSortOrderListDialogField(composite, 3); + Dialog.applyDialogFont(composite); + return composite; + } + + private void createSortOrderListDialogField(Composite composite, int span) { + fSortOrderList.doFillIntoGrid(composite, span); + + fSortOrderList.getLabelControl(null).dispose(); + + GridData data = (GridData) fSortOrderList.getListControl(null) + .getLayoutData(); + data.grabExcessHorizontalSpace = true; + data.verticalAlignment = 0; + data.heightHint = SWTUtil.getTableHeightHint(fSortOrderList + .getTableViewer().getTable(), 8); + } + + /* + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + String string = getPreferenceStore().getDefaultString( + PREF_OUTLINE_SORT_OPTION); + fSortOrderList.setElements(getSortOrderList(string)); + } + + /* + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + // reorders elements in the Outline based on selection + public boolean performOk() { + // update outline view + + // save preferences + IPreferenceStore store = getPreferenceStore(); + + StringBuffer buf = new StringBuffer(); + List curr = fSortOrderList.getElements(); + for (Iterator iter = curr.iterator(); iter.hasNext();) { + String s = (String) iter.next(); + buf.append(s); + buf.append(','); + } + store.setValue(PREF_OUTLINE_SORT_OPTION, buf.toString()); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + return true; + } + + private class MemberSortLabelProvider extends LabelProvider { + + public MemberSortLabelProvider() { + } + + /* + * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object) + */ + public String getText(Object element) { + + if (element instanceof String) { + String s = (String) element; + if (s.equals(FIELDS)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$ + } else if (s.equals(CONSTRUCTORS)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$ + } else if (s.equals(METHODS)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$ + } else if (s.equals(STATIC_FIELDS)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$ + } else if (s.equals(STATIC_METHODS)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$ + } else if (s.equals(INIT)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$ + } else if (s.equals(STATIC_INIT)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$ + } else if (s.equals(TYPES)) { + return PreferencesMessages + .getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$ + } + } + return ""; //$NON-NLS-1$ + } + + /* + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object) + */ + public Image getImage(Object element) { + // access to image registry + ImageDescriptorRegistry registry = PHPeclipsePlugin + .getImageDescriptorRegistry(); + ImageDescriptor descriptor = null; + + if (element instanceof String) { + int visibility = Flags.AccPublic; + String s = (String) element; + if (s.equals(FIELDS)) { + // 0 will give the default field image + descriptor = JavaElementImageProvider + .getFieldImageDescriptor(false, visibility); + } else if (s.equals(CONSTRUCTORS)) { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.CONSTRUCTOR, + JavaElementImageProvider.SMALL_SIZE); + } else if (s.equals(METHODS)) { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + } else if (s.equals(STATIC_FIELDS)) { + descriptor = JavaElementImageProvider + .getFieldImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); + } else if (s.equals(STATIC_METHODS)) { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + // add a constructor adornment to the image descriptor + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); + } else if (s.equals(INIT)) { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + } else if (s.equals(STATIC_INIT)) { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, visibility); + descriptor = new JavaElementImageDescriptor(descriptor, + JavaElementImageDescriptor.STATIC, + JavaElementImageProvider.SMALL_SIZE); + } else if (s.equals(TYPES)) { + descriptor = JavaElementImageProvider + .getTypeImageDescriptor(false, true, + Flags.AccPublic); + } else { + descriptor = JavaElementImageProvider + .getMethodImageDescriptor(false, Flags.AccPublic); + } + return registry.get(descriptor); + } + return null; + } + + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MockupPreferenceStore.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java new file mode 100644 index 0000000..7a304ef --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OptionsConfigurationBlock.java @@ -0,0 +1,584 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.Map.Entry; + +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.SWT; +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.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.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Widget; + +/** + * Abstract options configuration block providing a general implementation for + * setting up an options configuration page. + * + * @since 2.1 + */ +public abstract class OptionsConfigurationBlock { + + protected static class ControlData { + private String fKey; + + private String[] fValues; + + public ControlData(String key, String[] values) { + fKey = key; + fValues = values; + } + + public String getKey() { + return fKey; + } + + public String getValue(boolean selection) { + int index = selection ? 0 : 1; + return fValues[index]; + } + + public String getValue(int index) { + return fValues[index]; + } + + public int getSelection(String value) { + if (value != null) { + for (int i = 0; i < fValues.length; i++) { + if (value.equals(fValues[i])) { + return i; + } + } + } + return fValues.length - 1; // assume the last option is the least + // severe + } + } + + protected Map fWorkingValues; + + protected ArrayList fCheckBoxes; + + protected ArrayList fComboBoxes; + + protected ArrayList fTextBoxes; + + protected HashMap fLabels; + + private SelectionListener fSelectionListener; + + private ModifyListener fTextModifyListener; + + protected IStatusChangeListener fContext; + + protected IJavaProject fProject; // project or null + + protected String[] fAllKeys; + + private Shell fShell; + + public OptionsConfigurationBlock(IStatusChangeListener context, + IJavaProject project, String[] allKeys) { + fContext = context; + fProject = project; + fAllKeys = allKeys; + + fWorkingValues = getOptions(true); + testIfOptionsComplete(fWorkingValues, allKeys); + + fCheckBoxes = new ArrayList(); + fComboBoxes = new ArrayList(); + fTextBoxes = new ArrayList(2); + fLabels = new HashMap(); + } + + private void testIfOptionsComplete(Map workingValues, String[] allKeys) { + for (int i = 0; i < allKeys.length; i++) { + if (workingValues.get(allKeys[i]) == null) { + PHPeclipsePlugin + .logErrorMessage("preference option missing: " + allKeys[i] + " (" + this.getClass().getName() + ')'); //$NON-NLS-1$//$NON-NLS-2$ + } + } + } + + protected Map getOptions(boolean inheritJavaCoreOptions) { + if (fProject != null) { + return fProject.getOptions(inheritJavaCoreOptions); + } else { + return JavaCore.getOptions(); + } + } + + protected Map getDefaultOptions() { + return JavaCore.getDefaultOptions(); + } + + public final boolean hasProjectSpecificOptions() { + if (fProject != null) { + Map settings = fProject.getOptions(false); + String[] allKeys = fAllKeys; + for (int i = 0; i < allKeys.length; i++) { + if (settings.get(allKeys[i]) != null) { + return true; + } + } + } + return false; + } + + protected void setOptions(Map map) { + if (fProject != null) { + Map oldOptions = fProject.getOptions(false); + fProject.setOptions(map); + firePropertyChangeEvents(oldOptions, map); + } else { + JavaCore.setOptions((Hashtable) map); + } + } + + /** + * Computes the differences between the given old and new options and fires + * corresponding property change events on the Java plugin's mockup + * preference store. + * + * @param oldOptions + * The old options + * @param newOptions + * The new options + */ + private void firePropertyChangeEvents(Map oldOptions, Map newOptions) { + oldOptions = new HashMap(oldOptions); + Object source = fProject.getProject(); + MockupPreferenceStore store = PHPeclipsePlugin.getDefault() + .getMockupPreferenceStore(); + Iterator iter = newOptions.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = (Entry) iter.next(); + + String name = (String) entry.getKey(); + Object oldValue = oldOptions.get(name); + Object newValue = entry.getValue(); + + if ((oldValue != null && !oldValue.equals(newValue)) + || (oldValue == null && newValue != null)) + store.firePropertyChangeEvent(source, name, oldValue, newValue); + oldOptions.remove(name); + } + + iter = oldOptions.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = (Entry) iter.next(); + store.firePropertyChangeEvent(source, (String) entry.getKey(), + entry.getValue(), null); + } + } + + protected Shell getShell() { + return fShell; + } + + protected void setShell(Shell shell) { + fShell = shell; + } + + protected abstract Control createContents(Composite parent); + + protected Button addCheckBox(Composite parent, String label, String key, + String[] values, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = 3; + gd.horizontalIndent = indent; + + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + checkBox.setData(data); + checkBox.setLayoutData(gd); + checkBox.addSelectionListener(getSelectionListener()); + + String currValue = (String) fWorkingValues.get(key); + checkBox.setSelection(data.getSelection(currValue) == 0); + + fCheckBoxes.add(checkBox); + + return checkBox; + } + + protected Combo addComboBox(Composite parent, String label, String key, + String[] values, String[] valueLabels, int indent) { + ControlData data = new ControlData(key, values); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indent; + + Label labelControl = new Label(parent, SWT.LEFT | SWT.WRAP); + labelControl.setText(label); + labelControl.setLayoutData(gd); + + Combo comboBox = new Combo(parent, SWT.READ_ONLY); + comboBox.setItems(valueLabels); + comboBox.setData(data); + comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); + comboBox.addSelectionListener(getSelectionListener()); + + fLabels.put(comboBox, labelControl); + + Label placeHolder = new Label(parent, SWT.NONE); + placeHolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + String currValue = (String) fWorkingValues.get(key); + comboBox.select(data.getSelection(currValue)); + + fComboBoxes.add(comboBox); + return comboBox; + } + +// protected void addInversedComboBox(Composite parent, String label, +// String key, String[] values, String[] valueLabels, int indent) { +// ControlData data = new ControlData(key, values); +// +// GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); +// gd.horizontalIndent = indent; +// gd.horizontalSpan = 3; +// +// Composite composite = new Composite(parent, SWT.NONE); +// GridLayout layout = new GridLayout(); +// layout.marginHeight = 0; +// layout.marginWidth = 0; +// layout.numColumns = 2; +// composite.setLayout(layout); +// composite.setLayoutData(gd); +// +// Combo comboBox = new Combo(composite, SWT.READ_ONLY); +// comboBox.setItems(valueLabels); +// comboBox.setData(data); +// comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); +// comboBox.addSelectionListener(getSelectionListener()); +// +// Label labelControl = new Label(composite, SWT.LEFT | SWT.WRAP); +// labelControl.setText(label); +// labelControl.setLayoutData(new GridData()); +// +// fLabels.put(comboBox, labelControl); +// +// String currValue = (String) fWorkingValues.get(key); +// comboBox.select(data.getSelection(currValue)); +// +// fComboBoxes.add(comboBox); +// } + + protected Text addTextField(Composite parent, String label, String key, + int indent, int widthHint) { + Label labelControl = new Label(parent, SWT.NONE); + labelControl.setText(label); + labelControl.setLayoutData(new GridData()); + + Text textBox = new Text(parent, SWT.BORDER | SWT.SINGLE); + textBox.setData(key); + textBox.setLayoutData(new GridData()); + + fLabels.put(textBox, labelControl); + + String currValue = (String) fWorkingValues.get(key); + if (currValue != null) { + textBox.setText(currValue); + } + textBox.addModifyListener(getTextModifyListener()); + + GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + if (widthHint != 0) { + data.widthHint = widthHint; + } + data.horizontalIndent = indent; + data.horizontalSpan = 2; + textBox.setLayoutData(data); + + fTextBoxes.add(textBox); + return textBox; + } + + protected SelectionListener getSelectionListener() { + if (fSelectionListener == null) { + fSelectionListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + controlChanged(e.widget); + } + }; + } + return fSelectionListener; + } + + protected ModifyListener getTextModifyListener() { + if (fTextModifyListener == null) { + fTextModifyListener = new ModifyListener() { + public void modifyText(ModifyEvent e) { + textChanged((Text) e.widget); + } + }; + } + return fTextModifyListener; + } + + protected void controlChanged(Widget widget) { + ControlData data = (ControlData) widget.getData(); + String newValue = null; + if (widget instanceof Button) { + newValue = data.getValue(((Button) widget).getSelection()); + } else if (widget instanceof Combo) { + newValue = data.getValue(((Combo) widget).getSelectionIndex()); + } else { + return; + } + fWorkingValues.put(data.getKey(), newValue); + + validateSettings(data.getKey(), newValue); + } + + protected void textChanged(Text textControl) { + String key = (String) textControl.getData(); + String number = textControl.getText(); + fWorkingValues.put(key, number); + validateSettings(key, number); + } + +// protected boolean checkValue(String key, String value) { +// return value.equals(fWorkingValues.get(key)); +// } + + /* + * (non-javadoc) Update fields and validate. @param changedKey Key that + * changed, or null, if all changed. + */ + protected abstract void validateSettings(String changedKey, String newValue); + + protected String[] getTokens(String text, String separator) { + StringTokenizer tok = new StringTokenizer(text, separator); //$NON-NLS-1$ + int nTokens = tok.countTokens(); + String[] res = new String[nTokens]; + for (int i = 0; i < res.length; i++) { + res[i] = tok.nextToken().trim(); + } + return res; + } + + public boolean performOk(boolean enabled) { + String[] allKeys = fAllKeys; + Map actualOptions = getOptions(false); + + // preserve other options + boolean hasChanges = false; + for (int i = 0; i < allKeys.length; i++) { + String key = allKeys[i]; + String oldVal = (String) actualOptions.get(key); + String val = null; + if (enabled) { + val = (String) fWorkingValues.get(key); + if (val != null && !val.equals(oldVal)) { + hasChanges = true; + actualOptions.put(key, val); + } + } else { + if (oldVal != null) { + actualOptions.remove(key); + hasChanges = true; + } + } + } + + if (hasChanges) { + boolean doBuild = false; + String[] strings = getFullBuildDialogStrings(fProject == null); + if (strings != null) { + MessageDialog dialog = new MessageDialog(getShell(), + strings[0], null, strings[1], MessageDialog.QUESTION, + new String[] { IDialogConstants.YES_LABEL, + IDialogConstants.NO_LABEL, + IDialogConstants.CANCEL_LABEL }, 2); + int res = dialog.open(); + if (res == 0) { + doBuild = true; + } else if (res != 1) { + return false; // cancel pressed + } + } + setOptions(actualOptions); + if (doBuild) { + boolean res = doFullBuild(); + if (!res) { + return false; + } + } + } + return true; + } + + protected abstract String[] getFullBuildDialogStrings( + boolean workspaceSettings); + + protected boolean doFullBuild() { + + Job buildJob = new Job(PreferencesMessages + .getString("OptionsConfigurationBlock.job.title")) { //$NON-NLS-1$ + /* + * (non-Javadoc) + * + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + protected IStatus run(IProgressMonitor monitor) { + try { + if (fProject != null) { + monitor + .setTaskName(PreferencesMessages + .getFormattedString( + "OptionsConfigurationBlock.buildproject.taskname", fProject.getElementName())); //$NON-NLS-1$ + fProject.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + new SubProgressMonitor(monitor, 1)); + PHPeclipsePlugin.getWorkspace().build( + IncrementalProjectBuilder.INCREMENTAL_BUILD, + new SubProgressMonitor(monitor, 1)); + } else { + monitor + .setTaskName(PreferencesMessages + .getString("OptionsConfigurationBlock.buildall.taskname")); //$NON-NLS-1$ + PHPeclipsePlugin.getWorkspace().build( + IncrementalProjectBuilder.FULL_BUILD, + new SubProgressMonitor(monitor, 2)); + } + } catch (CoreException e) { + return e.getStatus(); + } catch (OperationCanceledException e) { + return Status.CANCEL_STATUS; + } finally { + monitor.done(); + } + return Status.OK_STATUS; + } + + public boolean belongsTo(Object family) { + return ResourcesPlugin.FAMILY_MANUAL_BUILD == family; + } + }; + + buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory() + .buildRule()); + buildJob.setUser(true); + buildJob.schedule(); + return true; + } + + public void performDefaults() { + fWorkingValues = getDefaultOptions(); + updateControls(); + validateSettings(null, null); + } + + protected void updateControls() { + // update the UI + for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { + updateCheckBox((Button) fCheckBoxes.get(i)); + } + for (int i = fComboBoxes.size() - 1; i >= 0; i--) { + updateCombo((Combo) fComboBoxes.get(i)); + } + for (int i = fTextBoxes.size() - 1; i >= 0; i--) { + updateText((Text) fTextBoxes.get(i)); + } + } + + protected void updateCombo(Combo curr) { + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.select(data.getSelection(currValue)); + } + + protected void updateCheckBox(Button curr) { + ControlData data = (ControlData) curr.getData(); + + String currValue = (String) fWorkingValues.get(data.getKey()); + curr.setSelection(data.getSelection(currValue) == 0); + } + + protected void updateText(Text curr) { + String key = (String) curr.getData(); + + String currValue = (String) fWorkingValues.get(key); + if (currValue != null) { + curr.setText(currValue); + } + } + +// protected Button getCheckBox(String key) { +// for (int i = fCheckBoxes.size() - 1; i >= 0; i--) { +// Button curr = (Button) fCheckBoxes.get(i); +// ControlData data = (ControlData) curr.getData(); +// if (key.equals(data.getKey())) { +// return curr; +// } +// } +// return null; +// } + + protected Combo getComboBox(String key) { + for (int i = fComboBoxes.size() - 1; i >= 0; i--) { + Combo curr = (Combo) fComboBoxes.get(i); + ControlData data = (ControlData) curr.getData(); + if (key.equals(data.getKey())) { + return curr; + } + } + return null; + } + +// protected void setComboEnabled(String key, boolean enabled) { +// Combo combo = getComboBox(key); +// Label label = (Label) fLabels.get(combo); +// combo.setEnabled(enabled); +// label.setEnabled(enabled); +// } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/OverlayPreferenceStore.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java new file mode 100644 index 0000000..fdb8eb8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/SpellingPreferencePage.java @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/** + * Preference page for spell checking preferences. + * + * @since 3.0 + */ +public class SpellingPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { + + /** The spelling configuration block */ + private final SpellingConfigurationBlock fBlock = new SpellingConfigurationBlock( + this, null); + + /** + * Creates a new spelling preference page. + */ + public SpellingPreferencePage() { + + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PreferencesMessages + .getString("SpellingPreferencePage.description")); //$NON-NLS-1$ + setTitle(PreferencesMessages.getString("SpellingPreferencePage.title")); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) + */ + protected Control createContents(final Composite parent) { + + final Control control = fBlock.createContents(parent); + Dialog.applyDialogFont(control); + + return control; + } + + /* + * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) + */ + public void createControl(final Composite parent) { + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); + } + + /* + * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(final IWorkbench workbench) { + // Do nothing + } + + /* + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { + fBlock.performDefaults(); + + super.performDefaults(); + } + + /* + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { + + if (!fBlock.performOk(true)) + return false; + + return super.performOk(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(final IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + + StatusUtil.applyToStatusLine(this, status); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java new file mode 100644 index 0000000..f16ecab --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TemplateEditorSourceViewerConfiguration.java @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.util.Iterator; + +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; +import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.IColorManager; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ContentAssistant; +import org.eclipse.jface.text.contentassist.IContentAssistant; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.TemplateVariableResolver; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.ui.texteditor.ITextEditor; + +public class TemplateEditorSourceViewerConfiguration extends + PHPSourceViewerConfiguration { + + private static class TemplateVariableTextHover implements ITextHover { + + private TemplateVariableProcessor fProcessor; + + /** + * @param type + */ + public TemplateVariableTextHover(TemplateVariableProcessor processor) { + fProcessor = processor; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, + * org.eclipse.jface.text.IRegion) + */ + public String getHoverInfo(ITextViewer textViewer, IRegion subject) { + try { + IDocument doc = textViewer.getDocument(); + int offset = subject.getOffset(); + if (offset >= 2 && "${".equals(doc.get(offset - 2, 2))) { //$NON-NLS-1$ + String varName = doc.get(offset, subject.getLength()); + TemplateContextType contextType = fProcessor + .getContextType(); + if (contextType != null) { + Iterator iter = contextType.resolvers(); + while (iter.hasNext()) { + TemplateVariableResolver var = (TemplateVariableResolver) iter + .next(); + if (varName.equals(var.getType())) { + return var.getDescription(); + } + } + } + } + } catch (BadLocationException e) { + } + return null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, + * int) + */ + public IRegion getHoverRegion(ITextViewer textViewer, int offset) { + if (textViewer != null) { + return JavaWordFinder + .findWord(textViewer.getDocument(), offset); + } + return null; + } + + } + + private final TemplateVariableProcessor fProcessor; + + public TemplateEditorSourceViewerConfiguration(IColorManager colorManager, + IPreferenceStore store, ITextEditor editor, + TemplateVariableProcessor processor) { + super(colorManager, store, editor, IPHPPartitions.PHP_PARTITIONING); + fProcessor = processor; + } + + /* + * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) + */ + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + IColorManager manager = textTools.getColorManager(); + + ContentAssistant assistant = new ContentAssistant(); + assistant.setContentAssistProcessor(fProcessor, + IDocument.DEFAULT_CONTENT_TYPE); + // Register the same processor for strings and single line comments to + // get code completion at the start of those partitions. + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_DQ); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_SQ); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_STRING_HEREDOC); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_SINGLELINE_COMMENT); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_MULTILINE_COMMENT); + assistant.setContentAssistProcessor(fProcessor, + IPHPPartitions.PHP_PHPDOC_COMMENT); + + assistant.enableAutoInsert(store + .getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); + assistant.enableAutoActivation(store + .getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); + assistant.setAutoActivationDelay(store + .getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); + assistant + .setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); + assistant + .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + + Color background = getColor(store, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); + assistant.setContextInformationPopupBackground(background); + assistant.setContextSelectorBackground(background); + assistant.setProposalSelectorBackground(background); + + Color foreground = getColor(store, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); + assistant.setContextInformationPopupForeground(foreground); + assistant.setContextSelectorForeground(foreground); + assistant.setProposalSelectorForeground(foreground); + + return assistant; + } + + private Color getColor(IPreferenceStore store, String key, + IColorManager manager) { + RGB rgb = PreferenceConverter.getColor(store, key); + return manager.getColor(rgb); + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) + * @since 2.1 + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType, int stateMask) { + return new TemplateVariableTextHover(fProcessor); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskConfigurationBlock.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskInputDialog.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java new file mode 100644 index 0000000..69613cf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPreferencePage.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +/* + * The page to configure the compiler options. + */ +public class TodoTaskPreferencePage extends PreferencePage implements + IWorkbenchPreferencePage, IStatusChangeListener { + + public static final String ID = "net.sourceforge.phpdt.ui.preferences.TodoTaskPreferencePage"; //$NON-NLS-1$ + + private TodoTaskConfigurationBlock fConfigurationBlock; + + public TodoTaskPreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + // setDescription(PreferencesMessages.getString("TodoTaskPreferencePage.description")); + // //$NON-NLS-1$ + + // only used when page is shown programatically + setTitle(PreferencesMessages.getString("TodoTaskPreferencePage.title")); //$NON-NLS-1$ + + fConfigurationBlock = new TodoTaskConfigurationBlock(this, null); + } + + /* + * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all + // preference pages + super.createControl(parent); + PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), + IJavaHelpContextIds.TODOTASK_PREFERENCE_PAGE); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + Control result = fConfigurationBlock.createContents(parent); + Dialog.applyDialogFont(result); + return result; + } + + /* + * @see IPreferencePage#performOk() + */ + public boolean performOk() { + if (!fConfigurationBlock.performOk(true)) { + return false; + } + return super.performOk(); + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fConfigurationBlock.performDefaults(); + super.performDefaults(); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/TodoTaskPropertyPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/AbstractJavaScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/BufferedDocumentScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CompositeReconcilingStrategy.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java new file mode 100644 index 0000000..c331757 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ContentAssistPreference.java @@ -0,0 +1,329 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text; + +import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCompletionProcessor; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.IColorManager; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.HTMLCompletionProcessor; +import net.sourceforge.phpeclipse.phpeditor.php.PHPCompletionProcessor; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.text.contentassist.ContentAssistant; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; + +public class ContentAssistPreference { + + /** Preference key for content assist auto activation */ + private final static String AUTOACTIVATION = PreferenceConstants.CODEASSIST_AUTOACTIVATION; + + /** Preference key for content assist auto activation delay */ + private final static String AUTOACTIVATION_DELAY = PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY; + + /** Preference key for content assist proposal color */ + private final static String PROPOSALS_FOREGROUND = PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND; + + /** Preference key for content assist proposal color */ + private final static String PROPOSALS_BACKGROUND = PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND; + + /** Preference key for content assist parameters color */ + private final static String PARAMETERS_FOREGROUND = PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND; + + /** Preference key for content assist parameters color */ + private final static String PARAMETERS_BACKGROUND = PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND; + + /** Preference key for content assist completion replacement color */ + //private final static String COMPLETION_REPLACEMENT_FOREGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND; + + /** Preference key for content assist completion replacement color */ + //private final static String COMPLETION_REPLACEMENT_BACKGROUND = PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND; + + /** Preference key for content assist auto insert */ + private final static String AUTOINSERT = PreferenceConstants.CODEASSIST_AUTOINSERT; + + /** Preference key for php content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_JAVA = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA; + + /** Preference key for phpdoc content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_JAVADOC = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC; + + /** Preference key for html content assist auto activation triggers */ + private final static String AUTOACTIVATION_TRIGGERS_HTML = PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML; + + /** Preference key for visibility of proposals */ + //private final static String SHOW_VISIBLE_PROPOSALS = PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS; + + /** Preference key for alphabetic ordering of proposals */ + private final static String ORDER_PROPOSALS = PreferenceConstants.CODEASSIST_ORDER_PROPOSALS; + + /** Preference key for case sensitivity of propsals */ + private final static String CASE_SENSITIVITY = PreferenceConstants.CODEASSIST_CASE_SENSITIVITY; + + /** Preference key for adding imports on code assist */ + //private final static String ADD_IMPORT = PreferenceConstants.CODEASSIST_ADDIMPORT; + + /** Preference key for inserting content assist */ + //private static final String INSERT_COMPLETION = PreferenceConstants.CODEASSIST_INSERT_COMPLETION; + + /** Preference key for filling argument names on method completion */ + //private static final String FILL_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES; + + /** Preference key for guessing argument names on method completion */ + //private static final String GUESS_METHOD_ARGUMENTS = PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS; + + private static Color getColor(IPreferenceStore store, String key, + IColorManager manager) { + RGB rgb = PreferenceConverter.getColor(store, key); + return manager.getColor(rgb); + } + + private static Color getColor(IPreferenceStore store, String key) { + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + return getColor(store, key, textTools.getColorManager()); + } + + private static PHPCompletionProcessor getJavaProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.PHP_PARTITIONING); + if (p instanceof PHPCompletionProcessor) + return (PHPCompletionProcessor) p; + return null; + } + + private static PHPDocCompletionProcessor getJavaDocProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.PHP_PHPDOC_COMMENT); + if (p instanceof PHPDocCompletionProcessor) + return (PHPDocCompletionProcessor) p; + return null; + } + + private static HTMLCompletionProcessor getHTMLProcessor( + ContentAssistant assistant) { + IContentAssistProcessor p = assistant + .getContentAssistProcessor(IPHPPartitions.HTML); + if (p instanceof HTMLCompletionProcessor) + return (HTMLCompletionProcessor) p; + return null; + } + + private static void configureJavaProcessor(ContentAssistant assistant, + IPreferenceStore store) { + PHPCompletionProcessor pcp = getJavaProcessor(assistant); + if (pcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); + if (triggers != null) + pcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + boolean enabled; + // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); + // jcp.restrictProposalsToVisibility(enabled); + // + // enabled= store.getBoolean(CASE_SENSITIVITY); + // jcp.restrictProposalsToMatchingCases(enabled); + // + enabled = store.getBoolean(ORDER_PROPOSALS); + pcp.orderProposalsAlphabetically(enabled); + // + // enabled= store.getBoolean(ADD_IMPORT); + // jcp.allowAddingImports(enabled); + } + + private static void configureJavaDocProcessor(ContentAssistant assistant, + IPreferenceStore store) { + PHPDocCompletionProcessor pdcp = getJavaDocProcessor(assistant); + if (pdcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); + if (triggers != null) + pdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + + boolean enabled = store.getBoolean(CASE_SENSITIVITY); + pdcp.restrictProposalsToMatchingCases(enabled); + + enabled = store.getBoolean(ORDER_PROPOSALS); + pdcp.orderProposalsAlphabetically(enabled); + } + + private static void configureHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store) { + HTMLCompletionProcessor hcp = getHTMLProcessor(assistant); + if (hcp == null) + return; + + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + hcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + + boolean enabled; + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + + enabled = store.getBoolean(ORDER_PROPOSALS); + hcp.orderProposalsAlphabetically(enabled); + } + + /** + * Configure the given content assistant from the given store. + */ + public static void configure(ContentAssistant assistant, + IPreferenceStore store) { + + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + IColorManager manager = textTools.getColorManager(); + + boolean enabled = store.getBoolean(AUTOACTIVATION); + assistant.enableAutoActivation(enabled); + + int delay = store.getInt(AUTOACTIVATION_DELAY); + assistant.setAutoActivationDelay(delay); + + Color c = getColor(store, PROPOSALS_FOREGROUND, manager); + assistant.setProposalSelectorForeground(c); + + c = getColor(store, PROPOSALS_BACKGROUND, manager); + assistant.setProposalSelectorBackground(c); + + c = getColor(store, PARAMETERS_FOREGROUND, manager); + assistant.setContextInformationPopupForeground(c); + assistant.setContextSelectorForeground(c); + + c = getColor(store, PARAMETERS_BACKGROUND, manager); + assistant.setContextInformationPopupBackground(c); + assistant.setContextSelectorBackground(c); + + enabled = store.getBoolean(AUTOINSERT); + assistant.enableAutoInsert(enabled); + + configureJavaProcessor(assistant, store); + configureJavaDocProcessor(assistant, store); + configureHTMLProcessor(assistant, store); + } + + private static void changeJavaProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + PHPCompletionProcessor jcp = getJavaProcessor(assistant); + if (jcp == null) + return; + + if (AUTOACTIVATION_TRIGGERS_JAVA.equals(key)) { + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVA); + if (triggers != null) + jcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + } + // else if (SHOW_VISIBLE_PROPOSALS.equals(key)) { + // boolean enabled= store.getBoolean(SHOW_VISIBLE_PROPOSALS); + // jcp.restrictProposalsToVisibility(enabled); + // } else if (CASE_SENSITIVITY.equals(key)) { + // boolean enabled= store.getBoolean(CASE_SENSITIVITY); + // jcp.restrictProposalsToMatchingCases(enabled); } + else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jcp.orderProposalsAlphabetically(enable); + // } else if (ADD_IMPORT.equals(key)) { + // boolean enabled= store.getBoolean(ADD_IMPORT); + // jcp.allowAddingImports(enabled); + } + } + + private static void changeJavaDocProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + PHPDocCompletionProcessor jdcp = getJavaDocProcessor(assistant); + if (jdcp == null) + return; + + if (AUTOACTIVATION_TRIGGERS_JAVADOC.equals(key)) { + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_JAVADOC); + if (triggers != null) + jdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + } else if (CASE_SENSITIVITY.equals(key)) { + boolean enabled = store.getBoolean(CASE_SENSITIVITY); + jdcp.restrictProposalsToMatchingCases(enabled); + } else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jdcp.orderProposalsAlphabetically(enable); + } + } + + private static void changeHTMLProcessor(ContentAssistant assistant, + IPreferenceStore store, String key) { + HTMLCompletionProcessor jdcp = getHTMLProcessor(assistant); + if (jdcp == null) + return; + + if (AUTOACTIVATION_TRIGGERS_HTML.equals(key)) { + String triggers = store.getString(AUTOACTIVATION_TRIGGERS_HTML); + if (triggers != null) + jdcp.setCompletionProposalAutoActivationCharacters(triggers + .toCharArray()); + // } else if (CASE_SENSITIVITY.equals(key)) { + // boolean enabled = store.getBoolean(CASE_SENSITIVITY); + // jdcp.restrictProposalsToMatchingCases(enabled); + } else if (ORDER_PROPOSALS.equals(key)) { + boolean enable = store.getBoolean(ORDER_PROPOSALS); + jdcp.orderProposalsAlphabetically(enable); + } + } + + /** + * Changes the configuration of the given content assistant according to the + * given property change event and the given preference store. + */ + public static void changeConfiguration(ContentAssistant assistant, + IPreferenceStore store, PropertyChangeEvent event) { + + String p = event.getProperty(); + + if (AUTOACTIVATION.equals(p)) { + boolean enabled = store.getBoolean(AUTOACTIVATION); + assistant.enableAutoActivation(enabled); + } else if (AUTOACTIVATION_DELAY.equals(p)) { + int delay = store.getInt(AUTOACTIVATION_DELAY); + assistant.setAutoActivationDelay(delay); + } else if (PROPOSALS_FOREGROUND.equals(p)) { + Color c = getColor(store, PROPOSALS_FOREGROUND); + assistant.setProposalSelectorForeground(c); + } else if (PROPOSALS_BACKGROUND.equals(p)) { + Color c = getColor(store, PROPOSALS_BACKGROUND); + assistant.setProposalSelectorBackground(c); + } else if (PARAMETERS_FOREGROUND.equals(p)) { + Color c = getColor(store, PARAMETERS_FOREGROUND); + assistant.setContextInformationPopupForeground(c); + assistant.setContextSelectorForeground(c); + } else if (PARAMETERS_BACKGROUND.equals(p)) { + Color c = getColor(store, PARAMETERS_BACKGROUND); + assistant.setContextInformationPopupBackground(c); + assistant.setContextSelectorBackground(c); + } else if (AUTOINSERT.equals(p)) { + boolean enabled = store.getBoolean(AUTOINSERT); + assistant.enableAutoInsert(enabled); + } + + changeJavaProcessor(assistant, store, p); + changeJavaDocProcessor(assistant, store, p); + changeHTMLProcessor(assistant, store, p); + } + +// public static boolean fillArgumentsOnMethodCompletion(IPreferenceStore store) { +// return store.getBoolean(FILL_METHOD_ARGUMENTS); +// } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/CustomSourceInformationControl.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/DocumentCharacterIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/FastJavaPartitionScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTML2TextReader.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLPrinter.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java new file mode 100644 index 0000000..211bc27 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/HTMLTextPresenter.java @@ -0,0 +1,195 @@ +package net.sourceforge.phpdt.internal.ui.text; + +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Iterator; + +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.DefaultInformationControl; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextPresentation; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.widgets.Display; + +public class HTMLTextPresenter implements + DefaultInformationControl.IInformationPresenter { + + private static final String LINE_DELIM = System.getProperty( + "line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + + private int fCounter; + + private boolean fEnforceUpperLineLimit; + + public HTMLTextPresenter(boolean enforceUpperLineLimit) { + super(); + fEnforceUpperLineLimit = enforceUpperLineLimit; + } + +// public HTMLTextPresenter() { +// this(true); +// } + + protected Reader createReader(String hoverInfo, + TextPresentation presentation) { + return new HTML2TextReader(new StringReader(hoverInfo), presentation); + } + + protected void adaptTextPresentation(TextPresentation presentation, + int offset, int insertLength) { + + int yoursStart = offset; + int yoursEnd = offset + insertLength - 1; + yoursEnd = Math.max(yoursStart, yoursEnd); + + Iterator e = presentation.getAllStyleRangeIterator(); + while (e.hasNext()) { + + StyleRange range = (StyleRange) e.next(); + + int myStart = range.start; + int myEnd = range.start + range.length - 1; + myEnd = Math.max(myStart, myEnd); + + if (myEnd < yoursStart) + continue; + + if (myStart < yoursStart) + range.length += insertLength; + else + range.start += insertLength; + } + } + + private void append(StringBuffer buffer, String string, + TextPresentation presentation) { + + int length = string.length(); + buffer.append(string); + + if (presentation != null) + adaptTextPresentation(presentation, fCounter, length); + + fCounter += length; + } + + private String getIndent(String line) { + int length = line.length(); + + int i = 0; + while (i < length && Character.isWhitespace(line.charAt(i))) + ++i; + + return (i == length ? line : line.substring(0, i)) + " "; //$NON-NLS-1$ + } + + /* + * @see IHoverInformationPresenter#updatePresentation(Display display, + * String, TextPresentation, int, int) + */ + public String updatePresentation(Display display, String hoverInfo, + TextPresentation presentation, int maxWidth, int maxHeight) { + + if (hoverInfo == null) + return null; + + GC gc = new GC(display); + try { + + StringBuffer buffer = new StringBuffer(); + int maxNumberOfLines = Math.round(maxHeight + / gc.getFontMetrics().getHeight()); + + fCounter = 0; + LineBreakingReader reader = new LineBreakingReader(createReader( + hoverInfo, presentation), gc, maxWidth); + + boolean lastLineFormatted = false; + String lastLineIndent = null; + + String line = reader.readLine(); + boolean lineFormatted = reader.isFormattedLine(); + boolean firstLineProcessed = false; + + while (line != null) { + + if (fEnforceUpperLineLimit && maxNumberOfLines <= 0) + break; + + if (firstLineProcessed) { + if (!lastLineFormatted) + append(buffer, LINE_DELIM, null); + else { + append(buffer, LINE_DELIM, presentation); + if (lastLineIndent != null) + append(buffer, lastLineIndent, presentation); + } + } + + append(buffer, line, null); + firstLineProcessed = true; + + lastLineFormatted = lineFormatted; + if (!lineFormatted) + lastLineIndent = null; + else if (lastLineIndent == null) + lastLineIndent = getIndent(line); + + line = reader.readLine(); + lineFormatted = reader.isFormattedLine(); + + maxNumberOfLines--; + } + + if (line != null) { + append(buffer, LINE_DELIM, lineFormatted ? presentation : null); + append(buffer, PHPUIMessages + .getString("HTMLTextPresenter.ellipsis"), presentation); //$NON-NLS-1$ + } + + return trim(buffer, presentation); + + } catch (IOException e) { + + PHPeclipsePlugin.log(e); + return null; + + } finally { + gc.dispose(); + } + } + + private String trim(StringBuffer buffer, TextPresentation presentation) { + + int length = buffer.length(); + + int end = length - 1; + while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) + --end; + + if (end == -1) + return ""; //$NON-NLS-1$ + + if (end < length - 1) + buffer.delete(end + 1, length); + else + end = length; + + int start = 0; + while (start < end && Character.isWhitespace(buffer.charAt(start))) + ++start; + + buffer.delete(0, start); + presentation.setResultWindow(new Region(start, buffer.length())); + return buffer.toString(); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/IPHPPartitions.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/ITypingRunListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaAnnotationHover.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaBreakIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java new file mode 100644 index 0000000..bdbe486 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java @@ -0,0 +1,151 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text; + +import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension; +import net.sourceforge.phpdt.internal.ui.text.java.JavaReconcilingStrategy; +import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Reconciling strategy for Java code. This is a composite strategy containing + * the regular java model reconciler and the comment spell checking strategy. + * + * @since 3.0 + */ +public class JavaCompositeReconcilingStrategy extends + CompositeReconcilingStrategy { + + private ITextEditor fEditor; + + private JavaReconcilingStrategy fJavaStrategy; + + /** + * Creates a new Java reconciling strategy. + * + * @param editor + * the editor of the strategy's reconciler + * @param documentPartitioning + * the document partitioning this strategy uses for configuration + */ + public JavaCompositeReconcilingStrategy(ITextEditor editor, + String documentPartitioning) { + fEditor = editor; + fJavaStrategy = new JavaReconcilingStrategy(editor); + setReconcilingStrategies(new IReconcilingStrategy[] { + fJavaStrategy, + new SpellReconcileStrategy(editor, documentPartitioning, + PreferenceConstants.getPreferenceStore()) }); + } + + /** + * Returns the problem requestor for the editor's input element. + * + * @return the problem requestor for the editor's input element + */ + private IProblemRequestorExtension getProblemRequestorExtension() { + IDocumentProvider p = fEditor.getDocumentProvider(); + if (p == null) { + try { + // work around for + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522 + p = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + } catch (NullPointerException npe) { + return null; + } + } + IAnnotationModel m = p.getAnnotationModel(fEditor.getEditorInput()); + if (m instanceof IProblemRequestorExtension) + return (IProblemRequestorExtension) m; + return null; + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, + * org.eclipse.jface.text.IRegion) + */ + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + IProblemRequestorExtension e = getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.reconcile(dirtyRegion, subRegion); + } finally { + e.endReportingSequence(); + } + } else { + super.reconcile(dirtyRegion, subRegion); + } + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion) + */ + public void reconcile(IRegion partition) { + IProblemRequestorExtension e = getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.reconcile(partition); + } finally { + e.endReportingSequence(); + } + } else { + super.reconcile(partition); + } + } + + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify + * true if listeners should be notified + */ + public void notifyListeners(boolean notify) { + fJavaStrategy.notifyListeners(notify); + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#initialReconcile() + */ + public void initialReconcile() { + IProblemRequestorExtension e = getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.initialReconcile(); + } finally { + e.endReportingSequence(); + } + } else { + super.initialReconcile(); + } + } + + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + fJavaStrategy.aboutToBeReconciled(); + + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaHeuristicScanner.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java new file mode 100644 index 0000000..d6b5cf1 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaIndenter.java @@ -0,0 +1,1520 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text; + +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.Plugin; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; + +/** + * Uses the {@link net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner}to + * get the indentation level for a certain position in a document. + * + *

+ * An instance holds some internal position in the document and is therefore not + * threadsafe. + *

+ * + * @since 3.0 + */ +public class JavaIndenter { + + /** The document being scanned. */ + private IDocument fDocument; + + /** The indentation accumulated by findPreviousIndenationUnit. */ + private int fIndent; + + /** + * The absolute (character-counted) indentation offset for special cases + * (method defs, array initializers) + */ + private int fAlign; + + /** The stateful scanposition for the indentation methods. */ + private int fPosition; + + /** The previous position. */ + private int fPreviousPos; + + /** The most recent token. */ + private int fToken; + + /** The line of fPosition. */ + private int fLine; + + /** + * The scanner we will use to scan the document. It has to be installed on + * the same document as the one we get. + */ + private JavaHeuristicScanner fScanner; + + /** + * Creates a new instance. + * + * @param document + * the document to scan + * @param scanner + * the {@link JavaHeuristicScanner} to be used for scanning the + * document. It must be installed on the same + * IDocument. + */ + public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) { + Assert.isNotNull(document); + Assert.isNotNull(scanner); + fDocument = document; + fScanner = scanner; + } + + /** + * Computes the indentation at the reference point of position. + * + * @param offset + * the offset in the document + * @return a String which reflects the indentation at the line in which the + * reference position to offset resides, or + * null if it cannot be determined + */ +// public StringBuffer getReferenceIndentation(int offset) { +// return getReferenceIndentation(offset, false); +// } + + /** + * Computes the indentation at the reference point of position. + * + * @param offset + * the offset in the document + * @param assumeOpeningBrace + * true if an opening brace should be assumed + * @return a String which reflects the indentation at the line in which the + * reference position to offset resides, or + * null if it cannot be determined + */ + private StringBuffer getReferenceIndentation(int offset, + boolean assumeOpeningBrace) { + + int unit; + if (assumeOpeningBrace) + unit = findReferencePosition(offset, Symbols.TokenLBRACE); + else + unit = findReferencePosition(offset, peekChar(offset)); + + // if we were unable to find anything, return null + if (unit == JavaHeuristicScanner.NOT_FOUND) + return null; + + return getLeadingWhitespace(unit); + + } + + /** + * Computes the indentation at offset. + * + * @param offset + * the offset in the document + * @return a String which reflects the correct indentation for the line in + * which offset resides, or null if it cannot be + * determined + */ + public StringBuffer computeIndentation(int offset) { + return computeIndentation(offset, false); + } + + /** + * Computes the indentation at offset. + * + * @param offset + * the offset in the document + * @param assumeOpeningBrace + * true if an opening brace should be assumed + * @return a String which reflects the correct indentation for the line in + * which offset resides, or null if it cannot be + * determined + */ + public StringBuffer computeIndentation(int offset, + boolean assumeOpeningBrace) { + + StringBuffer indent = getReferenceIndentation(offset, + assumeOpeningBrace); + + // handle special alignment + if (fAlign != JavaHeuristicScanner.NOT_FOUND) { + try { + // a special case has been detected. + IRegion line = fDocument.getLineInformationOfOffset(fAlign); + int lineOffset = line.getOffset(); + return createIndent(lineOffset, fAlign); + } catch (BadLocationException e) { + return null; + } + } + + if (indent == null) + return null; + + // add additional indent + //indent.append(createIndent(fIndent)); + indent.insert(0, createIndent(fIndent)); + if (fIndent < 0) + unindent(indent); + + return indent; + } + + /** + * Returns the indentation of the line at offset as a + * StringBuffer. If the offset is not valid, the empty + * string is returned. + * + * @param offset + * the offset in the document + * @return the indentation (leading whitespace) of the line in which + * offset is located + */ + private StringBuffer getLeadingWhitespace(int offset) { + StringBuffer indent = new StringBuffer(); + try { + IRegion line = fDocument.getLineInformationOfOffset(offset); + int lineOffset = line.getOffset(); + int nonWS = fScanner.findNonWhitespaceForwardInAnyPartition( + lineOffset, lineOffset + line.getLength()); + indent.append(fDocument.get(lineOffset, nonWS - lineOffset)); + return indent; + } catch (BadLocationException e) { + return indent; + } + } + + /** + * Reduces indentation in indent by one indentation unit. + * + * @param indent + * the indentation to be modified + */ + private void unindent(StringBuffer indent) { + CharSequence oneIndent = createIndent(); + int i = indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$ + if (i != -1) { + indent.delete(i, i + oneIndent.length()); + } + } + + /** + * Creates an indentation string of the length indent - start + 1, + * consisting of the content in fDocument in the range + * [start, indent), with every character replaced by a space except for + * tabs, which are kept as such. + * + *

+ * Every run of the number of spaces that make up a tab are replaced by a + * tab character. + *

+ * + * @return the indentation corresponding to the document content specified + * by start and indent + */ + private StringBuffer createIndent(int start, int indent) { + final int tabLen = prefTabLength(); + StringBuffer ret = new StringBuffer(); + try { + int spaces = 0; + while (start < indent) { + + char ch = fDocument.getChar(start); + if (ch == '\t') { + ret.append('\t'); + spaces = 0; + } else if (tabLen == -1) { + ret.append(' '); + } else { + spaces++; + if (spaces == tabLen) { + ret.append('\t'); + spaces = 0; + } + } + + start++; + } + // remainder + if (spaces == tabLen) + ret.append('\t'); + else + while (spaces-- > 0) + ret.append(' '); + + } catch (BadLocationException e) { + } + + return ret; + } + + /** + * Creates a string that represents the given number of indents (can be + * spaces or tabs..) + * + * @param indent + * the requested indentation level. + * + * @return the indentation specified by indent + */ + public StringBuffer createIndent(int indent) { + StringBuffer oneIndent = createIndent(); + + StringBuffer ret = new StringBuffer(); + while (indent-- > 0) + ret.append(oneIndent); + + return ret; + } + + /** + * Creates a string that represents one indent (can be spaces or tabs..) + * + * @return one indentation + */ + private StringBuffer createIndent() { + // get a sensible default when running without the infrastructure for + // testing + StringBuffer oneIndent = new StringBuffer(); + // JavaCore plugin= JavaCore.getJavaCore(); + PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); + if (plugin == null) { + oneIndent.append('\t'); + } else { + if (JavaCore.SPACE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) { + int tabLen = Integer + .parseInt(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE)); + for (int i = 0; i < tabLen; i++) + oneIndent.append(' '); + } else if (JavaCore.TAB + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) + oneIndent.append('\t'); + else + oneIndent.append('\t'); // default + } + return oneIndent; + } + + /** + * Returns the reference position regarding to indentation for + * offset, or NOT_FOUND. This method calls + * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} + * where nextChar is the next character after + * offset. + * + * @param offset + * the offset for which the reference is computed + * @return the reference statement relative to which offset + * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} + */ +// public int findReferencePosition(int offset) { +// return findReferencePosition(offset, peekChar(offset)); +// } + + /** + * Peeks the next char in the document that comes after offset + * on the same line as offset. + * + * @param offset + * the offset into document + * @return the token symbol of the next element, or TokenEOF if there is + * none + */ + private int peekChar(int offset) { + if (offset < fDocument.getLength()) { + try { + IRegion line = fDocument.getLineInformationOfOffset(offset); + int lineOffset = line.getOffset(); + int next = fScanner.nextToken(offset, lineOffset + + line.getLength()); + return next; + } catch (BadLocationException e) { + } + } + return Symbols.TokenEOF; + } + + /** + * Returns the reference position regarding to indentation for + * position, or NOT_FOUND. + * + *

+ * If peekNextChar is true, the next token + * after offset is read and taken into account when computing + * the indentation. Currently, if the next token is the first token on the + * line (i.e. only preceded by whitespace), the following tokens are + * specially handled: + *

    + *
  • switch labels are indented relative to the switch + * block
  • + *
  • opening curly braces are aligned correctly with the introducing code
  • + *
  • closing curly braces are aligned properly with the introducing code + * of the matching opening brace
  • + *
  • closing parenthesis' are aligned with their opening peer
  • + *
  • the else keyword is aligned with its if, + * anything else is aligned normally (i.e. with the base of any introducing + * statements).
  • + *
  • if there is no token on the same line after offset, + * the indentation is the same as for an else keyword
  • + *
+ * + * @param offset + * the offset for which the reference is computed + * @param nextToken + * the next token to assume in the document + * @return the reference statement relative to which offset + * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} + */ + public int findReferencePosition(int offset, int nextToken) { + boolean danglingElse = false; + boolean unindent = false; + boolean indent = false; + boolean matchBrace = false; + boolean matchParen = false; + boolean matchCase = false; + + // account for unindenation characters already typed in, but after + // position + // if they are on a line by themselves, the indentation gets adjusted + // accordingly + // + // also account for a dangling else + if (offset < fDocument.getLength()) { + try { + IRegion line = fDocument.getLineInformationOfOffset(offset); + int lineOffset = line.getOffset(); + int prevPos = Math.max(offset - 1, 0); + boolean isFirstTokenOnLine = fDocument.get(lineOffset, + prevPos + 1 - lineOffset).trim().length() == 0; + int prevToken = fScanner.previousToken(prevPos, + JavaHeuristicScanner.UNBOUND); + if (prevToken == Symbols.TokenEOF && nextToken == Symbols.TokenEOF) { + ITypedRegion partition = TextUtilities.getPartition(fDocument, IPHPPartitions.PHP_PARTITIONING, offset, true); + if (partition.getType().equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) { + fAlign = fScanner.getPosition(); + } else { + fAlign = JavaHeuristicScanner.NOT_FOUND; + } + return JavaHeuristicScanner.NOT_FOUND; + } + boolean bracelessBlockStart = fScanner.isBracelessBlockStart( + prevPos, JavaHeuristicScanner.UNBOUND); + + switch (nextToken) { + case Symbols.TokenEOF: + case Symbols.TokenELSE: + danglingElse = true; + break; + case Symbols.TokenCASE: + case Symbols.TokenDEFAULT: + if (isFirstTokenOnLine) + matchCase = true; + break; + case Symbols.TokenLBRACE: // for opening-brace-on-new-line + // style + // if (bracelessBlockStart && !prefIndentBracesForBlocks()) + // unindent= true; + // else if ((prevToken == Symbols.TokenCOLON || prevToken == + // Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && + // !prefIndentBracesForArrays()) + // unindent= true; + // else if (!bracelessBlockStart && + // prefIndentBracesForMethods()) + // indent= true; + // break; + if (bracelessBlockStart) + unindent = true; + else if ((prevToken == Symbols.TokenCOLON + || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET)) + unindent = true; + else if (!bracelessBlockStart) + indent = true; + break; + case Symbols.TokenRBRACE: // closing braces get unindented + if (isFirstTokenOnLine) + matchBrace = true; + break; + case Symbols.TokenRPAREN: + if (isFirstTokenOnLine) + matchParen = true; + break; + } + } catch (BadLocationException e) { + } + } else { + // assume an else could come if we are at the end of file + danglingElse = true; + } + + int ref = findReferencePosition(offset, danglingElse, matchBrace, + matchParen, matchCase); + if (unindent) + fIndent--; + if (indent) + fIndent++; + return ref; + } + + /** + * Returns the reference position regarding to indentation for + * position, or NOT_FOUND.fIndent + * will contain the relative indentation (in indentation units, not + * characters) after the call. If there is a special alignment (e.g. for a + * method declaration where parameters should be aligned), + * fAlign will contain the absolute position of the alignment + * reference in fDocument, otherwise fAlign + * is set to JavaHeuristicScanner.NOT_FOUND. + * + * @param offset + * the offset for which the reference is computed + * @param danglingElse + * whether a dangling else should be assumed at + * position + * @param matchBrace + * whether the position of the matching brace should be returned + * instead of doing code analysis + * @param matchParen + * whether the position of the matching parenthesis should be + * returned instead of doing code analysis + * @param matchCase + * whether the position of a switch statement reference should be + * returned (either an earlier case statement or the switch block + * brace) + * @return the reference statement relative to which position + * should be indented, or {@link JavaHeuristicScanner#NOT_FOUND} + */ + public int findReferencePosition(int offset, boolean danglingElse, + boolean matchBrace, boolean matchParen, boolean matchCase) { + fIndent = 0; // the indentation modification + fAlign = JavaHeuristicScanner.NOT_FOUND; + fPosition = offset; + + // forward cases + // an unindentation happens sometimes if the next token is special, + // namely on braces, parens and case labels + // align braces, but handle the case where we align with the method + // declaration start instead of + // the opening brace. + if (matchBrace) { + if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) { + try { + // align with the opening brace that is on a line by its own + int lineOffset = fDocument.getLineOffset(fLine); + if (lineOffset <= fPosition + && fDocument + .get(lineOffset, fPosition - lineOffset) + .trim().length() == 0) + return fPosition; + } catch (BadLocationException e) { + // concurrent modification - walk default path + } + // if the opening brace is not on the start of the line, skip to + // the start + int pos = skipToStatementStart(true, true); + fIndent = 0; // indent is aligned with reference position + return pos; + } else { + // if we can't find the matching brace, the heuristic is to + // unindent + // by one against the normal position + int pos = findReferencePosition(offset, danglingElse, false, + matchParen, matchCase); + fIndent--; + return pos; + } + } + + // align parenthesis' + if (matchParen) { + if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) + return fPosition; + else { + // if we can't find the matching paren, the heuristic is to + // unindent + // by one against the normal position + int pos = findReferencePosition(offset, danglingElse, + matchBrace, false, matchCase); + fIndent--; + return pos; + } + } + + // the only reliable way to get case labels aligned (due to many + // different styles of using braces in a block) + // is to go for another case statement, or the scope opening brace + if (matchCase) { + return matchCaseAlignment(); + } + + nextToken(); + switch (fToken) { + case Symbols.TokenRBRACE: + // skip the block and fall through + // if we can't complete the scope, reset the scan position + int pos = fPosition; + if (!skipScope()) + fPosition = pos; + case Symbols.TokenSEMICOLON: + // this is the 90% case: after a statement block + // the end of the previous statement / block previous.end + // search to the end of the statement / block before the previous; + // the token just after that is previous.start + return skipToStatementStart(danglingElse, false); + + // scope introduction: special treat who special is + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + return handleScopeIntroduction(offset + 1); + + case Symbols.TokenEOF: + // trap when hitting start of document + return 0; + + case Symbols.TokenEQUAL: + // indent assignments + fIndent = prefAssignmentIndent(); + return fPosition; + + case Symbols.TokenCOLON: + // TODO handle ternary deep indentation + fIndent = prefCaseBlockIndent(); + return fPosition; + + case Symbols.TokenQUESTIONMARK: + if (prefTernaryDeepAlign()) { + setFirstElementAlignment(fPosition, offset + 1); + return fPosition; + } else { + fIndent = prefTernaryIndent(); + return fPosition; + } + + // indentation for blockless introducers: + case Symbols.TokenDO: + case Symbols.TokenWHILE: + case Symbols.TokenELSE: + fIndent = prefSimpleIndent(); + return fPosition; + case Symbols.TokenRPAREN: + int line = fLine; + if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) { + int scope = fPosition; + nextToken(); + if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE + || fToken == Symbols.TokenFOR) { + fIndent = prefSimpleIndent(); + return fPosition; + } + fPosition = scope; + if (looksLikeMethodDecl()) { + return skipToStatementStart(danglingElse, false); + } + } + // restore + fPosition = offset; + fLine = line; + // else: fall through to default + + case Symbols.TokenCOMMA: + // inside a list of some type + // easy if there is already a list item before with its own + // indentation - we just align + // if not: take the start of the list ( LPAREN, LBRACE, LBRACKET ) + // and either align or + // indent by list-indent + default: + // inside whatever we don't know about: similar to the list case: + // if we are inside a continued expression, then either align with a + // previous line that has indentation + // or indent from the expression start line (either a scope + // introducer or the start of the expr). + return skipToPreviousListItemOrListStart(); + + } + } + + /** + * Skips to the start of a statement that ends at the current position. + * + * @param danglingElse + * whether to indent aligned with the last if + * @param isInBlock + * whether the current position is inside a block, which limits + * the search scope to the next scope introducer + * @return the reference offset of the start of the statement + */ + private int skipToStatementStart(boolean danglingElse, boolean isInBlock) { + while (true) { + nextToken(); + + if (isInBlock) { + switch (fToken) { + // exit on all block introducers + case Symbols.TokenIF: + case Symbols.TokenELSE: + case Symbols.TokenSYNCHRONIZED: + case Symbols.TokenCOLON: + case Symbols.TokenSTATIC: + case Symbols.TokenCATCH: + case Symbols.TokenDO: + case Symbols.TokenWHILE: + case Symbols.TokenFINALLY: + case Symbols.TokenFOR: + case Symbols.TokenTRY: + return fPosition; + + case Symbols.TokenSWITCH: + fIndent = prefCaseIndent(); + return fPosition; + } + } + + switch (fToken) { + // scope introduction through: LPAREN, LBRACE, LBRACKET + // search stop on SEMICOLON, RBRACE, COLON, EOF + // -> the next token is the start of the statement (i.e. previousPos + // when backward scanning) + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + case Symbols.TokenSEMICOLON: + case Symbols.TokenEOF: + return fPreviousPos; + + case Symbols.TokenCOLON: + int pos = fPreviousPos; + if (!isConditional()) + return pos; + break; + + case Symbols.TokenRBRACE: + // RBRACE is a little tricky: it can be the end of an array + // definition, but + // usually it is the end of a previous block + pos = fPreviousPos; // store state + if (skipScope() && looksLikeArrayInitializerIntro()) + continue; // it's an array + else + return pos; // it's not - do as with all the above + + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + pos = fPreviousPos; + if (skipScope()) + break; + else + return pos; + + // IF / ELSE: align the position after the conditional block + // with the if + // so we are ready for an else, except if danglingElse is false + // in order for this to work, we must skip an else to its if + case Symbols.TokenIF: + if (danglingElse) + return fPosition; + else + break; + case Symbols.TokenELSE: + // skip behind the next if, as we have that one covered + pos = fPosition; + if (skipNextIF()) + break; + else + return pos; + + case Symbols.TokenDO: + // align the WHILE position with its do + return fPosition; + + case Symbols.TokenWHILE: + // this one is tricky: while can be the start of a while loop + // or the end of a do - while + pos = fPosition; + if (hasMatchingDo()) { + // continue searching from the DO on + break; + } else { + // continue searching from the WHILE on + fPosition = pos; + break; + } + default: + // keep searching + + } + + } + } + + /** + * Returns true if the colon at the current position is part of a + * conditional (ternary) expression, false otherwise. + * + * @return true if the colon at the current position is part of a + * conditional + */ + private boolean isConditional() { + while (true) { + nextToken(); + switch (fToken) { + + // search for case, otherwise return true + case Symbols.TokenIDENT: + continue; + case Symbols.TokenCASE: + return false; + + default: + return true; + } + } + } + + /** + * Returns as a reference any previous switch labels (case + * or default) or the offset of the brace that scopes the + * switch statement. Sets fIndent to + * prefCaseIndent upon a match. + * + * @return the reference offset for a switch label + */ + private int matchCaseAlignment() { + while (true) { + nextToken(); + switch (fToken) { + // invalid cases: another case label or an LBRACE must come before a + // case + // -> bail out with the current position + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACKET: + case Symbols.TokenEOF: + return fPosition; + case Symbols.TokenLBRACE: + // opening brace of switch statement + fIndent = 1; //prefCaseIndent() is for Java + return fPosition; + case Symbols.TokenCASE: + case Symbols.TokenDEFAULT: + // align with previous label + fIndent = 0; + return fPosition; + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + case Symbols.TokenRBRACE: + skipScope(); + break; + default: + // keep searching + continue; + } + } + } + + /** + * Returns the reference position for a list element. The algorithm tries to + * match any previous indentation on the same list. If there is none, the + * reference position returned is determined depending on the type of list: + * The indentation will either match the list scope introducer (e.g. for + * method declarations), so called deep indents, or simply increase the + * indentation by a number of standard indents. See also + * {@link #handleScopeIntroduction(int)}. + * + * @return the reference position for a list item: either a previous list + * item that has its own indentation, or the list introduction + * start. + */ + private int skipToPreviousListItemOrListStart() { + int startLine = fLine; + int startPosition = fPosition; + while (true) { + nextToken(); + + // if any line item comes with its own indentation, adapt to it + if (fLine < startLine) { + try { + int lineOffset = fDocument.getLineOffset(startLine); + int bound = Math.min(fDocument.getLength(), + startPosition + 1); + fAlign = fScanner.findNonWhitespaceForwardInAnyPartition( + lineOffset, bound); + } catch (BadLocationException e) { + // ignore and return just the position + } + return startPosition; + } + + switch (fToken) { + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + case Symbols.TokenRBRACE: + skipScope(); + break; + + // scope introduction: special treat who special is + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + return handleScopeIntroduction(startPosition + 1); + + case Symbols.TokenSEMICOLON: + return fPosition; + case Symbols.TokenQUESTIONMARK: + if (prefTernaryDeepAlign()) { + setFirstElementAlignment(fPosition - 1, fPosition + 1); + } else { + fIndent = prefTernaryIndent(); + } + return fPosition; + case Symbols.TokenEOF: + return 0; + + case Symbols.TokenEQUAL: + // indent assignments + fIndent= prefAssignmentIndent(); + return fPosition; + } + } + } + + /** + * Skips a scope and positions the cursor (fPosition) on + * the token that opens the scope. Returns true if a matching + * peer could be found, false otherwise. The current token + * when calling must be one out of Symbols.TokenRPAREN, + * Symbols.TokenRBRACE, and + * Symbols.TokenRBRACKET. + * + * @return true if a matching peer was found, + * false otherwise + */ + private boolean skipScope() { + switch (fToken) { + case Symbols.TokenRPAREN: + return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN); + case Symbols.TokenRBRACKET: + return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET); + case Symbols.TokenRBRACE: + return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); + default: + Assert.isTrue(false); + return false; + } + } + + /** + * Handles the introduction of a new scope. The current token must be one + * out of Symbols.TokenLPAREN, + * Symbols.TokenLBRACE, and + * Symbols.TokenLBRACKET. Returns as the reference position + * either the token introducing the scope or - if available - the first java + * token after that. + * + *

+ * Depending on the type of scope introduction, the indentation will align + * (deep indenting) with the reference position (fAlign will + * be set to the reference position) or fIndent will be set + * to the number of indentation units. + *

+ * + * @param bound + * the bound for the search for the first token after the scope + * introduction. + * @return + */ + private int handleScopeIntroduction(int bound) { + switch (fToken) { + // scope introduction: special treat who special is + case Symbols.TokenLPAREN: + int pos = fPosition; // store + + // special: method declaration deep indentation + if (looksLikeMethodDecl()) { + if (prefMethodDeclDeepIndent()) + return setFirstElementAlignment(pos, bound); + else { + fIndent = prefMethodDeclIndent(); + return pos; + } + } else { + fPosition = pos; + if (looksLikeMethodCall()) { + if (prefMethodCallDeepIndent()) + return setFirstElementAlignment(pos, bound); + else { + fIndent = prefMethodCallIndent(); + return pos; + } + } else if (prefParenthesisDeepIndent()) + return setFirstElementAlignment(pos, bound); + } + + // normal: return the parenthesis as reference + fIndent = prefParenthesisIndent(); + return pos; + + case Symbols.TokenLBRACE: + pos = fPosition; // store + + // special: array initializer + if (looksLikeArrayInitializerIntro()) + if (prefArrayDeepIndent()) + return setFirstElementAlignment(pos, bound); + else + fIndent = prefArrayIndent(); + else + fIndent = prefBlockIndent(); + + // normal: skip to the statement start before the scope introducer + // opening braces are often on differently ending indents than e.g. + // a method definition + fPosition = pos; // restore + return skipToStatementStart(true, true); // set to true to match + // the first if + + case Symbols.TokenLBRACKET: + pos = fPosition; // store + + // special: method declaration deep indentation + if (prefArrayDimensionsDeepIndent()) { + return setFirstElementAlignment(pos, bound); + } + + // normal: return the bracket as reference + fIndent = prefBracketIndent(); + return pos; // restore + + default: + Assert.isTrue(false); + return -1; // dummy + } + } + + /** + * Sets the deep indent offset (fAlign) to either the + * offset right after scopeIntroducerOffset or - if available - + * the first Java token after scopeIntroducerOffset, but + * before bound. + * + * @param scopeIntroducerOffset + * the offset of the scope introducer + * @param bound + * the bound for the search for another element + * @return the reference position + */ + private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) { + int firstPossible = scopeIntroducerOffset + 1; // align with the first + // position after the + // scope intro + fAlign = fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, + bound); + if (fAlign == JavaHeuristicScanner.NOT_FOUND) + fAlign = firstPossible; + return fAlign; + } + + /** + * Returns true if the next token received after calling + * nextToken is either an equal sign or an array designator + * ('[]'). + * + * @return true if the next elements look like the start of + * an array definition + */ + private boolean looksLikeArrayInitializerIntro() { + nextToken(); + if (fToken == Symbols.TokenEQUAL || skipBrackets()) { + return true; + } + return false; + } + + /** + * Skips over the next if keyword. The current token when + * calling this method must be an else keyword. Returns + * true if a matching if could be found, + * false otherwise. The cursor (fPosition) + * is set to the offset of the if token. + * + * @return true if a matching if token was + * found, false otherwise + */ + private boolean skipNextIF() { + Assert.isTrue(fToken == Symbols.TokenELSE); + + while (true) { + nextToken(); + switch (fToken) { + // scopes: skip them + case Symbols.TokenRPAREN: + case Symbols.TokenRBRACKET: + case Symbols.TokenRBRACE: + skipScope(); + break; + + case Symbols.TokenIF: + // found it, return + return true; + case Symbols.TokenELSE: + // recursively skip else-if blocks + skipNextIF(); + break; + + // shortcut scope starts + case Symbols.TokenLPAREN: + case Symbols.TokenLBRACE: + case Symbols.TokenLBRACKET: + case Symbols.TokenEOF: + return false; + } + } + } + + /** + * while(condition); is ambiguous when parsed backwardly, as it is a valid + * statement by its own, so we have to check whether there is a matching do. + * A do can either be separated from the while by a block, or + * by a single statement, which limits our search distance. + * + * @return true if the while currently in + * fToken has a matching do. + */ + private boolean hasMatchingDo() { + Assert.isTrue(fToken == Symbols.TokenWHILE); + nextToken(); + switch (fToken) { + case Symbols.TokenRBRACE: + skipScope(); // and fall thru + case Symbols.TokenSEMICOLON: + skipToStatementStart(false, false); + return fToken == Symbols.TokenDO; + } + return false; + } + + /** + * Skips brackets if the current token is a RBRACKET. There can be nothing + * but whitespace in between, this is only to be used for [] + * elements. + * + * @return true if a [] could be scanned, the + * current token is left at the LBRACKET. + */ + private boolean skipBrackets() { + if (fToken == Symbols.TokenRBRACKET) { + nextToken(); + if (fToken == Symbols.TokenLBRACKET) { + return true; + } + } + return false; + } + + /** + * Reads the next token in backward direction from the heuristic scanner and + * sets the fields fToken, fPreviousPosition and + * fPosition accordingly. + */ + private void nextToken() { + nextToken(fPosition); + } + + /** + * Reads the next token in backward direction of start from + * the heuristic scanner and sets the fields + * fToken, fPreviousPosition and fPosition + * accordingly. + */ + private void nextToken(int start) { + fToken = fScanner + .previousToken(start - 1, JavaHeuristicScanner.UNBOUND); + fPreviousPos = start; + fPosition = fScanner.getPosition() + 1; + try { + fLine = fDocument.getLineOfOffset(fPosition); + } catch (BadLocationException e) { + fLine = -1; + } + } + + /** + * Returns true if the current tokens look like a method + * declaration header (i.e. only the return type and method name). The + * heuristic calls nextToken and expects an identifier + * (method name) and a type declaration (an identifier with optional + * brackets) which also covers the visibility modifier of constructors; it + * does not recognize package visible constructors. + * + * @return true if the current position looks like a method + * declaration header. + */ + private boolean looksLikeMethodDecl() { + /* + * TODO This heuristic does not recognize package private constructors + * since those do have neither type nor visibility keywords. One option + * would be to go over the parameter list, but that might be empty as + * well - hard to do without an AST... + */ + + nextToken(); + if (fToken == Symbols.TokenIDENT) { // method name + do + nextToken(); + while (skipBrackets()); // optional brackets for array valued return + // types + return fToken == Symbols.TokenIDENT; // type name + + } + return false; + } + + /** + * Returns true if the current tokens look like a method call + * header (i.e. an identifier as opposed to a keyword taking parenthesized + * parameters such as if). + *

+ * The heuristic calls nextToken and expects an identifier + * (method name). + * + * @return true if the current position looks like a method + * call header. + */ + private boolean looksLikeMethodCall() { + nextToken(); + return fToken == Symbols.TokenIDENT; // method name + } + + /** + * Scans tokens for the matching opening peer. The internal cursor (fPosition) + * is set to the offset of the opening peer if found. + * + * @return true if a matching token was found, + * false otherwise + */ + private boolean skipScope(int openToken, int closeToken) { + + int depth = 1; + + while (true) { + nextToken(); + + if (fToken == closeToken) { + depth++; + } else if (fToken == openToken) { + depth--; + if (depth == 0) + return true; + } else if (fToken == Symbols.TokenEOF) { + return false; + } + } + } + + // TODO adjust once there are per-project settings + + private int prefTabLength() { + int tabLen; + // JavaCore core= JavaCore.getJavaCore(); + PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); + // if (core != null && plugin != null) + if (plugin != null) + if (JavaCore.SPACE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) + // if the formatter uses chars to mark indentation, then don't + // substitute any chars + tabLen = -1; // results in no tabs being substituted for + // space runs + else + // if the formatter uses tabs to mark indentations, use the + // visual setting from the editor + // to get nicely aligned indentations + tabLen = plugin + .getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + else + tabLen = 4; // sensible default for testing + + return tabLen; + } + + private boolean prefArrayDimensionsDeepIndent() { + return true; // sensible default + } + + private int prefArrayIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); + try { + if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) + return 1; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return prefContinuationIndent(); // default + } + + private boolean prefArrayDeepIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER); + try { + return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return true; + } + + private boolean prefTernaryDeepAlign() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); + try { + return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + return false; + } + + private int prefTernaryIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION); + try { + if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) + return 1; + else + return prefContinuationIndent(); + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return prefContinuationIndent(); + } + + private int prefCaseIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + if (DefaultCodeFormatterConstants.TRUE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH))) + return prefBlockIndent(); + else + return 0; + } + + return 0; // sun standard + } + + private int prefAssignmentIndent() { + return prefBlockIndent(); + } + + private int prefCaseBlockIndent() { + if (true) + return prefBlockIndent(); + + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + if (DefaultCodeFormatterConstants.TRUE + .equals(JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES))) + return prefBlockIndent(); + else + return 0; + } + return prefBlockIndent(); // sun standard + } + + private int prefSimpleIndent() { + return prefBlockIndent(); + } + + private int prefBracketIndent() { + return prefBlockIndent(); + } + + private boolean prefMethodDeclDeepIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); + try { + return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return true; + } + + private int prefMethodDeclIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION); + try { + if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) + return 1; + else + return prefContinuationIndent(); + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + return 1; + } + + private boolean prefMethodCallDeepIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); + try { + return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + return false; // sensible default + } + + private int prefMethodCallIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION); + try { + if (DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_BY_ONE) + return 1; + else + return prefContinuationIndent(); + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return 1; // sensible default + } + + private boolean prefParenthesisDeepIndent() { + + if (true) // don't do parenthesis deep indentation + return false; + + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); + try { + return DefaultCodeFormatterConstants.getIndentStyle(option) == DefaultCodeFormatterConstants.INDENT_ON_COLUMN; + } catch (IllegalArgumentException e) { + // ignore and return default + } + } + + return false; // sensible default + } + + private int prefParenthesisIndent() { + return prefContinuationIndent(); + } + + private int prefBlockIndent() { + return 1; // sensible default + } + +// private boolean prefIndentBracesForBlocks() { +// Plugin plugin = JavaCore.getPlugin(); +// if (plugin != null) { +// String option = JavaCore +// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); +// return option +// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); +// } +// +// return false; // sensible default +// } + +// private boolean prefIndentBracesForArrays() { +// Plugin plugin = JavaCore.getPlugin(); +// if (plugin != null) { +// String option = JavaCore +// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER); +// return option +// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); +// } +// +// return false; // sensible default +// } + +// private boolean prefIndentBracesForMethods() { +// Plugin plugin = JavaCore.getPlugin(); +// if (plugin != null) { +// String option = JavaCore +// .getOption(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); +// return option +// .equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED); +// } +// +// return false; // sensible default +// } + + private int prefContinuationIndent() { + Plugin plugin = JavaCore.getPlugin(); + if (plugin != null) { + String option = JavaCore + .getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION); + try { + return Integer.parseInt(option); + } catch (NumberFormatException e) { + // ignore and return default + } + } + + return 2; // sensible default + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java new file mode 100644 index 0000000..b99ee96 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java @@ -0,0 +1,639 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IParent; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.ui.actions.OpenActionUtil; +import net.sourceforge.phpdt.internal.ui.util.StringMatcher; +import net.sourceforge.phpdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; +import net.sourceforge.phpdt.ui.JavaElementSorter; +import net.sourceforge.phpdt.ui.StandardJavaElementContentProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.text.IInformationControl; +import org.eclipse.jface.text.IInformationControlExtension; +import org.eclipse.jface.text.IInformationControlExtension2; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.jface.viewers.IBaseLabelProvider; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.StructuredViewer; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +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.graphics.Color; +import org.eclipse.swt.graphics.FontMetrics; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +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.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Layout; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.TreeItem; + +/** + * @author dmegert + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. To enable and disable the creation of type + * comments go to Window>Preferences>Java>Code Generation. + */ +public class JavaOutlineInformationControl implements IInformationControl, + IInformationControlExtension, IInformationControlExtension2 { + + /** + * The NamePatternFilter selects the elements which match the given string + * patterns. + *

+ * The following characters have special meaning: ? => any character * => + * any string + *

+ * + * @since 2.0 + */ + private static class NamePatternFilter extends ViewerFilter { + private String fPattern; + + private StringMatcher fMatcher; + + private ILabelProvider fLabelProvider; + + private Viewer fViewer; + + private StringMatcher getMatcher() { + return fMatcher; + } + + /* + * (non-Javadoc) Method declared on ViewerFilter. + */ + public boolean select(Viewer viewer, Object parentElement, + Object element) { + if (fMatcher == null) + return true; + + ILabelProvider labelProvider = getLabelProvider(viewer); + + String matchName = null; + if (labelProvider != null) + matchName = ((ILabelProvider) labelProvider).getText(element); + else if (element instanceof IJavaElement) + matchName = ((IJavaElement) element).getElementName(); + + if (matchName != null && fMatcher.match(matchName)) + return true; + + return hasUnfilteredChild(viewer, element); + } + + private ILabelProvider getLabelProvider(Viewer viewer) { + if (fViewer == viewer) + return fLabelProvider; + + fLabelProvider = null; + IBaseLabelProvider baseLabelProvider = null; + if (viewer instanceof StructuredViewer) + baseLabelProvider = ((StructuredViewer) viewer) + .getLabelProvider(); + + if (baseLabelProvider instanceof ILabelProvider) + fLabelProvider = (ILabelProvider) baseLabelProvider; + + return fLabelProvider; + } + + private boolean hasUnfilteredChild(Viewer viewer, Object element) { + IJavaElement[] children; + if (element instanceof IParent) { + try { + children = ((IParent) element).getChildren(); + } catch (JavaModelException ex) { + return false; + } + for (int i = 0; i < children.length; i++) + if (select(viewer, element, children[i])) + return true; + } + return false; + } + + /** + * Sets the patterns to filter out for the receiver. + *

+ * The following characters have special meaning: ? => any character * => + * any string + *

+ */ + public void setPattern(String pattern) { + fPattern = pattern; + if (fPattern == null) { + fMatcher = null; + return; + } + boolean ignoreCase = pattern.toLowerCase().equals(pattern); + fMatcher = new StringMatcher(pattern, ignoreCase, false); + } + } + + private static class BorderFillLayout extends Layout { + + /** The border widths. */ + final int fBorderSize; + + /** + * Creates a fill layout with a border. + */ + public BorderFillLayout(int borderSize) { + if (borderSize < 0) + throw new IllegalArgumentException(); + fBorderSize = borderSize; + } + + /** + * Returns the border size. + */ + public int getBorderSize() { + return fBorderSize; + } + + /* + * @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, + * int, int, boolean) + */ + protected Point computeSize(Composite composite, int wHint, int hHint, + boolean flushCache) { + + Control[] children = composite.getChildren(); + Point minSize = new Point(0, 0); + + if (children != null) { + for (int i = 0; i < children.length; i++) { + Point size = children[i].computeSize(wHint, hHint, + flushCache); + minSize.x = Math.max(minSize.x, size.x); + minSize.y = Math.max(minSize.y, size.y); + } + } + + minSize.x += fBorderSize * 2 + RIGHT_MARGIN; + minSize.y += fBorderSize * 2; + + return minSize; + } + + /* + * @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, + * boolean) + */ + protected void layout(Composite composite, boolean flushCache) { + + Control[] children = composite.getChildren(); + Point minSize = new Point(composite.getClientArea().width, + composite.getClientArea().height); + + if (children != null) { + for (int i = 0; i < children.length; i++) { + Control child = children[i]; + child.setSize(minSize.x - fBorderSize * 2, minSize.y + - fBorderSize * 2); + child.setLocation(fBorderSize, fBorderSize); + } + } + } + } + + /** Border thickness in pixels. */ + private static final int BORDER = 1; + + /** Right margin in pixels. */ + private static final int RIGHT_MARGIN = 3; + + /** The control's shell */ + private Shell fShell; + + /** The composite */ + Composite fComposite; + + /** The control's text widget */ + private Text fFilterText; + + /** The control's tree widget */ + private TreeViewer fTreeViewer; + + /** The control width constraint */ + private int fMaxWidth = -1; + + /** The control height constraint */ + private int fMaxHeight = -1; + + private StringMatcher fStringMatcher; + + /** + * Creates a tree information control with the given shell as parent. The + * given style is applied to the tree widget. + * + * @param parent + * the parent shell + * @param style + * the additional styles for the tree widget + */ + public JavaOutlineInformationControl(Shell parent, int style) { + this(parent, SWT.RESIZE, style); + } + + /** + * Creates a tree information control with the given shell as parent. No + * additional styles are applied. + * + * @param parent + * the parent shell + */ +// public JavaOutlineInformationControl(Shell parent) { +// this(parent, SWT.NONE); +// } + + /** + * Creates a tree information control with the given shell as parent. The + * given styles are applied to the shell and the tree widget. + * + * @param parent + * the parent shell + * @param shellStyle + * the additional styles for the shell + * @param treeStyle + * the additional styles for the tree widget + */ + public JavaOutlineInformationControl(Shell parent, int shellStyle, + int treeStyle) { + fShell = new Shell(parent, shellStyle); + Display display = fShell.getDisplay(); + fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); + + // Composite for filter text and tree + fComposite = new Composite(fShell, SWT.RESIZE); + GridLayout layout = new GridLayout(1, false); + fComposite.setLayout(layout); + fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + createFilterText(fComposite); + createTreeViewer(fComposite, treeStyle); + + int border = ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; + fShell.setLayout(new BorderFillLayout(border)); + + setInfoSystemColor(); + installFilter(); + } + + private void createTreeViewer(Composite parent, int style) { + Tree tree = new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI)); + GridData data = new GridData(GridData.FILL_BOTH); + tree.setLayoutData(data); + + fTreeViewer = new TreeViewer(tree); + + // Hide import declartions but show the container + // fTreeViewer.addFilter(new ViewerFilter() { + // public boolean select(Viewer viewer, Object parentElement, Object + // element) { + // return !(element instanceof IImportDeclaration); + // } + // }); + + fTreeViewer.setContentProvider(new StandardJavaElementContentProvider( + true, true)); + fTreeViewer.setSorter(new JavaElementSorter()); + fTreeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); + + AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( + AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS + | JavaElementLabels.F_APP_TYPE_SIGNATURE, + AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); + fTreeViewer + .setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); + + fTreeViewer.getTree().addKeyListener(new KeyListener() { + public void keyPressed(KeyEvent e) { + if (e.character == 0x1B) // ESC + dispose(); + } + + public void keyReleased(KeyEvent e) { + // do nothing + } + }); + + fTreeViewer.getTree().addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + // do nothing + } + + public void widgetDefaultSelected(SelectionEvent e) { + gotoSelectedElement(); + } + }); + } + + private Text createFilterText(Composite parent) { + fFilterText = new Text(parent, SWT.FLAT); + + GridData data = new GridData(); + GC gc = new GC(parent); + gc.setFont(parent.getFont()); + FontMetrics fontMetrics = gc.getFontMetrics(); + gc.dispose(); + + data.heightHint = org.eclipse.jface.dialogs.Dialog + .convertHeightInCharsToPixels(fontMetrics, 1); + data.horizontalAlignment = GridData.FILL; + data.verticalAlignment = GridData.BEGINNING; + fFilterText.setLayoutData(data); + + fFilterText.addKeyListener(new KeyListener() { + public void keyPressed(KeyEvent e) { + if (e.keyCode == 0x0D) // return + gotoSelectedElement(); + if (e.keyCode == SWT.ARROW_DOWN) + fTreeViewer.getTree().setFocus(); + if (e.keyCode == SWT.ARROW_UP) + fTreeViewer.getTree().setFocus(); + if (e.character == 0x1B) // ESC + dispose(); + } + + public void keyReleased(KeyEvent e) { + // do nothing + } + }); + + // Horizonral separator line + Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL + | SWT.LINE_DOT); + separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + return fFilterText; + } + + private void setInfoSystemColor() { + Display display = fShell.getDisplay(); + setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } + + private void installFilter() { + final NamePatternFilter viewerFilter = new NamePatternFilter(); + fTreeViewer.addFilter(viewerFilter); + fFilterText.setText(""); //$NON-NLS-1$ + + fFilterText.addModifyListener(new ModifyListener() { + public void modifyText(ModifyEvent e) { + String pattern = fFilterText.getText(); + if (pattern != null) { + int length = pattern.length(); + if (length == 0) + pattern = null; + else if (pattern.charAt(length - 1) != '*') + pattern = pattern + '*'; + } else + pattern = null; + viewerFilter.setPattern(pattern); + fStringMatcher = viewerFilter.getMatcher(); + fTreeViewer.getControl().setRedraw(false); + fTreeViewer.refresh(); + fTreeViewer.expandAll(); + selectFirstMatch(); + fTreeViewer.getControl().setRedraw(true); + } + }); + } + + private void gotoSelectedElement() { + Object selectedElement = ((IStructuredSelection) fTreeViewer + .getSelection()).getFirstElement(); + if (selectedElement != null) { + try { + dispose(); + OpenActionUtil.open(selectedElement, true); + } catch (CoreException ex) { + PHPeclipsePlugin.log(ex); + } + } + } + + /** + * Selects the first element in the tree which matches the current filter + * pattern. + */ + private void selectFirstMatch() { + Tree tree = fTreeViewer.getTree(); + Object element = findElement(tree.getItems()); + if (element != null) + fTreeViewer.setSelection(new StructuredSelection(element), true); + else + fTreeViewer.setSelection(StructuredSelection.EMPTY); + } + + private IJavaElement findElement(TreeItem[] items) { + ILabelProvider labelProvider = (ILabelProvider) fTreeViewer + .getLabelProvider(); + for (int i = 0; i < items.length; i++) { + IJavaElement element = (IJavaElement) items[i].getData(); + if (fStringMatcher == null) + return element; + + if (element != null) { + String label = labelProvider.getText(element); + if (fStringMatcher.match(label)) + return element; + } + + element = findElement(items[i].getItems()); + if (element != null) + return element; + } + return null; + } + + /* + * @see IInformationControl#setInformation(String) + */ + public void setInformation(String information) { + // this method is ignored, see IInformationControlExtension2 + } + + /* + * @see IInformationControlExtension2#setInput(Object) + */ + public void setInput(Object information) { + fFilterText.setText(""); //$NON-NLS-1$ + if (information == null || information instanceof String) { + setInput(null); + return; + } + IJavaElement je = (IJavaElement) information; + IJavaElement sel = null; + ICompilationUnit cu = (ICompilationUnit) je + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null) + sel = cu; + else + sel = je.getAncestor(IJavaElement.CLASS_FILE); + fTreeViewer.setInput(sel); + fTreeViewer.setSelection(new StructuredSelection(information)); + } + + /* + * @see IInformationControl#setVisible(boolean) + */ + public void setVisible(boolean visible) { + fShell.setVisible(visible); + } + + /* + * @see IInformationControl#dispose() + */ + public void dispose() { + if (fShell != null) { + if (!fShell.isDisposed()) + fShell.dispose(); + fShell = null; + fTreeViewer = null; + fComposite = null; + fFilterText = null; + } + } + + /* + * @see org.eclipse.jface.text.IInformationControlExtension#hasContents() + */ + public boolean hasContents() { + return fTreeViewer != null && fTreeViewer.getInput() != null; + } + + /* + * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, + * int) + */ + public void setSizeConstraints(int maxWidth, int maxHeight) { + fMaxWidth = maxWidth; + fMaxHeight = maxHeight; + } + + /* + * @see org.eclipse.jface.text.IInformationControl#computeSizeHint() + */ + public Point computeSizeHint() { + return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); + } + + /* + * @see IInformationControl#setLocation(Point) + */ + public void setLocation(Point location) { + Rectangle trim = fShell.computeTrim(0, 0, 0, 0); + Point textLocation = fComposite.getLocation(); + location.x += trim.x - textLocation.x; + location.y += trim.y - textLocation.y; + fShell.setLocation(location); + } + + /* + * @see IInformationControl#setSize(int, int) + */ + public void setSize(int width, int height) { + fShell.setSize(width, height); + } + + /* + * @see IInformationControl#addDisposeListener(DisposeListener) + */ + public void addDisposeListener(DisposeListener listener) { + fShell.addDisposeListener(listener); + } + + /* + * @see IInformationControl#removeDisposeListener(DisposeListener) + */ + public void removeDisposeListener(DisposeListener listener) { + fShell.removeDisposeListener(listener); + } + + /* + * @see IInformationControl#setForegroundColor(Color) + */ + public void setForegroundColor(Color foreground) { + fTreeViewer.getTree().setForeground(foreground); + fFilterText.setForeground(foreground); + fComposite.setForeground(foreground); + } + + /* + * @see IInformationControl#setBackgroundColor(Color) + */ + public void setBackgroundColor(Color background) { + fTreeViewer.getTree().setBackground(background); + fFilterText.setBackground(background); + fComposite.setBackground(background); + } + + /* + * @see IInformationControl#isFocusControl() + */ + public boolean isFocusControl() { + return fTreeViewer.getControl().isFocusControl() + || fFilterText.isFocusControl(); + } + + /* + * @see IInformationControl#setFocus() + */ + public void setFocus() { + fShell.forceFocus(); + fFilterText.setFocus(); + } + + /* + * @see IInformationControl#addFocusListener(FocusListener) + */ + public void addFocusListener(FocusListener listener) { + fShell.addFocusListener(listener); + } + + /* + * @see IInformationControl#removeFocusListener(FocusListener) + */ + public void removeFocusListener(FocusListener listener) { + fShell.removeFocusListener(listener); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaPresentationReconciler.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java new file mode 100644 index 0000000..11bf1c3 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java @@ -0,0 +1,462 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text; + +import net.sourceforge.phpdt.core.ElementChangedEvent; +import net.sourceforge.phpdt.core.IElementChangedListener; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; + +import org.eclipse.core.resources.IMarkerDelta; +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.IWorkspace; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.MonoReconciler; +import org.eclipse.swt.events.ShellAdapter; +import org.eclipse.swt.events.ShellEvent; +import org.eclipse.swt.events.ShellListener; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IPartListener; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchPartSite; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * A reconciler that is also activated on editor activation. + */ +public class JavaReconciler extends MonoReconciler { + + /** + * Internal part listener for activating the reconciler. + */ + private class PartListener implements IPartListener { + + /* + * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) + */ + public void partActivated(IWorkbenchPart part) { + if (part == fTextEditor && hasJavaModelChanged()) + JavaReconciler.this.forceReconciling(); + } + + /* + * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) + */ + public void partBroughtToTop(IWorkbenchPart part) { + } + + /* + * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) + */ + public void partClosed(IWorkbenchPart part) { + } + + /* + * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) + */ + public void partDeactivated(IWorkbenchPart part) { + if (part == fTextEditor) + setJavaModelChanged(false); + } + + /* + * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) + */ + public void partOpened(IWorkbenchPart part) { + } + } + + /** + * Internal Shell activation listener for activating the reconciler. + */ + private class ActivationListener extends ShellAdapter { + + private Control fControl; + + public ActivationListener(Control control) { + fControl = control; + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellActivated(ShellEvent e) { + if (!fControl.isDisposed() && fControl.isVisible() + && hasJavaModelChanged()) + JavaReconciler.this.forceReconciling(); + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellDeactivated(ShellEvent e) { + setJavaModelChanged(false); + } + } + + /** + * Internal Java element changed listener + * + * @since 3.0 + */ + private class ElementChangedListener implements IElementChangedListener { + /* + * @see net.sourceforge.phpdt.core.IElementChangedListener#elementChanged(net.sourceforge.phpdt.core.ElementChangedEvent) + */ + public void elementChanged(ElementChangedEvent event) { + setJavaModelChanged(true); + } + } + + /** + * Internal resource change listener. + * + * @since 3.0 + */ + class ResourceChangeListener implements IResourceChangeListener { + + private IResource getResource() { + IEditorInput input = fTextEditor.getEditorInput(); + if (input instanceof IFileEditorInput) { + IFileEditorInput fileInput = (IFileEditorInput) input; + return fileInput.getFile(); + } + return null; + } + + /* + * @see IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) + */ + public void resourceChanged(IResourceChangeEvent e) { + IResourceDelta delta = e.getDelta(); + IResource resource = getResource(); + if (delta != null && resource != null) { + IResourceDelta child = delta.findMember(resource.getFullPath()); + if (child != null) { + IMarkerDelta[] deltas = child.getMarkerDeltas(); + if (deltas.length > 0) + forceReconciling(); + } + } + } + } + + /** The reconciler's editor */ + private ITextEditor fTextEditor; + + /** The part listener */ + private IPartListener fPartListener; + + /** The shell listener */ + private ShellListener fActivationListener; + + /** + * The mutex that keeps us from running multiple reconcilers on one editor. + * TODO remove once we have ensured that there is only one reconciler per + * editor. + */ + private Object fMutex; + + /** + * The Java element changed listener. + * + * @since 3.0 + */ + private IElementChangedListener fJavaElementChangedListener; + + /** + * Tells whether the Java model sent out a changed event. + * + * @since 3.0 + */ + private volatile boolean fHasJavaModelChanged = true; + + /** + * The resource change listener. + * + * @since 3.0 + */ + private IResourceChangeListener fResourceChangeListener; + + private boolean fIninitalProcessDone = false; + + /** + * Creates a new reconciler. + */ + public JavaReconciler(ITextEditor editor, + JavaCompositeReconcilingStrategy strategy, boolean isIncremental) { + super(strategy, isIncremental); + fTextEditor = editor; + + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 + // when re-using editors, a new reconciler is set up by the source + // viewer + // and the old one uninstalled. However, the old reconciler may still be + // running. + // To avoid having to reconcilers calling + // CompilationUnitEditor.reconciled, + // we synchronized on a lock object provided by the editor. + // The critical section is really the entire run() method of the + // reconciler + // thread, but synchronizing process() only will keep + // JavaReconcilingStrategy + // from running concurrently on the same editor. + // TODO remove once we have ensured that there is only one reconciler + // per editor. + if (editor instanceof PHPUnitEditor) + fMutex = ((PHPUnitEditor) editor).getReconcilerLock(); + else + fMutex = new Object(); // Null Object + } + + /* + * @see org.eclipse.jface.text.reconciler.IReconciler#install(org.eclipse.jface.text.ITextViewer) + */ + public void install(ITextViewer textViewer) { + super.install(textViewer); + + fPartListener = new PartListener(); + IWorkbenchPartSite site = fTextEditor.getSite(); + IWorkbenchWindow window = site.getWorkbenchWindow(); + window.getPartService().addPartListener(fPartListener); + + fActivationListener = new ActivationListener(textViewer.getTextWidget()); + Shell shell = window.getShell(); + shell.addShellListener(fActivationListener); + + fJavaElementChangedListener = new ElementChangedListener(); + JavaCore.addElementChangedListener(fJavaElementChangedListener); + + fResourceChangeListener = new ResourceChangeListener(); + IWorkspace workspace = PHPeclipsePlugin.getWorkspace(); + workspace.addResourceChangeListener(fResourceChangeListener); + } + + /* + * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() + */ + public void uninstall() { + + IWorkbenchPartSite site = fTextEditor.getSite(); + IWorkbenchWindow window = site.getWorkbenchWindow(); + window.getPartService().removePartListener(fPartListener); + fPartListener = null; + + Shell shell = window.getShell(); + if (shell != null && !shell.isDisposed()) + shell.removeShellListener(fActivationListener); + fActivationListener = null; + + JavaCore.removeElementChangedListener(fJavaElementChangedListener); + fJavaElementChangedListener = null; + + IWorkspace workspace = PHPeclipsePlugin.getWorkspace(); + workspace.removeResourceChangeListener(fResourceChangeListener); + fResourceChangeListener = null; + + super.uninstall(); + } + + /* + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#forceReconciling() + */ + protected void forceReconciling() { + if (!fIninitalProcessDone) + return; + + super.forceReconciling(); + JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.notifyListeners(false); + } + + /* + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#aboutToReconcile() + * @since 3.0 + */ + protected void aboutToBeReconciled() { + JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.aboutToBeReconciled(); + } + + /* + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerReset() + */ + protected void reconcilerReset() { + super.reconcilerReset(); + JavaCompositeReconcilingStrategy strategy = (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.notifyListeners(true); + } + + /* + * @see org.eclipse.jface.text.reconciler.MonoReconciler#initialProcess() + */ + protected void initialProcess() { + // TODO remove once we have ensured that there is only one reconciler + // per editor. + synchronized (fMutex) { + super.initialProcess(); + } + fIninitalProcessDone = true; + } + + /* + * @see org.eclipse.jface.text.reconciler.MonoReconciler#process(org.eclipse.jface.text.reconciler.DirtyRegion) + */ + protected void process(DirtyRegion dirtyRegion) { + // TODO remove once we have ensured that there is only one reconciler + // per editor. + synchronized (fMutex) { + super.process(dirtyRegion); + } + } + + /** + * Tells whether the Java Model has changed or not. + * + * @return true iff the Java Model has changed + * @since 3.0 + */ + private synchronized boolean hasJavaModelChanged() { + return fHasJavaModelChanged; + } + + /** + * Sets whether the Java Model has changed or not. + * + * @param state + * true iff the java model has changed + * @since 3.0 + */ + private synchronized void setJavaModelChanged(boolean state) { + fHasJavaModelChanged = state; + } +} +// /** +// * A reconciler that is also activated on editor activation. +// */ +// public class JavaReconciler extends MonoReconciler { +// +// /** +// * Internal part listener for activating the reconciler. +// */ +// class PartListener implements IPartListener { +// +// /* +// * @see IPartListener#partActivated(IWorkbenchPart) +// */ +// public void partActivated(IWorkbenchPart part) { +// if (part == fTextEditor) +// JavaReconciler.this.forceReconciling(); +// } +// +// /* +// * @see IPartListener#partBroughtToTop(IWorkbenchPart) +// */ +// public void partBroughtToTop(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partClosed(IWorkbenchPart) +// */ +// public void partClosed(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partDeactivated(IWorkbenchPart) +// */ +// public void partDeactivated(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partOpened(IWorkbenchPart) +// */ +// public void partOpened(IWorkbenchPart part) { +// } +// }; +// +// +// /** The reconciler's editor */ +// private ITextEditor fTextEditor; +// /** The part listener */ +// private IPartListener fPartListener; +// +// +// /** +// * Creates a new reconciler. +// */ +// public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, +// boolean isIncremental) { +// super(strategy, isIncremental); +// fTextEditor= editor; +// } +// +// /* +// * @see IReconciler#install(ITextViewer) +// */ +// public void install(ITextViewer textViewer) { +// super.install(textViewer); +// +// fPartListener= new PartListener(); +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().addPartListener(fPartListener); +// } +// +// /* +// * @see IReconciler#uninstall() +// */ +// public void uninstall() { +// +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().removePartListener(fPartListener); +// fPartListener= null; +// +// super.uninstall(); +// } +// +// /* +// * @see AbstractReconciler#forceReconciling() +// */ +// protected void forceReconciling() { +// super.forceReconciling(); +// IReconcilingStrategy strategy= +// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(false); +// } +// } +// +// /* +// * @see AbstractReconciler#reconcilerReset() +// */ +// protected void reconcilerReset() { +// super.reconcilerReset(); +// IReconcilingStrategy strategy= +// getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(true); +// } +// } +// } diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaWordFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordFinder.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaWordFinder.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordFinder.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaWordIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/LineBreakingReader.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPCodeReader.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PHPPairMatcher.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/PreferencesAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SequenceCharacterIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartBackspaceManager.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java new file mode 100644 index 0000000..d0b0d8d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SmartSemicolonAutoEditStrategy.java @@ -0,0 +1,1300 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text; + +import java.util.Arrays; + +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +//incastrix +//import net.sourceforge.phpdt.internal.corext.Assert; +import org.eclipse.core.runtime.Assert; +import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager.UndoSpec; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IAutoEditStrategy; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.text.edits.DeleteEdit; +import org.eclipse.text.edits.MalformedTreeException; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.ITextEditorExtension2; +import org.eclipse.ui.texteditor.ITextEditorExtension3; + +/** + * Modifies DocumentCommands inserting semicolons and opening + * braces to place them smartly, i.e. moving them to the end of a line if that + * is what the user expects. + * + *

+ * In practice, semicolons and braces (and the caret) are moved to the end of + * the line if they are typed anywhere except for semicolons in a + * for statements definition. If the line contains a semicolon or + * brace after the current caret position, the cursor is moved after it. + *

+ * + * @see org.eclipse.jface.text.DocumentCommand + * @since 3.0 + */ +public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy { + + /** String representation of a semicolon. */ + private static final String SEMICOLON = ";"; //$NON-NLS-1$ + + /** Char representation of a semicolon. */ + private static final char SEMICHAR = ';'; + + /** String represenattion of a opening brace. */ + private static final String BRACE = "{"; //$NON-NLS-1$ + + /** Char representation of a opening brace */ + private static final char BRACECHAR = '{'; + + private char fCharacter; + + private String fPartitioning; + + /** + * Creates a new SmartSemicolonAutoEditStrategy. + * + * @param partitioning + * the document partitioning + */ + public SmartSemicolonAutoEditStrategy(String partitioning) { + fPartitioning = partitioning; + } + + /* + * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.DocumentCommand) + */ + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + // 0: early pruning + // also customize if doit is false (so it works in code + // completion situations) + // if (!command.doit) + // return; + + if (command.text == null) + return; + + if (command.text.equals(SEMICOLON)) + fCharacter = SEMICHAR; + else if (command.text.equals(BRACE)) + fCharacter = BRACECHAR; + else + return; + + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + if (fCharacter == SEMICHAR + && !store + .getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON)) + return; + if (fCharacter == BRACECHAR + && !store + .getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE)) + return; + + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page == null) + return; + IEditorPart part = page.getActiveEditor(); + if (!(part instanceof PHPUnitEditor)) + return; + PHPUnitEditor editor = (PHPUnitEditor) part; + if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT + || !editor.isEditable()) + return; + ITextEditorExtension2 extension = (ITextEditorExtension2) editor + .getAdapter(ITextEditorExtension2.class); + if (extension != null && !extension.validateEditorInputState()) + return; + if (isMultilineSelection(document, command)) + return; + + // 1: find concerned line / position in java code, location in statement + int pos = command.offset; + ITextSelection line; + try { + IRegion l = document.getLineInformationOfOffset(pos); + line = new TextSelection(document, l.getOffset(), l.getLength()); + } catch (BadLocationException e) { + return; + } + + // 2: choose action based on findings (is for-Statement?) + // for now: compute the best position to insert the new character + int positionInLine = computeCharacterPosition(document, line, pos + - line.getOffset(), fCharacter, fPartitioning); + int position = positionInLine + line.getOffset(); + + // never position before the current position! + if (position < pos) + return; + + // never double already existing content + if (alreadyPresent(document, fCharacter, position)) + return; + + // don't do special processing if what we do is actually the normal + // behaviour + String insertion = adjustSpacing(document, position, fCharacter); + if (command.offset == position && insertion.equals(command.text)) + return; + + try { + + final SmartBackspaceManager manager = (SmartBackspaceManager) editor + .getAdapter(SmartBackspaceManager.class); + if (manager != null + && PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_SMART_BACKSPACE)) { + TextEdit e1 = new ReplaceEdit(command.offset, command.text + .length(), document.get(command.offset, command.length)); + UndoSpec s1 = new UndoSpec(command.offset + + command.text.length(), new Region(command.offset, 0), + new TextEdit[] { e1 }, 0, null); + + DeleteEdit smart = new DeleteEdit(position, insertion.length()); + ReplaceEdit raw = new ReplaceEdit(command.offset, + command.length, command.text); + UndoSpec s2 = new UndoSpec(position + insertion.length(), + new Region(command.offset + command.text.length(), 0), + new TextEdit[] { smart, raw }, 2, s1); + manager.register(s2); + } + + // 3: modify command + command.offset = position; + command.length = 0; + command.caretOffset = position; + command.text = insertion; + command.doit = true; + command.owner = null; + } catch (MalformedTreeException e) { + PHPeclipsePlugin.log(e); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + + } + + /** + * Returns true if the document command is applied on a multi + * line selection, false otherwise. + * + * @param document + * the document + * @param command + * the command + * @return true if command is a multiline + * command + */ + private boolean isMultilineSelection(IDocument document, + DocumentCommand command) { + try { + return document.getNumberOfLines(command.offset, command.length) > 1; + } catch (BadLocationException e) { + // ignore + return false; + } + } + + /** + * Adds a space before a brace if it is inserted after a parenthesis, equal + * sign, or one of the keywords try, else, do. + * + * @param document + * the document we are working on + * @param position + * the insert position of character + * @param character + * the character to be inserted + * @return a String consisting of character + * plus any additional spacing + */ + private String adjustSpacing(IDocument doc, int position, char character) { + if (character == BRACECHAR) { + if (position > 0 && position <= doc.getLength()) { + int pos = position - 1; + if (looksLike(doc, pos, ")") //$NON-NLS-1$ + || looksLike(doc, pos, "=") //$NON-NLS-1$ + || looksLike(doc, pos, "]") //$NON-NLS-1$ + || looksLike(doc, pos, "try") //$NON-NLS-1$ + || looksLike(doc, pos, "else") //$NON-NLS-1$ + || looksLike(doc, pos, "synchronized") //$NON-NLS-1$ + || looksLike(doc, pos, "static") //$NON-NLS-1$ + || looksLike(doc, pos, "finally") //$NON-NLS-1$ + || looksLike(doc, pos, "do")) //$NON-NLS-1$ + return new String(new char[] { ' ', character }); + } + } + + return new String(new char[] { character }); + } + + /** + * Checks whether a character to be inserted is already present at the + * insert location (perhaps separated by some whitespace from + * position. + * + * @param document + * the document we are working on + * @param position + * the insert position of ch + * @param character + * the character to be inserted + * @return true if ch is already present at + * location, false otherwise + */ + private boolean alreadyPresent(IDocument document, char ch, int position) { + int pos = firstNonWhitespaceForward(document, position, fPartitioning, + document.getLength()); + try { + if (pos != -1 && document.getChar(pos) == ch) + return true; + } catch (BadLocationException e) { + } + + return false; + } + + /** + * Computes the next insert position of the given character in the current + * line. + * + * @param document + * the document we are working on + * @param line + * the line where the change is being made + * @param offset + * the position of the caret in the line when + * character was typed + * @param character + * the character to look for + * @param partitioning + * the document partitioning + * @return the position where character should be inserted / + * replaced + */ + protected static int computeCharacterPosition(IDocument document, + ITextSelection line, int offset, char character, String partitioning) { + String text = line.getText(); + if (text == null) + return 0; + + int insertPos; + if (character == BRACECHAR) { + + insertPos = computeArrayInitializationPos(document, line, offset, + partitioning); + + if (insertPos == -1) { + insertPos = computeAfterTryDoElse(document, line, offset); + } + + if (insertPos == -1) { + insertPos = computeAfterParenthesis(document, line, offset, + partitioning); + } + + } else if (character == SEMICHAR) { + + if (isForStatement(text, offset)) { + insertPos = -1; // don't do anything in for statements, as semis + // are vital part of these + } else { + int nextPartitionPos = nextPartitionOrLineEnd(document, line, + offset, partitioning); + insertPos = startOfWhitespaceBeforeOffset(text, + nextPartitionPos); + // if there is a semi present, return its location as + // alreadyPresent() will take it out this way. + if (insertPos > 0 && text.charAt(insertPos - 1) == character) + insertPos = insertPos - 1; + } + + } else { + Assert.isTrue(false); + return -1; + } + + return insertPos; + } + + /** + * Computes an insert position for an opening brace if offset + * maps to a position in document that looks like being the + * RHS of an assignment or like an array definition. + * + * @param document + * the document being modified + * @param line + * the current line under investigation + * @param offset + * the offset of the caret position, relative to the line start. + * @param partitioning + * the document partitioning + * @return an insert position relative to the line start if + * line looks like being an array initialization at + * offset, -1 otherwise + */ + private static int computeArrayInitializationPos(IDocument document, + ITextSelection line, int offset, String partitioning) { + // search backward while WS, find = (not != <= >= ==) in default + // partition + int pos = offset + line.getOffset(); + + if (pos == 0) + return -1; + + int p = firstNonWhitespaceBackward(document, pos - 1, partitioning, -1); + + if (p == -1) + return -1; + + try { + + char ch = document.getChar(p); + if (ch != '=' && ch != ']') + return -1; + + if (p == 0) + return offset; + + p = firstNonWhitespaceBackward(document, p - 1, partitioning, -1); + if (p == -1) + return -1; + + ch = document.getChar(p); + if (Scanner.isPHPIdentifierPart(ch) || ch == ']' || ch == '[') + return offset; + + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Computes an insert position for an opening brace if offset + * maps to a position in document involving a keyword taking + * a block after it. These are: try, do, + * synchronized, static, + * finally, or else. + * + * @param document + * the document being modified + * @param line + * the current line under investigation + * @param offset + * the offset of the caret position, relative to the line start. + * @return an insert position relative to the line start if + * line contains one of the above keywords at or + * before offset, -1 otherwise + */ + private static int computeAfterTryDoElse(IDocument doc, + ITextSelection line, int offset) { + // search backward while WS, find 'try', 'do', 'else' in default + // partition + int p = offset + line.getOffset(); + p = firstWhitespaceToRight(doc, p); + if (p == -1) + return -1; + p--; + + if (looksLike(doc, p, "try") //$NON-NLS-1$ + || looksLike(doc, p, "do") //$NON-NLS-1$ + || looksLike(doc, p, "synchronized") //$NON-NLS-1$ + || looksLike(doc, p, "static") //$NON-NLS-1$ + || looksLike(doc, p, "finally") //$NON-NLS-1$ + || looksLike(doc, p, "else")) //$NON-NLS-1$ + return p + 1 - line.getOffset(); + + return -1; + } + + /** + * Computes an insert position for an opening brace if offset + * maps to a position in document with a expression in + * parenthesis that will take a block after the closing parenthesis. + * + * @param document + * the document being modified + * @param line + * the current line under investigation + * @param offset + * the offset of the caret position, relative to the line start. + * @param partitioning + * the document partitioning + * @return an insert position relative to the line start if + * line contains a parenthesized expression that can + * be followed by a block, -1 otherwise + */ + private static int computeAfterParenthesis(IDocument document, + ITextSelection line, int offset, String partitioning) { + // find the opening parenthesis for every closing parenthesis on the + // current line after offset + // return the position behind the closing parenthesis if it looks like a + // method declaration + // or an expression for an if, while, for, catch statement + int pos = offset + line.getOffset(); + int length = line.getOffset() + line.getLength(); + int scanTo = scanForward(document, pos, partitioning, length, '}'); + if (scanTo == -1) + scanTo = length; + + int closingParen = findClosingParenToLeft(document, pos, partitioning) - 1; + + while (true) { + int startScan = closingParen + 1; + closingParen = scanForward(document, startScan, partitioning, + scanTo, ')'); + if (closingParen == -1) + break; + + int openingParen = findOpeningParenMatch(document, closingParen, + partitioning); + + // no way an expression at the beginning of the document can mean + // anything + if (openingParen < 1) + break; + + // only select insert positions for parenthesis currently embracing + // the caret + if (openingParen > pos) + continue; + + if (looksLikeAnonymousClassDef(document, openingParen - 1, + partitioning)) + return closingParen + 1 - line.getOffset(); + + if (looksLikeIfWhileForCatch(document, openingParen - 1, + partitioning)) + return closingParen + 1 - line.getOffset(); + + if (looksLikeMethodDecl(document, openingParen - 1, partitioning)) + return closingParen + 1 - line.getOffset(); + + } + + return -1; + } + + /** + * Finds a closing parenthesis to the left of position in + * document, where that parenthesis is only separated by whitespace from + * position. If no such parenthesis can be found, + * position is returned. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the position of a closing parenthesis left to + * position separated only by whitespace, or + * position if no parenthesis can be found + */ + private static int findClosingParenToLeft(IDocument document, int position, + String partitioning) { + final char CLOSING_PAREN = ')'; + try { + if (position < 1) + return position; + + int nonWS = firstNonWhitespaceBackward(document, position - 1, + partitioning, -1); + if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN) + return nonWS; + } catch (BadLocationException e1) { + } + return position; + } + + /** + * Finds the first whitespace character position to the right of (and + * including) position. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @return the position of a whitespace character greater or equal than + * position separated only by whitespace, or -1 if + * none found + */ + private static int firstWhitespaceToRight(IDocument document, int position) { + int length = document.getLength(); + Assert.isTrue(position >= 0); + Assert.isTrue(position <= length); + + try { + while (position < length) { + char ch = document.getChar(position); + if (Character.isWhitespace(ch)) + return position; + position++; + } + return position; + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Finds the highest position in document such that the + * position is <= position and > bound + * and Character.isWhitespace(document.getChar(pos)) + * evaluates to false and the position is in the default + * partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with bound > position + * @return the highest position of one element in chars in [position, + * scanTo) that resides in a Java partition, or + * -1 if none can be found + */ + private static int firstNonWhitespaceBackward(IDocument document, + int position, String partitioning, int bound) { + Assert.isTrue(position < document.getLength()); + Assert.isTrue(bound >= -1); + + try { + while (position > bound) { + char ch = document.getChar(position); + if (!Character.isWhitespace(ch) + && isDefaultPartition(document, position, partitioning)) + return position; + position--; + } + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Finds the smallest position in document such that the + * position is >= position and < bound + * and Character.isWhitespace(document.getChar(pos)) + * evaluates to false and the position is in the default + * partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with bound > position + * @return the smallest position of one element in chars in [position, + * scanTo) that resides in a Java partition, or + * -1 if none can be found + */ + private static int firstNonWhitespaceForward(IDocument document, + int position, String partitioning, int bound) { + Assert.isTrue(position >= 0); + Assert.isTrue(bound <= document.getLength()); + + try { + while (position < bound) { + char ch = document.getChar(position); + if (!Character.isWhitespace(ch) + && isDefaultPartition(document, position, partitioning)) + return position; + position++; + } + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Finds the highest position in document such that the + * position is <= position and > bound + * and document.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the highest position of one element in chars in (bound, + * position] that resides in a Java partition, or + * -1 if none can be found + */ + private static int scanBackward(IDocument document, int position, + String partitioning, int bound, char[] chars) { + Assert.isTrue(bound >= -1); + Assert.isTrue(position < document.getLength()); + + Arrays.sort(chars); + + try { + while (position > bound) { + + if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 + && isDefaultPartition(document, position, partitioning)) + return position; + + position--; + } + } catch (BadLocationException e) { + } + return -1; + } + + // /** + // * Finds the highest position in document such that the + // position is <= position + // * and > bound and document.getChar(position) == + // ch evaluates to true + // * and the position is in the default partition. + // * + // * @param document the document being modified + // * @param position the first character position in document + // to be considered + // * @param bound the first position in document to not + // consider any more, with scanTo > position + // * @param chars an array of char to search for + // * @return the highest position of one element in chars in + // [position, scanTo) that resides in a Java + // partition, or -1 if none can be found + // */ + // private static int scanBackward(IDocument document, int position, int + // bound, char ch) { + // return scanBackward(document, position, bound, new char[] {ch}); + // } + // + /** + * Finds the lowest position in document such that the + * position is >= position and < bound + * and document.getChar(position) == ch evaluates to + * true for at least one ch in chars and the + * position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the lowest position of one element in chars in [position, + * bound) that resides in a Java partition, or + * -1 if none can be found + */ + private static int scanForward(IDocument document, int position, + String partitioning, int bound, char[] chars) { + Assert.isTrue(position >= 0); + Assert.isTrue(bound <= document.getLength()); + + Arrays.sort(chars); + + try { + while (position < bound) { + + if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 + && isDefaultPartition(document, position, partitioning)) + return position; + + position++; + } + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Finds the lowest position in document such that the + * position is >= position and < bound + * and document.getChar(position) == ch evaluates to + * true and the position is in the default partition. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @param bound + * the first position in document to not consider + * any more, with scanTo > + * position + * @param chars + * an array of char to search for + * @return the lowest position of one element in chars in [position, + * bound) that resides in a Java partition, or + * -1 if none can be found + */ + private static int scanForward(IDocument document, int position, + String partitioning, int bound, char ch) { + return scanForward(document, position, partitioning, bound, + new char[] { ch }); + } + + /** + * Checks whether the content of document in the range (offset, + * length) contains the new keyword. + * + * @param document + * the document being modified + * @param offset + * the first character position in document to be + * considered + * @param length + * the length of the character range to be considered + * @param partitioning + * the document partitioning + * @return true if the specified character range contains a + * new keyword, false otherwise. + */ + private static boolean isNewMatch(IDocument document, int offset, + int length, String partitioning) { + Assert.isTrue(length >= 0); + Assert.isTrue(offset >= 0); + Assert.isTrue(offset + length < document.getLength() + 1); + + try { + String text = document.get(offset, length); + int pos = text.indexOf("new"); //$NON-NLS-1$ + + while (pos != -1 + && !isDefaultPartition(document, pos + offset, partitioning)) + pos = text.indexOf("new", pos + 2); //$NON-NLS-1$ + + if (pos < 0) + return false; + + if (pos != 0 && Scanner.isPHPIdentifierPart(text.charAt(pos - 1))) + return false; + + if (pos + 3 < length + && Scanner.isPHPIdentifierPart(text.charAt(pos + 3))) + return false; + + return true; + + } catch (BadLocationException e) { + } + return false; + } + + /** + * Checks whether the content of document at + * position looks like an anonymous class definition. + * position must be to the left of the opening parenthesis of + * the definition's parameter list. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return true if the content of document + * looks like an anonymous class definition, false + * otherwise + */ + private static boolean looksLikeAnonymousClassDef(IDocument document, + int position, String partitioning) { + int previousCommaOrParen = scanBackward(document, position - 1, + partitioning, -1, new char[] { ',', '(' }); + if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 + // for + // borders, + // 3 + // for + // "new" + return false; + + if (isNewMatch(document, previousCommaOrParen + 1, position + - previousCommaOrParen - 2, partitioning)) + return true; + + return false; + } + + /** + * Checks whether position resides in a default (Java) + * partition of document. + * + * @param document + * the document being modified + * @param position + * the position to be checked + * @param partitioning + * the document partitioning + * @return true if position is in the default + * partition of document, false + * otherwise + */ + private static boolean isDefaultPartition(IDocument document, int position, + String partitioning) { + Assert.isTrue(position >= 0); + Assert.isTrue(position <= document.getLength()); + + try { + // don't use getPartition2 since we're interested in the scanned + // character's partition + ITypedRegion region = TextUtilities.getPartition(document, + partitioning, position, false); + return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE); + + } catch (BadLocationException e) { + } + + return false; + } + + /** + * Finds the position of the parenthesis matching the closing parenthesis at + * position. + * + * @param document + * the document being modified + * @param position + * the position in document of a closing + * parenthesis + * @param partitioning + * the document partitioning + * @return the position in document of the matching + * parenthesis, or -1 if none can be found + */ + private static int findOpeningParenMatch(IDocument document, int position, + String partitioning) { + final char CLOSING_PAREN = ')'; + final char OPENING_PAREN = '('; + + Assert.isTrue(position < document.getLength()); + Assert.isTrue(position >= 0); + Assert.isTrue(isDefaultPartition(document, position, partitioning)); + + try { + + Assert.isTrue(document.getChar(position) == CLOSING_PAREN); + + int depth = 1; + while (true) { + position = scanBackward(document, position - 1, partitioning, + -1, new char[] { CLOSING_PAREN, OPENING_PAREN }); + if (position == -1) + return -1; + + if (document.getChar(position) == CLOSING_PAREN) + depth++; + else + depth--; + + if (depth == 0) + return position; + } + + } catch (BadLocationException e) { + return -1; + } + } + + /** + * Checks whether, to the left of position and separated only + * by whitespace, document contains a keyword taking a + * parameter list and a block after it. These are: if, + * while, catch, for, + * synchronized, switch. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return true if document contains any of + * the above keywords to the left of position, + * false otherwise + */ + private static boolean looksLikeIfWhileForCatch(IDocument document, + int position, String partitioning) { + position = firstNonWhitespaceBackward(document, position, partitioning, + -1); + if (position == -1) + return false; + + return looksLike(document, position, "if") //$NON-NLS-1$ + || looksLike(document, position, "while") //$NON-NLS-1$ + || looksLike(document, position, "catch") //$NON-NLS-1$ + || looksLike(document, position, "synchronized") //$NON-NLS-1$ + || looksLike(document, position, "switch") //$NON-NLS-1$ + || looksLike(document, position, "for"); //$NON-NLS-1$ + } + + /** + * Checks whether code>document contains the String like + * such that its last character is at position. If like + * starts with a identifier part (as determined by + * {@link Scanner#isPHPIdentifierPart(char)}), it is also made sure that + * like is preceded by some non-identifier character or + * stands at the document start. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param like + * the String to look for. + * @return true if document contains like + * such that it ends at position, false + * otherwise + */ + private static boolean looksLike(IDocument document, int position, + String like) { + int length = like.length(); + if (position < length - 1) + return false; + + try { + if (!like.equals(document.get(position - length + 1, length))) + return false; + + if (position >= length + && Scanner.isPHPIdentifierPart(like.charAt(0)) + && Scanner.isPHPIdentifierPart(document.getChar(position + - length))) + return false; + + } catch (BadLocationException e) { + return false; + } + + return true; + } + + /** + * Checks whether the content of document at + * position looks like a method declaration header (i.e. only + * the return type and method name). position must be just + * left of the opening parenthesis of the parameter list. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return true if the content of document + * looks like a method definition, false otherwise + */ + private static boolean looksLikeMethodDecl(IDocument document, + int position, String partitioning) { + + // method name + position = eatIdentToLeft(document, position, partitioning); + if (position < 1) + return false; + + position = eatBrackets(document, position - 1, partitioning); + if (position < 1) + return false; + + position = eatIdentToLeft(document, position - 1, partitioning); + + return position != -1; + } + + /** + * From position to the left, eats any whitespace and then a + * pair of brackets as used to declare an array return type like + * + *
+	 * String [ ]
+	 * 
. The return value is either the position of the opening bracket + * or position if no pair of brackets can be parsed. + * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the smallest character position of bracket pair or + * position + */ + private static int eatBrackets(IDocument document, int position, + String partitioning) { + // accept array return type + int pos = firstNonWhitespaceBackward(document, position, partitioning, + -1); + try { + if (pos > 1 && document.getChar(pos) == ']') { + pos = firstNonWhitespaceBackward(document, pos - 1, + partitioning, -1); + if (pos > 0 && document.getChar(pos) == '[') + return pos; + } + } catch (BadLocationException e) { + // won't happen + } + return position; + } + + /** + * From position to the left, eats any whitespace and the + * first identifier, returning the position of the first identifier + * character (in normal read order). + *

+ * When called on a document with content " some string " and + * positionition 13, the return value will be 6 (the first letter in + * string). + *

+ * + * @param document + * the document being modified + * @param position + * the first character position in document to be + * considered + * @param partitioning + * the document partitioning + * @return the smallest character position of an identifier or -1 if none + * can be found; always <= position + */ + private static int eatIdentToLeft(IDocument document, int position, + String partitioning) { + if (position < 0) + return -1; + Assert.isTrue(position < document.getLength()); + + int p = firstNonWhitespaceBackward(document, position, partitioning, -1); + if (p == -1) + return -1; + + try { + while (p >= 0) { + + char ch = document.getChar(p); + if (Scanner.isPHPIdentifierPart(ch)) { + p--; + continue; + } + + // length must be > 0 + if (Character.isWhitespace(ch) && p != position) + return p + 1; + else + return -1; + + } + + // start of document reached + return 0; + + } catch (BadLocationException e) { + } + return -1; + } + + /** + * Returns a position in the first java partition after the last non-empty + * and non-comment partition. There is no non-whitespace from the returned + * position to the end of the partition it is contained in. + * + * @param document + * the document being modified + * @param line + * the line under investigation + * @param offset + * the caret offset into line + * @param partitioning + * the document partitioning + * @return the position of the next Java partition, or the end of + * line + */ + private static int nextPartitionOrLineEnd(IDocument document, + ITextSelection line, int offset, String partitioning) { + // run relative to document + final int docOffset = offset + line.getOffset(); + final int eol = line.getOffset() + line.getLength(); + int nextPartitionPos = eol; // init with line end + int validPosition = docOffset; + + try { + ITypedRegion partition = TextUtilities.getPartition(document, + partitioning, nextPartitionPos, true); + validPosition = getValidPositionForPartition(document, partition, + eol); + while (validPosition == -1) { + nextPartitionPos = partition.getOffset() - 1; + if (nextPartitionPos < docOffset) { + validPosition = docOffset; + break; + } + partition = TextUtilities.getPartition(document, partitioning, + nextPartitionPos, false); + validPosition = getValidPositionForPartition(document, + partition, eol); + } + } catch (BadLocationException e) { + } + + validPosition = Math.max(validPosition, docOffset); + // make relative to line + validPosition -= line.getOffset(); + return validPosition; + } + + /** + * Returns a valid insert location (except for whitespace) in + * partition or -1 if there is no valid insert location. An + * valid insert location is right after any java string or character + * partition, or at the end of a java default partition, but never behind + * maxOffset. Comment partitions or empty java partitions do + * never yield valid insert positions. + * + * @param doc + * the document being modified + * @param partition + * the current partition + * @param maxOffset + * the maximum offset to consider + * @return a valid insert location in partition, or -1 if + * there is no valid insert location + */ + private static int getValidPositionForPartition(IDocument doc, + ITypedRegion partition, int maxOffset) { + final int INVALID = -1; + + if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(partition.getType())) + return INVALID; + if (IPHPPartitions.PHP_MULTILINE_COMMENT.equals(partition.getType())) + return INVALID; + if (IPHPPartitions.PHP_SINGLELINE_COMMENT.equals(partition.getType())) + return INVALID; + + int endOffset = Math.min(maxOffset, partition.getOffset() + + partition.getLength()); + + // if (IPHPPartitions.JAVA_CHARACTER.equals(partition.getType())) + // return endOffset; + if (IPHPPartitions.PHP_STRING_DQ.equals(partition.getType())) + return endOffset; + if (IPHPPartitions.PHP_STRING_SQ.equals(partition.getType())) + return endOffset; + if (IPHPPartitions.PHP_STRING_HEREDOC.equals(partition.getType())) + return endOffset; + if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) { + try { + if (doc.get(partition.getOffset(), + endOffset - partition.getOffset()).trim().length() == 0) + return INVALID; + else + return endOffset; + } catch (BadLocationException e) { + return INVALID; + } + } + // default: we don't know anything about the partition - assume valid + return endOffset; + } + + /** + * Determines whether the current line contains a for statement. Algorithm: + * any "for" word in the line is a positive, "for" contained in a string + * literal will produce a false positive. + * + * @param line + * the line where the change is being made + * @param offset + * the position of the caret + * @return true if line contains + * for, false otherwise + */ + private static boolean isForStatement(String line, int offset) { + /* searching for (^|\s)for(\s|$) */ + int forPos = line.indexOf("for"); //$NON-NLS-1$ + if (forPos != -1) { + if ((forPos == 0 || !Scanner.isPHPIdentifierPart(line + .charAt(forPos - 1))) + && (line.length() == forPos + 3 || !Scanner + .isPHPIdentifierPart(line.charAt(forPos + 3)))) + return true; + } + return false; + } + + /** + * Returns the position in text after which there comes only + * whitespace, up to offset. + * + * @param text + * the text being searched + * @param offset + * the maximum offset to search for + * @return the smallest value v such that + * text.substring(v, offset).trim() == 0 + */ + private static int startOfWhitespaceBeforeOffset(String text, int offset) { + int i = Math.min(offset, text.length()); + for (; i >= 1; i--) { + if (!Character.isWhitespace(text.charAt(i - 1))) + break; + } + return i; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/SubstitutionTextReader.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/Symbols.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRun.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/TypingRunDetector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/comment/CommentFormattingContext.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java new file mode 100644 index 0000000..5e7e1b1 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java @@ -0,0 +1,184 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.folding; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore; +import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore.OverlayKey; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.swt.SWT; +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; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; + +/** + * Java default folding preferences. + * + * @since 3.0 + */ +public class DefaultJavaFoldingPreferenceBlock implements + IJavaFoldingPreferenceBlock { + + private IPreferenceStore fStore; + + private OverlayPreferenceStore fOverlayStore; + + private OverlayKey[] fKeys; + + private Map fCheckBoxes = new HashMap(); + + private SelectionListener fCheckBoxListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + + public void widgetSelected(SelectionEvent e) { + Button button = (Button) e.widget; + fOverlayStore.setValue((String) fCheckBoxes.get(button), button + .getSelection()); + } + }; + + public DefaultJavaFoldingPreferenceBlock() { + fStore = PHPeclipsePlugin.getDefault().getPreferenceStore(); + fKeys = createKeys(); + fOverlayStore = new OverlayPreferenceStore(fStore, fKeys); + } + + private OverlayKey[] createKeys() { + ArrayList overlayKeys = new ArrayList(); + + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_JAVADOC)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_HEADERS)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_INNERTYPES)); + overlayKeys.add(new OverlayPreferenceStore.OverlayKey( + OverlayPreferenceStore.BOOLEAN, + PreferenceConstants.EDITOR_FOLDING_METHODS)); + // overlayKeys.add(new + // OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, + // PreferenceConstants.EDITOR_FOLDING_IMPORTS)); + + return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys + .size()]); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group) + */ + public Control createControl(Composite composite) { + fOverlayStore.load(); + fOverlayStore.start(); + + Composite inner = new Composite(composite, SWT.NONE); + GridLayout layout = new GridLayout(1, true); + layout.verticalSpacing = 3; + layout.marginWidth = 0; + inner.setLayout(layout); + + Label label = new Label(inner, SWT.LEFT); + label.setText(FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.title")); //$NON-NLS-1$ + + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.comments"), PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0); //$NON-NLS-1$ + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.headers"), PreferenceConstants.EDITOR_FOLDING_HEADERS, 0);//$NON-NLS-1$ + addCheckBox(inner, FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.innerTypes"), + PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0); //$NON-NLS-1$ + addCheckBox( + inner, + FoldingMessages + .getString("DefaultJavaFoldingPreferenceBlock.methods"), PreferenceConstants.EDITOR_FOLDING_METHODS, 0); //$NON-NLS-1$ + // addCheckBox(inner, + // FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.imports"), + // PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0); //$NON-NLS-1$ + + return inner; + } + + private Button addCheckBox(Composite parent, String label, String key, + int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 1; + gd.grabExcessVerticalSpace = false; + checkBox.setLayoutData(gd); + checkBox.addSelectionListener(fCheckBoxListener); + + fCheckBoxes.put(checkBox, key); + + return checkBox; + } + + private void initializeFields() { + Iterator it = fCheckBoxes.keySet().iterator(); + while (it.hasNext()) { + Button b = (Button) it.next(); + String key = (String) fCheckBoxes.get(b); + b.setSelection(fOverlayStore.getBoolean(key)); + } + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performOk() + */ + public void performOk() { + fOverlayStore.propagate(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#initialize() + */ + public void initialize() { + initializeFields(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performDefaults() + */ + public void performDefaults() { + fOverlayStore.loadDefaults(); + initializeFields(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#dispose() + */ + public void dispose() { + fOverlayStore.stop(); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java new file mode 100644 index 0000000..074e4e9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/DefaultJavaFoldingStructureProvider.java @@ -0,0 +1,1064 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.folding; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import net.sourceforge.phpdt.core.ElementChangedEvent; +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IElementChangedListener; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaElementDelta; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.IParent; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.core.compiler.IScanner; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; + +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.projection.IProjectionListener; +import org.eclipse.jface.text.source.projection.IProjectionPosition; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; +import org.eclipse.jface.text.source.projection.ProjectionViewer; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Updates the projection model of a class file or compilation unit. + * + * @since 3.0 + */ +public class DefaultJavaFoldingStructureProvider implements + IProjectionListener, IJavaFoldingStructureProvider { + + private static class JavaProjectionAnnotation extends ProjectionAnnotation { + + private IJavaElement fJavaElement; + + private boolean fIsComment; + + public JavaProjectionAnnotation(IJavaElement element, + boolean isCollapsed, boolean isComment) { + super(isCollapsed); + fJavaElement = element; + fIsComment = isComment; + } + + public IJavaElement getElement() { + return fJavaElement; + } + + public void setElement(IJavaElement element) { + fJavaElement = element; + } + + public boolean isComment() { + return fIsComment; + } + + public void setIsComment(boolean isComment) { + fIsComment = isComment; + } + + /* + * @see java.lang.Object#toString() + */ + public String toString() { + return "JavaProjectionAnnotation:\n" + //$NON-NLS-1$ + "\telement: \t" + fJavaElement.toString() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\tcollapsed: \t" + isCollapsed() + "\n" + //$NON-NLS-1$ //$NON-NLS-2$ + "\tcomment: \t" + fIsComment + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private static final class Tuple { + JavaProjectionAnnotation annotation; + + Position position; + + Tuple(JavaProjectionAnnotation annotation, Position position) { + this.annotation = annotation; + this.position = position; + } + } + + private class ElementChangedListener implements IElementChangedListener { + + /* + * @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent) + */ + public void elementChanged(ElementChangedEvent e) { + IJavaElementDelta delta = findElement(fInput, e.getDelta()); + if (delta != null) + processDelta(delta); + } + + private IJavaElementDelta findElement(IJavaElement target, + IJavaElementDelta delta) { + + if (delta == null || target == null) + return null; + + IJavaElement element = delta.getElement(); + + if (element.getElementType() > IJavaElement.CLASS_FILE) + return null; + + if (target.equals(element)) + return delta; + + IJavaElementDelta[] children = delta.getAffectedChildren(); + + for (int i = 0; i < children.length; i++) { + IJavaElementDelta d = findElement(target, children[i]); + if (d != null) + return d; + } + + return null; + } + } + + /** + * Projection position that will return two foldable regions: one folding + * away the region from after the '/**' to the beginning of the content, the + * other from after the first content line until after the comment. + * + * @since 3.1 + */ + private static final class CommentPosition extends Position implements + IProjectionPosition { + CommentPosition(int offset, int length) { + super(offset, length); + } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) + */ + public IRegion[] computeProjectionRegions(IDocument document) + throws BadLocationException { + DocumentCharacterIterator sequence = new DocumentCharacterIterator( + document, offset, offset + length); + int prefixEnd = 0; + int contentStart = findFirstContent(sequence, prefixEnd); + + int firstLine = document.getLineOfOffset(offset + prefixEnd); + int captionLine = document.getLineOfOffset(offset + contentStart); + int lastLine = document.getLineOfOffset(offset + length); + + Assert.isTrue(firstLine <= captionLine, + "first folded line is greater than the caption line"); //$NON-NLS-1$ + Assert.isTrue(captionLine <= lastLine, + "caption line is greater than the last folded line"); //$NON-NLS-1$ + + IRegion preRegion; + if (firstLine < captionLine) { + // preRegion= new Region(offset + prefixEnd, contentStart - + // prefixEnd); + int preOffset = document.getLineOffset(firstLine); + IRegion preEndLineInfo = document + .getLineInformation(captionLine); + int preEnd = preEndLineInfo.getOffset(); + preRegion = new Region(preOffset, preEnd - preOffset); + } else { + preRegion = null; + } + + if (captionLine < lastLine) { + int postOffset = document.getLineOffset(captionLine + 1); + IRegion postRegion = new Region(postOffset, offset + length + - postOffset); + + if (preRegion == null) + return new IRegion[] { postRegion }; + + return new IRegion[] { preRegion, postRegion }; + } + + if (preRegion != null) + return new IRegion[] { preRegion }; + + return null; + } + + /** + * Finds the offset of the first identifier part within + * content. Returns 0 if none is found. + * + * @param content + * the content to search + * @return the first index of a unicode identifier part, or zero if none + * can be found + */ + private int findFirstContent(final CharSequence content, int prefixEnd) { + int lenght = content.length(); + for (int i = prefixEnd; i < lenght; i++) { + if (Character.isUnicodeIdentifierPart(content.charAt(i))) + return i; + } + return 0; + } + + // /** + // * Finds the offset of the first identifier part within + // content. + // * Returns 0 if none is found. + // * + // * @param content the content to search + // * @return the first index of a unicode identifier part, or zero if + // none + // can + // * be found + // */ + // private int findPrefixEnd(final CharSequence content) { + // // return the index after the leading '/*' or '/**' + // int len= content.length(); + // int i= 0; + // while (i < len && isWhiteSpace(content.charAt(i))) + // i++; + // if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) + // == + // '*') + // if (len >= i + 3 && content.charAt(i + 2) == '*') + // return i + 3; + // else + // return i + 2; + // else + // return i; + // } + // + // private boolean isWhiteSpace(char c) { + // return c == ' ' || c == '\t'; + // } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) + */ + public int computeCaptionOffset(IDocument document) { + // return 0; + DocumentCharacterIterator sequence = new DocumentCharacterIterator( + document, offset, offset + length); + return findFirstContent(sequence, 0); + } + } + + /** + * Projection position that will return two foldable regions: one folding + * away the lines before the one containing the simple name of the java + * element, one folding away any lines after the caption. + * + * @since 3.1 + */ + private static final class JavaElementPosition extends Position implements + IProjectionPosition { + + private IMember fMember; + + public JavaElementPosition(int offset, int length, IMember member) { + super(offset, length); + Assert.isNotNull(member); + fMember = member; + } + + public void setMember(IMember member) { + Assert.isNotNull(member); + fMember = member; + } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) + */ + public IRegion[] computeProjectionRegions(IDocument document) + throws BadLocationException { + int nameStart = offset; + try { + /* + * The member's name range may not be correct. However, + * reconciling would trigger another element delta which would + * lead to reentrant situations. Therefore, we optimistically + * assume that the name range is correct, but double check the + * received lines below. + */ + ISourceRange nameRange = fMember.getNameRange(); + if (nameRange != null) + nameStart = nameRange.getOffset(); + + } catch (JavaModelException e) { + // ignore and use default + } + + int firstLine = document.getLineOfOffset(offset); + int captionLine = document.getLineOfOffset(nameStart); + int lastLine = document.getLineOfOffset(offset + length); + + /* + * see comment above - adjust the caption line to be inside the + * entire folded region, and rely on later element deltas to correct + * the name range. + */ + if (captionLine < firstLine) + captionLine = firstLine; + if (captionLine > lastLine) + captionLine = lastLine; + + IRegion preRegion; + if (firstLine < captionLine) { + int preOffset = document.getLineOffset(firstLine); + IRegion preEndLineInfo = document + .getLineInformation(captionLine); + int preEnd = preEndLineInfo.getOffset(); + preRegion = new Region(preOffset, preEnd - preOffset); + } else { + preRegion = null; + } + + if (captionLine < lastLine) { + int postOffset = document.getLineOffset(captionLine + 1); + IRegion postRegion = new Region(postOffset, offset + length + - postOffset); + + if (preRegion == null) + return new IRegion[] { postRegion }; + + return new IRegion[] { preRegion, postRegion }; + } + + if (preRegion != null) + return new IRegion[] { preRegion }; + + return null; + } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) + */ + public int computeCaptionOffset(IDocument document) + throws BadLocationException { + int nameStart = offset; + try { + // need a reconcile here? + ISourceRange nameRange = fMember.getNameRange(); + if (nameRange != null) + nameStart = nameRange.getOffset(); + } catch (JavaModelException e) { + // ignore and use default + } + + return nameStart - offset; + } + + } + + private IDocument fCachedDocument; + + private ProjectionAnnotationModel fCachedModel; + + private ITextEditor fEditor; + + private ProjectionViewer fViewer; + + private IJavaElement fInput; + + private IElementChangedListener fElementListener; + + private boolean fAllowCollapsing = false; + + private boolean fCollapseJavadoc = false; + + // private boolean fCollapseImportContainer = true; + + private boolean fCollapseInnerTypes = true; + + private boolean fCollapseMethods = false; + + private boolean fCollapseHeaderComments = true; + + /* caches for header comment extraction. */ + private IType fFirstType; + + private boolean fHasHeaderComment; + + public DefaultJavaFoldingStructureProvider() { + } + + public void install(ITextEditor editor, ProjectionViewer viewer) { + if (editor instanceof PHPEditor) { + fEditor = editor; + fViewer = viewer; + fViewer.addProjectionListener(this); + } + } + + public void uninstall() { + if (isInstalled()) { + projectionDisabled(); + fViewer.removeProjectionListener(this); + fViewer = null; + fEditor = null; + } + } + + protected boolean isInstalled() { + return fEditor != null; + } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled() + */ + public void projectionEnabled() { + // http://home.ott.oti.com/teams/wswb/anon/out/vms/index.html + // projectionEnabled messages are not always paired with + // projectionDisabled + // i.e. multiple enabled messages may be sent out. + // we have to make sure that we disable first when getting an enable + // message. + projectionDisabled(); + + if (fEditor instanceof PHPEditor) { + initialize(); + fElementListener = new ElementChangedListener(); + JavaCore.addElementChangedListener(fElementListener); + } + } + + /* + * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled() + */ + public void projectionDisabled() { + fCachedDocument = null; + if (fElementListener != null) { + JavaCore.removeElementChangedListener(fElementListener); + fElementListener = null; + } + } + + public void initialize() { + + if (!isInstalled()) + return; + + initializePreferences(); + + try { + + IDocumentProvider provider = fEditor.getDocumentProvider(); + fCachedDocument = provider.getDocument(fEditor.getEditorInput()); + fAllowCollapsing = true; + + fFirstType = null; + fHasHeaderComment = false; + + if (fEditor instanceof PHPUnitEditor) { + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + fInput = manager.getWorkingCopy(fEditor.getEditorInput()); + } + // else if (fEditor instanceof ClassFileEditor) { + // IClassFileEditorInput editorInput= (IClassFileEditorInput) + // fEditor.getEditorInput(); + // fInput= editorInput.getClassFile(); + // } + + if (fInput != null) { + ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor + .getAdapter(ProjectionAnnotationModel.class); + if (model != null) { + fCachedModel = model; + if (fInput instanceof ICompilationUnit) { + ICompilationUnit unit = (ICompilationUnit) fInput; + synchronized (unit) { + try { + // unit.reconcile(ICompilationUnit.NO_AST, + // false, null, null); + unit.reconcile(); + } catch (JavaModelException x) { + } + } + } + + Map additions = computeAdditions((IParent) fInput); + /* + * Minimize the events being sent out - as this happens in + * the UI thread merge everything into one call. + */ + List removals = new LinkedList(); + Iterator existing = model.getAnnotationIterator(); + while (existing.hasNext()) + removals.add(existing.next()); + model.replaceAnnotations((Annotation[]) removals + .toArray(new Annotation[removals.size()]), + additions); + } + } + + } finally { + fCachedDocument = null; + fCachedModel = null; + fAllowCollapsing = false; + + fFirstType = null; + fHasHeaderComment = false; + } + } + + private void initializePreferences() { + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + fCollapseInnerTypes = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); + // fCollapseImportContainer = + // store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS); + fCollapseJavadoc = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); + fCollapseMethods = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); + fCollapseHeaderComments = store + .getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); + } + + private Map computeAdditions(IParent parent) { + Map map = new LinkedHashMap(); // use a linked map to maintain ordering + // of + // comments + try { + computeAdditions(parent.getChildren(), map); + } catch (JavaModelException x) { + } + return map; + } + + private void computeAdditions(IJavaElement[] elements, Map map) + throws JavaModelException { + for (int i = 0; i < elements.length; i++) { + IJavaElement element = elements[i]; + + computeAdditions(element, map); + + if (element instanceof IParent) { + IParent parent = (IParent) element; + computeAdditions(parent.getChildren(), map); + } + } + } + + private void computeAdditions(IJavaElement element, Map map) { + + boolean createProjection = false; + + boolean collapse = false; + switch (element.getElementType()) { + + // case IJavaElement.IMPORT_CONTAINER: + // collapse = fAllowCollapsing && fCollapseImportContainer; + // createProjection = true; + // break; + case IJavaElement.TYPE: + collapse = fAllowCollapsing; + if (isInnerType((IType) element)) { + collapse = collapse && fCollapseInnerTypes; + } else { + collapse = false; // don't allow the most outer type to be + // folded, may be changed in future versions + } + createProjection = true; + break; + case IJavaElement.METHOD: + collapse = fAllowCollapsing && fCollapseMethods; + createProjection = true; + break; + } + + if (createProjection) { + IRegion[] regions = computeProjectionRanges(element); + if (regions != null) { + // comments + for (int i = 0; i < regions.length - 1; i++) { + Position position = createProjectionPosition(regions[i], + null); + boolean commentCollapse; + if (position != null) { + if (i == 0 && (regions.length > 2 || fHasHeaderComment) + && element == fFirstType) { + commentCollapse = fAllowCollapsing + && fCollapseHeaderComments; + } else { + commentCollapse = fAllowCollapsing + && fCollapseJavadoc; + } + map.put(new JavaProjectionAnnotation(element, + commentCollapse, true), position); + } + } + // code + Position position = createProjectionPosition( + regions[regions.length - 1], element); + if (position != null) + map.put(new JavaProjectionAnnotation(element, collapse, + false), position); + } + } + } + + private boolean isInnerType(IType type) { + + try { + return type.isMember(); + } catch (JavaModelException x) { + IJavaElement parent = type.getParent(); + if (parent != null) { + int parentType = parent.getElementType(); + return (parentType != IJavaElement.COMPILATION_UNIT && parentType != IJavaElement.CLASS_FILE); + } + } + + return false; + } + + /** + * Computes the projection ranges for a given IJavaElement. + * More than one range may be returned if the element has a leading comment + * which gets folded separately. If there are no foldable regions, + * null is returned. + * + * @param element + * the java element that can be folded + * @return the regions to be folded, or null if there are + * none + */ + private IRegion[] computeProjectionRanges(IJavaElement element) { + + try { + if (element instanceof ISourceReference) { + ISourceReference reference = (ISourceReference) element; + ISourceRange range = reference.getSourceRange(); + + String contents = reference.getSource(); + if (contents == null) + return null; + + List regions = new ArrayList(); + // now add all comments first to the regions list + if (fFirstType == null && element instanceof IType) { + fFirstType = (IType) element; + IRegion headerComment = computeHeaderComment(fFirstType); + if (headerComment != null) { + regions.add(headerComment); + fHasHeaderComment = true; + } + } + + final int shift = range.getOffset(); + int start = shift; + if (element instanceof IType) { + Scanner scanner = ToolFactory.createScanner(true, false, + false, false); + scanner.setSource(contents.toCharArray()); + scanner.setPHPMode(true); + + TokenName token = scanner.getNextToken(); + while (token != ITerminalSymbols.TokenName.EOF) { + + token = scanner.getNextToken(); + start = shift + scanner.getCurrentTokenStartPosition(); + + switch (token) { + case COMMENT_PHPDOC: + case COMMENT_BLOCK: { + int end = shift + + scanner.getCurrentTokenEndPosition() + 1; + regions.add(new Region(start, end - start)); + } + case COMMENT_LINE: + continue; + } + } + } + // at the end add the element region + regions.add(new Region(range.getOffset(), range.getLength())); + + if (regions.size() > 0) { + IRegion[] result = new IRegion[regions.size()]; + regions.toArray(result); + return result; + } + + } + } catch (JavaModelException e) { + } catch (InvalidInputException e) { + } + + return null; + } + + private IRegion computeHeaderComment(IType type) throws JavaModelException { + if (fCachedDocument == null) + return null; + + // search at most up to the first type + ISourceRange range = type.getSourceRange(); + if (range == null) + return null; + int start = 0; + int end = range.getOffset(); + + if (fInput instanceof ISourceReference) { + String content; + try { + content = fCachedDocument.get(start, end - start); + } catch (BadLocationException e) { + return null; // ignore header comment in that case + } + + /* + * code adapted from CommentFormattingStrategy: scan the header + * content up to the first type. Once a comment is found, accumulate + * any additional comments up to the stop condition. The stop + * condition is reaching a package declaration, import container, or + * the end of the input. + */ + IScanner scanner = ToolFactory.createScanner(true, false, false, + false); + scanner.setSource(content.toCharArray()); + + int headerStart = -1; + int headerEnd = -1; + try { + boolean foundComment = false; + TokenName terminal = scanner.getNextToken(); + while (terminal != ITerminalSymbols.TokenName.EOF + && !(terminal == ITerminalSymbols.TokenName.CLASS + || terminal == ITerminalSymbols.TokenName.INTERFACE || foundComment)) { + + if (terminal == ITerminalSymbols.TokenName.COMMENT_PHPDOC + || terminal == ITerminalSymbols.TokenName.COMMENT_BLOCK + || terminal == ITerminalSymbols.TokenName.COMMENT_LINE) { + if (!foundComment) + headerStart = scanner + .getCurrentTokenStartPosition(); + headerEnd = scanner.getCurrentTokenEndPosition(); + foundComment = true; + } + terminal = scanner.getNextToken(); + } + + } catch (InvalidInputException ex) { + return null; + } + + if (headerEnd != -1) { + return new Region(headerStart, headerEnd - headerStart); + } + } + return null; + } + + private Position createProjectionPosition(IRegion region, + IJavaElement element) { + + if (fCachedDocument == null) + return null; + + try { + + int start = fCachedDocument.getLineOfOffset(region.getOffset()); + int end = fCachedDocument.getLineOfOffset(region.getOffset() + + region.getLength()); + if (start != end) { + int offset = fCachedDocument.getLineOffset(start); + int endOffset; + if (fCachedDocument.getNumberOfLines() > end + 1) + endOffset = fCachedDocument.getLineOffset(end + 1); + else if (end > start) + endOffset = fCachedDocument.getLineOffset(end) + + fCachedDocument.getLineLength(end); + else + return null; + if (element instanceof IMember) + return new JavaElementPosition(offset, endOffset - offset, + (IMember) element); + else + return new CommentPosition(offset, endOffset - offset); + } + + } catch (BadLocationException x) { + } + + return null; + } + + protected void processDelta(IJavaElementDelta delta) { + + if (!isInstalled()) + return; + + if ((delta.getFlags() & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_CHILDREN)) == 0) + return; + + ProjectionAnnotationModel model = (ProjectionAnnotationModel) fEditor + .getAdapter(ProjectionAnnotationModel.class); + if (model == null) + return; + + try { + + IDocumentProvider provider = fEditor.getDocumentProvider(); + fCachedDocument = provider.getDocument(fEditor.getEditorInput()); + fCachedModel = model; + fAllowCollapsing = false; + + fFirstType = null; + fHasHeaderComment = false; + + Map additions = new HashMap(); + List deletions = new ArrayList(); + List updates = new ArrayList(); + + Map updated = computeAdditions((IParent) fInput); + Map previous = createAnnotationMap(model); + + Iterator e = updated.keySet().iterator(); + while (e.hasNext()) { + JavaProjectionAnnotation newAnnotation = (JavaProjectionAnnotation) e + .next(); +//+ + Position newPosition = (Position) updated.get(newAnnotation); + additions.put(newAnnotation, newPosition); +//- +// IJavaElement element = newAnnotation.getElement(); +// Position newPosition = (Position) updated.get(newAnnotation); +// +// List annotations = (List) previous.get(element); +// if (annotations == null) { +// +// additions.put(newAnnotation, newPosition); +// +// } else { +// Iterator x = annotations.iterator(); +// boolean matched = false; +// while (x.hasNext()) { +// Tuple tuple = (Tuple) x.next(); +// JavaProjectionAnnotation existingAnnotation = tuple.annotation; +// Position existingPosition = tuple.position; +// if (newAnnotation.isComment() == existingAnnotation +// .isComment()) { +// if (existingPosition != null +// && (!newPosition.equals(existingPosition))) { +// existingPosition.setOffset(newPosition +// .getOffset()); +// existingPosition.setLength(newPosition +// .getLength()); +// updates.add(existingAnnotation); +// } +// matched = true; +// x.remove(); +// break; +// } +// } +// if (!matched) +// additions.put(newAnnotation, newPosition); +// +// if (annotations.isEmpty()) +// previous.remove(element); +// } +//- + } + + e = previous.values().iterator(); + while (e.hasNext()) { + List list = (List) e.next(); + int size = list.size(); + for (int i = 0; i < size; i++) + deletions.add(((Tuple) list.get(i)).annotation); + } + + match(deletions, additions, updates); + + Annotation[] removals = new Annotation[deletions.size()]; + deletions.toArray(removals); + Annotation[] changes = new Annotation[updates.size()]; + updates.toArray(changes); + model.modifyAnnotations(removals, additions, changes); + + } finally { + fCachedDocument = null; + fAllowCollapsing = true; + fCachedModel = null; + + fFirstType = null; + fHasHeaderComment = false; + } + } + + /** + * Matches deleted annotations to changed or added ones. A deleted + * annotation/position tuple that has a matching addition / change is + * updated and marked as changed. The matching tuple is not added (for + * additions) or marked as deletion instead (for changes). The result is + * that more annotations are changed and fewer get deleted/re-added. + */ + private void match(List deletions, Map additions, List changes) { + if (deletions.isEmpty() || (additions.isEmpty() && changes.isEmpty())) + return; + + List newDeletions = new ArrayList(); + List newChanges = new ArrayList(); + + Iterator deletionIterator = deletions.iterator(); + while (deletionIterator.hasNext()) { + JavaProjectionAnnotation deleted = (JavaProjectionAnnotation) deletionIterator + .next(); + Position deletedPosition = fCachedModel.getPosition(deleted); + if (deletedPosition == null) + continue; + + Tuple deletedTuple = new Tuple(deleted, deletedPosition); + + Tuple match = findMatch(deletedTuple, changes, null); + boolean addToDeletions = true; + if (match == null) { + match = findMatch(deletedTuple, additions.keySet(), additions); + addToDeletions = false; + } + + if (match != null) { + IJavaElement element = match.annotation.getElement(); + deleted.setElement(element); + deletedPosition.setLength(match.position.getLength()); + if (deletedPosition instanceof JavaElementPosition + && element instanceof IMember) { + JavaElementPosition jep = (JavaElementPosition) deletedPosition; + jep.setMember((IMember) element); + } + + deletionIterator.remove(); + newChanges.add(deleted); + + if (addToDeletions) + newDeletions.add(match.annotation); + } + } + + deletions.addAll(newDeletions); + changes.addAll(newChanges); + } + + /** + * Finds a match for tuple in a collection of annotations. + * The positions for the JavaProjectionAnnotation instances + * in annotations can be found in the passed + * positionMap or fCachedModel if + * positionMap is null. + *

+ * A tuple is said to match another if their annotations have the same + * comment flag and their position offsets are equal. + *

+ *

+ * If a match is found, the annotation gets removed from + * annotations. + *

+ * + * @param tuple + * the tuple for which we want to find a match + * @param annotations + * collection of JavaProjectionAnnotation + * @param positionMap + * a Map<Annotation, Position> or + * null + * @return a matching tuple or null for no match + */ + private Tuple findMatch(Tuple tuple, Collection annotations, Map positionMap) { + Iterator it = annotations.iterator(); + while (it.hasNext()) { + JavaProjectionAnnotation annotation = (JavaProjectionAnnotation) it + .next(); + if (tuple.annotation.isComment() == annotation.isComment()) { + Position position = positionMap == null ? fCachedModel + .getPosition(annotation) : (Position) positionMap + .get(annotation); + if (position == null) + continue; + + if (tuple.position.getOffset() == position.getOffset()) { + it.remove(); + return new Tuple(annotation, position); + } + } + } + + return null; + } + + private Map createAnnotationMap(IAnnotationModel model) { + Map map = new HashMap(); + Iterator e = model.getAnnotationIterator(); + while (e.hasNext()) { + Object annotation = e.next(); + if (annotation instanceof JavaProjectionAnnotation) { + JavaProjectionAnnotation java = (JavaProjectionAnnotation) annotation; + Position position = model.getPosition(java); + Assert.isNotNull(position); + List list = (List) map.get(java.getElement()); + if (list == null) { + list = new ArrayList(2); + map.put(java.getElement(), list); + } + list.add(new Tuple(java, position)); + } + } + + Comparator comparator = new Comparator() { + public int compare(Object o1, Object o2) { + return ((Tuple) o1).position.getOffset() + - ((Tuple) o2).position.getOffset(); + } + }; + for (Iterator it = map.values().iterator(); it.hasNext();) { + List list = (List) it.next(); + Collections.sort(list, comparator); + } + return map; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/FoldingMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java new file mode 100644 index 0000000..99f7f2f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/folding/JavaFoldingStructureProviderRegistry.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.folding; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.Platform; + +/** + * @since 3.0 + */ +public class JavaFoldingStructureProviderRegistry { + + private static final String EXTENSION_POINT = "foldingStructureProviders"; //$NON-NLS-1$ + + /** The map of descriptors, indexed by their identifiers. */ + private Map fDescriptors; + + /** + * Creates a new instance. + */ + public JavaFoldingStructureProviderRegistry() { + } + + /** + * Returns an array of IJavaFoldingProviderDescriptor + * describing all extension to the foldingProviders extension + * point. + * + * @return the list of extensions to the + * quickDiffReferenceProvider extension point. + */ + public JavaFoldingStructureProviderDescriptor[] getFoldingProviderDescriptors() { + synchronized (this) { + ensureRegistered(); + return (JavaFoldingStructureProviderDescriptor[]) fDescriptors + .values() + .toArray( + new JavaFoldingStructureProviderDescriptor[fDescriptors + .size()]); + } + } + + /** + * Returns the folding provider with identifier id or + * null if no such provider is registered. + * + * @param id + * the identifier for which a provider is wanted + * @return the corresponding provider, or null if none can be + * found + */ + public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor( + String id) { + synchronized (this) { + ensureRegistered(); + return (JavaFoldingStructureProviderDescriptor) fDescriptors + .get(id); + } + } + + /** + * Instantiates and returns the provider that is currently configured in the + * preferences. + * + * @return the current provider according to the preferences + */ + public IJavaFoldingStructureProvider getCurrentFoldingProvider() { + String id = PHPeclipsePlugin.getDefault().getPreferenceStore() + .getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER); + JavaFoldingStructureProviderDescriptor desc = getFoldingProviderDescriptor(id); + if (desc != null) { + try { + return desc.createProvider(); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + } + return null; + } + + /** + * Ensures that the extensions are read and stored in + * fDescriptors. + */ + private void ensureRegistered() { + if (fDescriptors == null) + reloadExtensions(); + } + + /** + * Reads all extensions. + *

+ * This method can be called more than once in order to reload from a + * changed extension registry. + *

+ */ + public void reloadExtensions() { + IExtensionRegistry registry = Platform.getExtensionRegistry(); + Map map = new HashMap(); + + IConfigurationElement[] elements = registry + .getConfigurationElementsFor(PHPeclipsePlugin.getPluginId(), + EXTENSION_POINT); + for (int i = 0; i < elements.length; i++) { + JavaFoldingStructureProviderDescriptor desc = new JavaFoldingStructureProviderDescriptor( + elements[i]); + map.put(desc.getId(), desc); + } + + synchronized (this) { + fDescriptors = Collections.unmodifiableMap(map); + } + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IInvocationContext.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IJavaReconcilingListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IPHPCompletionProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IReconcilingParticipant.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaFormattingStrategy.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaHoverMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaParameterListValidator.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java new file mode 100644 index 0000000..00919f8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java @@ -0,0 +1,217 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2003 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +public class JavaReconcilingStrategy implements IReconcilingStrategy, + IReconcilingStrategyExtension { + + private ITextEditor fEditor; + + private IWorkingCopyManager fManager; + + private IDocumentProvider fDocumentProvider; + + private IProgressMonitor fProgressMonitor; + + private boolean fNotify = true; + + private IJavaReconcilingListener fJavaReconcilingListener; + + private boolean fIsJavaReconcilingListener; + + public JavaReconcilingStrategy(ITextEditor editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + fDocumentProvider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + fIsJavaReconcilingListener = fEditor instanceof IJavaReconcilingListener; + if (fIsJavaReconcilingListener) + fJavaReconcilingListener = (IJavaReconcilingListener) fEditor; + } + + private IProblemRequestorExtension getProblemRequestorExtension() { + IAnnotationModel model = fDocumentProvider.getAnnotationModel(fEditor + .getEditorInput()); + if (model instanceof IProblemRequestorExtension) + return (IProblemRequestorExtension) model; + return null; + } + + private void reconcile() { + // // try { + // + // /* fix for missing cancel flag communication */ + // IProblemRequestorExtension extension = + // getProblemRequestorExtension(); + // if (extension != null) + // extension.setProgressMonitor(fProgressMonitor); + // + // // reconcile + // // synchronized (unit) { + // // unit.reconcile(true, fProgressMonitor); + // // } + // + // Parser parser = new Parser(); + // parser.initializeScanner(); + // // actualParser.setFileToParse(fileToParse); + // String text = + // fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()).get(); + // parser.init(text); + // parser.reportSyntaxError(); + // // checkAndReportBracketAnomalies(parser.problemReporter()); + // + // /* fix for missing cancel flag communication */ + // if (extension != null) + // extension.setProgressMonitor(null); + // + // // update participants + // try { + // if (fEditor instanceof IReconcilingParticipant && fNotify && + // !fProgressMonitor.isCanceled()) { + // IReconcilingParticipant p = (IReconcilingParticipant) fEditor; + // p.reconciled(); + // } + // } finally { + // fNotify = true; + // } + + // JDT implementation: + try { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + if (unit != null) { + try { + + /* fix for missing cancel flag communication */ + IProblemRequestorExtension extension = getProblemRequestorExtension(); + if (extension != null) + extension.setProgressMonitor(fProgressMonitor); + + // reconcile + synchronized (unit) { + unit.reconcile(true, fProgressMonitor); + } + + /* fix for missing cancel flag communication */ + if (extension != null) + extension.setProgressMonitor(null); + + // update participants + try { + if (fEditor instanceof IReconcilingParticipant + && fNotify && !fProgressMonitor.isCanceled()) { + IReconcilingParticipant p = (IReconcilingParticipant) fEditor; + p.reconciled(); + } + } finally { + fNotify = true; + } + + } catch (JavaModelException x) { + // swallow exception + } + } + } finally { + // Always notify listeners, see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=55969 for the final + // solution + try { + if (fIsJavaReconcilingListener) { + IProgressMonitor pm = fProgressMonitor; + if (pm == null) + pm = new NullProgressMonitor(); + fJavaReconcilingListener.reconciled(null, !fNotify, pm); + } + } finally { + fNotify = true; + } + + } + } + + /* + * @see IReconcilingStrategy#reconcile(IRegion) + */ + public void reconcile(IRegion partition) { + reconcile(); + } + + /* + * @see IReconcilingStrategy#reconcile(DirtyRegion, IRegion) + */ + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + reconcile(); + } + + /* + * @see IReconcilingStrategy#setDocument(IDocument) + */ + public void setDocument(IDocument document) { + } + + /* + * @see IReconcilingStrategyExtension#setProgressMonitor(IProgressMonitor) + */ + public void setProgressMonitor(IProgressMonitor monitor) { + fProgressMonitor = monitor; + } + + /* + * @see IReconcilingStrategyExtension#initialReconcile() + */ + public void initialReconcile() { + reconcile(); + } + + /** + * Tells this strategy whether to inform its participants. + * + * @param notify + * true if participant should be notified + */ +// public void notifyParticipants(boolean notify) { +// fNotify = notify; +// } + + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify + * true if listeners should be notified + */ + public void notifyListeners(boolean notify) { + fNotify = notify; + } + + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + if (fIsJavaReconcilingListener) + fJavaReconcilingListener.aboutToBeReconciled(); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java new file mode 100644 index 0000000..14dff9c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategyDQ.java @@ -0,0 +1,229 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.java; + +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.ITextEditorExtension3; + +/** + * Auto indent strategy for java strings + */ +public class JavaStringAutoIndentStrategyDQ extends + DefaultIndentLineAutoEditStrategy { + + private String fPartitioning; + + /** + * The input string doesn't contain any line delimiter. + * + * @param inputString + * the given input string + * @return the displayable string. + */ + private String displayString(String inputString, String indentation, + String delimiter) { + + int length = inputString.length(); + StringBuffer buffer = new StringBuffer(length); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + inputString, "\n\r", true); //$NON-NLS-1$ + while (tokenizer.hasMoreTokens()) { + + String token = tokenizer.nextToken(); + if (token.equals("\r")) { //$NON-NLS-1$ + buffer.append("\\r"); //$NON-NLS-1$ + if (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + if (token.equals("\n")) { //$NON-NLS-1$ + buffer.append("\\n"); //$NON-NLS-1$ + buffer.append("\" . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\""); //$NON-NLS-1$ + continue; + } else { + buffer.append("\" . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\""); //$NON-NLS-1$ + } + } else { + continue; + } + } else if (token.equals("\n")) { //$NON-NLS-1$ + buffer.append("\\n"); //$NON-NLS-1$ + buffer.append("\" . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\""); //$NON-NLS-1$ + continue; + } + + StringBuffer tokenBuffer = new StringBuffer(); + for (int i = 0; i < token.length(); i++) { + char c = token.charAt(i); + switch (c) { + case '\r': + tokenBuffer.append("\\r"); //$NON-NLS-1$ + break; + case '\n': + tokenBuffer.append("\\n"); //$NON-NLS-1$ + break; + case '\b': + tokenBuffer.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + // keep tabs verbatim + tokenBuffer.append("\t"); //$NON-NLS-1$ + break; + case '\f': + tokenBuffer.append("\\f"); //$NON-NLS-1$ + break; + case '\"': + tokenBuffer.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + tokenBuffer.append("\\'"); //$NON-NLS-1$ + break; + case '\\': + tokenBuffer.append("\\\\"); //$NON-NLS-1$ + break; + default: + tokenBuffer.append(c); + } + } + buffer.append(tokenBuffer); + } + return buffer.toString(); + } + + /** + * Creates a new Java string auto indent strategy for the given document + * partitioning. + * + * @param partitioning + * the document partitioning + */ + public JavaStringAutoIndentStrategyDQ(String partitioning) { + super(); + fPartitioning = partitioning; + } + + private boolean isLineDelimiter(IDocument document, String text) { + String[] delimiters = document.getLegalLineDelimiters(); + if (delimiters != null) + return TextUtilities.equals(delimiters, text) > -1; + return false; + } + + private String getLineIndentation(IDocument document, int offset) + throws BadLocationException { + + // find start of line + int adjustedOffset = (offset == document.getLength() ? offset - 1 + : offset); + IRegion line = document.getLineInformationOfOffset(adjustedOffset); + int start = line.getOffset(); + + // find white spaces + int end = findEndOfWhiteSpace(document, start, offset); + + return document.get(start, end - start); + } + + private String getModifiedText(String string, String indentation, + String delimiter) throws BadLocationException { + return displayString(string, indentation, delimiter); + } + + private void javaStringIndentAfterNewLine(IDocument document, + DocumentCommand command) throws BadLocationException { + + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, false); + int offset = partition.getOffset(); + int length = partition.getLength(); + + if (command.offset == offset) { + // we are really just before the string partition -> feet the event + // through the java indenter + // new + // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, + // command); + return; + } + + if (command.offset == offset + length + && document.getChar(offset + length - 1) == '\"') + return; + + String indentation = getLineIndentation(document, command.offset); + String delimiter = TextUtilities.getDefaultLineDelimiter(document); + + IRegion line = document.getLineInformationOfOffset(offset); + String string = document.get(line.getOffset(), offset + - line.getOffset()); + if (string.trim().length() != 0) + indentation += String.valueOf("\t\t"); //$NON-NLS-1$ + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + if (isLineDelimiter(document, command.text)) + command.text = "\" ." + command.text + indentation + "\""; //$NON-NLS-1$//$NON-NLS-2$ + else if (command.text.length() > 1 + && preferenceStore + .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ)) + command.text = getModifiedText(command.text, indentation, delimiter); + } + + private boolean isSmartMode() { + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); + if (part instanceof ITextEditorExtension3) { + ITextEditorExtension3 extension = (ITextEditorExtension3) part; + return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; + } + } + return false; + } + + /* + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, + * DocumentCommand) + */ + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + try { + if (command.length != 0 || command.text == null) + return; + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + if (preferenceStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ) + && isSmartMode()) + javaStringIndentAfterNewLine(document, command); + + } catch (BadLocationException e) { + } + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java new file mode 100644 index 0000000..d58f57b --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaStringAutoIndentStrategySQ.java @@ -0,0 +1,229 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.java; + +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.texteditor.ITextEditorExtension3; + +/** + * Auto indent strategy for java strings + */ +public class JavaStringAutoIndentStrategySQ extends + DefaultIndentLineAutoEditStrategy { + + private String fPartitioning; + + /** + * The input string doesn't contain any line delimiter. + * + * @param inputString + * the given input string + * @return the displayable string. + */ + private String displayString(String inputString, String indentation, + String delimiter) { + + int length = inputString.length(); + StringBuffer buffer = new StringBuffer(length); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + inputString, "\n\r", true); //$NON-NLS-1$ + while (tokenizer.hasMoreTokens()) { + + String token = tokenizer.nextToken(); + if (token.equals("\r")) { //$NON-NLS-1$ + buffer.append("\\r"); //$NON-NLS-1$ + if (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + if (token.equals("\n")) { //$NON-NLS-1$ + buffer.append("\\n"); //$NON-NLS-1$ + buffer.append("\' . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\'"); //$NON-NLS-1$ + continue; + } else { + buffer.append("\' . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\'"); //$NON-NLS-1$ + } + } else { + continue; + } + } else if (token.equals("\n")) { //$NON-NLS-1$ + buffer.append("\\n"); //$NON-NLS-1$ + buffer.append("\' . " + delimiter); //$NON-NLS-1$ + buffer.append(indentation); + buffer.append("\'"); //$NON-NLS-1$ + continue; + } + + StringBuffer tokenBuffer = new StringBuffer(); + for (int i = 0; i < token.length(); i++) { + char c = token.charAt(i); + switch (c) { + case '\r': + tokenBuffer.append("\\r"); //$NON-NLS-1$ + break; + case '\n': + tokenBuffer.append("\\n"); //$NON-NLS-1$ + break; + case '\b': + tokenBuffer.append("\\b"); //$NON-NLS-1$ + break; + case '\t': + // keep tabs verbatim + tokenBuffer.append("\t"); //$NON-NLS-1$ + break; + case '\f': + tokenBuffer.append("\\f"); //$NON-NLS-1$ + break; + case '\"': + tokenBuffer.append("\\\""); //$NON-NLS-1$ + break; + case '\'': + tokenBuffer.append("\\'"); //$NON-NLS-1$ + break; + case '\\': + tokenBuffer.append("\\\\"); //$NON-NLS-1$ + break; + default: + tokenBuffer.append(c); + } + } + buffer.append(tokenBuffer); + } + return buffer.toString(); + } + + /** + * Creates a new Java string auto indent strategy for the given document + * partitioning. + * + * @param partitioning + * the document partitioning + */ + public JavaStringAutoIndentStrategySQ(String partitioning) { + super(); + fPartitioning = partitioning; + } + + private boolean isLineDelimiter(IDocument document, String text) { + String[] delimiters = document.getLegalLineDelimiters(); + if (delimiters != null) + return TextUtilities.equals(delimiters, text) > -1; + return false; + } + + private String getLineIndentation(IDocument document, int offset) + throws BadLocationException { + + // find start of line + int adjustedOffset = (offset == document.getLength() ? offset - 1 + : offset); + IRegion line = document.getLineInformationOfOffset(adjustedOffset); + int start = line.getOffset(); + + // find white spaces + int end = findEndOfWhiteSpace(document, start, offset); + + return document.get(start, end - start); + } + + private String getModifiedText(String string, String indentation, + String delimiter) throws BadLocationException { + return displayString(string, indentation, delimiter); + } + + private void javaStringIndentAfterNewLine(IDocument document, + DocumentCommand command) throws BadLocationException { + + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, false); + int offset = partition.getOffset(); + int length = partition.getLength(); + + if (command.offset == offset) { + // we are really just before the string partition -> feet the event + // through the java indenter + // new + // JavaAutoIndentStrategy(fPartitioning).customizeDocumentCommand(document, + // command); + return; + } + + if (command.offset == offset + length + && document.getChar(offset + length - 1) == '\'') + return; + + String indentation = getLineIndentation(document, command.offset); + String delimiter = TextUtilities.getDefaultLineDelimiter(document); + + IRegion line = document.getLineInformationOfOffset(offset); + String string = document.get(line.getOffset(), offset + - line.getOffset()); + if (string.trim().length() != 0) + indentation += String.valueOf("\t\t"); //$NON-NLS-1$ + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + if (isLineDelimiter(document, command.text)) + command.text = "\' ." + command.text + indentation + "\'"; //$NON-NLS-1$//$NON-NLS-2$ + else if (command.text.length() > 1 + && preferenceStore + .getBoolean(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ)) + command.text = getModifiedText(command.text, indentation, delimiter); + } + + private boolean isSmartMode() { + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); + if (part instanceof ITextEditorExtension3) { + ITextEditorExtension3 extension = (ITextEditorExtension3) part; + return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; + } + } + return false; + } + + /* + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(IDocument, + * DocumentCommand) + */ + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + try { + if (command.length != 0 || command.text == null) + return; + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + if (preferenceStore + .getBoolean(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ) + && isSmartMode()) + javaStringIndentAfterNewLine(document, command); + + } catch (BadLocationException e) { + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/PHPCompletionProposalComparator.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java new file mode 100644 index 0000000..64fc808 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractAnnotationHover.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.util.Iterator; + +import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaAnnotationIterator; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.editors.text.EditorsUI; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; +import org.eclipse.ui.texteditor.IDocumentProvider; + +/** + * Abstract super class for annotation hovers. + * + * @since 3.0 + */ +public abstract class AbstractAnnotationHover extends + AbstractJavaEditorTextHover { + + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + + private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); + + private boolean fAllAnnotations; + + public AbstractAnnotationHover(boolean allAnnotations) { + fAllAnnotations = allAnnotations; + } + + /* + * Formats a message as HTML text. + */ + private String formatMessage(String message) { + StringBuffer buffer = new StringBuffer(); + HTMLPrinter.addPageProlog(buffer); + HTMLPrinter.addParagraph(buffer, HTMLPrinter + .convertToHTMLContent(message)); + HTMLPrinter.addPageEpilog(buffer); + return buffer.toString(); + } + + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) + */ + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + + if (getEditor() == null) + return null; + + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + IAnnotationModel model = provider.getAnnotationModel(getEditor() + .getEditorInput()); + + if (model != null) { + Iterator e = new JavaAnnotationIterator(model, true, + fAllAnnotations); + int layer = -1; + String message = null; + while (e.hasNext()) { + Annotation a = (Annotation) e.next(); + + AnnotationPreference preference = getAnnotationPreference(a); + if (preference == null + || !(preference.getTextPreferenceKey() != null + && fStore.getBoolean(preference + .getTextPreferenceKey()) || (preference + .getHighlightPreferenceKey() != null && fStore + .getBoolean(preference + .getHighlightPreferenceKey())))) + continue; + + Position p = model.getPosition(a); + + int l = fAnnotationAccess.getLayer(a); + + if (l > layer + && p != null + && p.overlapsWith(hoverRegion.getOffset(), hoverRegion + .getLength())) { + String msg = a.getText(); + if (msg != null && msg.trim().length() > 0) { + message = msg; + layer = l; + } + } + } + if (layer > -1) + return formatMessage(message); + } + + return null; + } + + /* + * @see IJavaEditorTextHover#setEditor(IEditorPart) + */ + public void setEditor(IEditorPart editor) { + if (editor instanceof PHPUnitEditor) + super.setEditor(editor); + else + super.setEditor(null); + } + + /** + * Returns the annotation preference for the given annotation. + * + * @param annotation + * the annotation + * @return the annotation preference or null if none + */ + private AnnotationPreference getAnnotationPreference(Annotation annotation) { + + if (annotation.isMarkedDeleted()) + return null; + return EditorsUI.getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java new file mode 100644 index 0000000..a8847b4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.util.List; + +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; +import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.DefaultInformationControl; +import org.eclipse.jface.text.IInformationControl; +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +//import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorPart; +//import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.commands.ICommand; +//import org.eclipse.ui.commands.ICommandManager; +import org.eclipse.ui.commands.IKeySequenceBinding; +import org.eclipse.ui.keys.KeySequence; +//import org.eclipse.jface.bindings.keys.KeySequence; +/** + * Abstract class for providing hover information for Java elements. + * + * @since 2.1 + */ +public abstract class AbstractJavaEditorTextHover implements + IJavaEditorTextHover { + + private IEditorPart fEditor; + + private ICommand fCommand; + { +// ICommandManager commandManager = PlatformUI.getWorkbench() +// .getCommandSupport().getCommandManager(); + // fCommand= + // commandManager.getCommand(PHPEditorActionDefinitionIds.SHOW_JAVADOC); + // if (!fCommand.isDefined()) + fCommand = null; + } + + /* + * @see IJavaEditorTextHover#setEditor(IEditorPart) + */ + public void setEditor(IEditorPart editor) { + fEditor = editor; + } + + protected IEditorPart getEditor() { + return fEditor; + } + + // protected ICodeAssist getCodeAssist() { + // if (fEditor != null) { + // IEditorInput input= fEditor.getEditorInput(); + // if (input instanceof IClassFileEditorInput) { + // IClassFileEditorInput cfeInput= (IClassFileEditorInput) input; + // return cfeInput.getClassFile(); + // } + // + // IWorkingCopyManager manager= + // PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + // return manager.getWorkingCopy(input); + // } + // + // return null; + // } + + /* + * @see ITextHover#getHoverRegion(ITextViewer, int) + */ + public IRegion getHoverRegion(ITextViewer textViewer, int offset) { + return JavaWordFinder.findWord(textViewer.getDocument(), offset); + } + + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) + */ + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + + // ICodeAssist resolve= getCodeAssist(); + // if (resolve != null) { + // try { + // IJavaElement[] result= null; + // + // synchronized (resolve) { + // result= resolve.codeSelect(hoverRegion.getOffset(), + // hoverRegion.getLength()); + // } + // + // if (result == null) + // return null; + // + // int nResults= result.length; + // if (nResults == 0) + // return null; + // + // return getHoverInfo(result); + // + // } catch (JavaModelException x) { + // PHPeclipsePlugin.log(x.getStatus()); + // } + // } + return null; + } + + /** + * Provides hover information for the given Java elements. + * + * @return the hover information string + * @since 2.1 + */ + protected String getHoverInfo(IJavaElement[] javaElements) { + return null; + } + + /* + * @see ITextHoverExtension#getHoverControlCreator() + * @since 3.0 + */ + public IInformationControlCreator getHoverControlCreator() { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + //incastrix + // return new DefaultInformationControl(parent, SWT.NONE, +// new HTMLTextPresenter(true), +// getTooltipAffordanceString()); + return new DefaultInformationControl(parent, getTooltipAffordanceString(), + new HTMLTextPresenter(true)); + } + }; + } + + /** + * Returns the tool tip affordance string. + * + * @return the affordance string or null if disabled or no + * key binding is defined + * @since 3.0 + */ + protected String getTooltipAffordanceString() { + if (!PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) + return null; + + KeySequence[] sequences = getKeySequences(); + if (sequences == null) + return null; + + String keySequence = sequences[0].format(); + return JavaHoverMessages.getFormattedString( + "JavaTextHover.makeStickyHint", keySequence); //$NON-NLS-1$ + } + + /** + * Returns the array of valid key sequence bindings for the show tool tip + * description command. + * + * @return the array with the {@link KeySequence}s + * + * @since 3.0 + */ + private KeySequence[] getKeySequences() { + if (fCommand != null) { + List list = fCommand.getKeySequenceBindings(); + if (!list.isEmpty()) { + KeySequence[] keySequences = new KeySequence[list.size()]; + for (int i = 0; i < keySequences.length; i++) { + keySequences[i] = ((IKeySequenceBinding) list.get(i)) + .getKeySequence(); + } + return keySequences; + } + } + return null; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpandHover.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationExpansionControl.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java new file mode 100644 index 0000000..d698b7f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AnnotationHover.java @@ -0,0 +1,159 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.util.Iterator; + +import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; +//import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaAnnotationIterator; +import net.sourceforge.phpeclipse.phpeditor.PHPTextHover; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.editors.text.EditorsUI; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; +import org.eclipse.ui.texteditor.IDocumentProvider; + +public class AnnotationHover extends AbstractJavaEditorTextHover { + + // private IPreferenceStore fStore = + // PHPeclipsePlugin.getDefault().getPreferenceStore(); + private IPreferenceStore fStore = EditorsUI.getPreferenceStore(); + + private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); + + private PHPTextHover fPHPTextHover = null; + + /* + * Formats a message as HTML text. + */ + private String formatMessage(String message) { + StringBuffer buffer = new StringBuffer(); + HTMLPrinter.addPageProlog(buffer); + HTMLPrinter.addParagraph(buffer, message); // HTMLPrinter.convertToHTMLContent(message)); + HTMLPrinter.addPageEpilog(buffer); + return buffer.toString(); + } + + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) + */ + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + + if (getEditor() == null) + return null; + + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + IAnnotationModel model = provider.getAnnotationModel(getEditor() + .getEditorInput()); + String message = null; + if (model != null) { + Iterator e = new JavaAnnotationIterator(model, true); + int layer = -1; + + while (e.hasNext()) { + Annotation a = (Annotation) e.next(); + + AnnotationPreference preference = getAnnotationPreference(a); + if (preference == null + || !(fStore.getBoolean(preference + .getTextPreferenceKey()) || (preference + .getHighlightPreferenceKey() != null && fStore + .getBoolean(preference + .getHighlightPreferenceKey())))) + continue; + + Position p = model.getPosition(a); + + int l = fAnnotationAccess.getLayer(a); + + if (l > layer + && p != null + && p.overlapsWith(hoverRegion.getOffset(), hoverRegion + .getLength())) { + String msg = a.getText(); + if (msg != null && msg.trim().length() > 0) { + message = msg; + layer = l; + } + } + } + if (layer > -1) + return formatMessage(message); + } + // Added as long as the above doesn't work + if (fPHPTextHover != null) { + message = fPHPTextHover.getHoverInfo(textViewer, hoverRegion); + if (message != null) { + return formatMessage(message); + } + } + return null; + } + + /* + * @see IJavaEditorTextHover#setEditor(IEditorPart) + */ + public void setEditor(IEditorPart editor) { + if (editor instanceof PHPUnitEditor) { + super.setEditor(editor); + if (editor != null) { + IEditorInput editorInput = editor.getEditorInput(); + if (editorInput instanceof IFileEditorInput) { + try { + IFile f = ((IFileEditorInput) editorInput).getFile(); + fPHPTextHover = new PHPTextHover(f.getProject()); + return; + } catch (NullPointerException e) { + // this exception occurs, if getTextHover is called by + // preference pages ! + } + } + } + fPHPTextHover = new PHPTextHover(null); + } else { + super.setEditor(null); + } + } + + /** + * Returns the annotation preference for the given annotation. + * + * @param annotation + * the annotation + * @return the annotation preference or null if none + */ + private AnnotationPreference getAnnotationPreference(Annotation annotation) { + + if (annotation.isMarkedDeleted()) + return null; + return EditorsUI.getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); + } + +// static boolean isJavaProblemHover(String id) { +// return PreferenceConstants.ID_PROBLEM_HOVER.equals(id); +// } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java new file mode 100644 index 0000000..a9da92f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextHoverExtension; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.information.IInformationProviderExtension2; +//import org.eclipse.ui.IEditorPart; + +/** + * Caution: this implementation is a layer breaker and contains some "shortcuts" + */ +public class BestMatchHover extends AbstractJavaEditorTextHover implements + ITextHoverExtension, IInformationProviderExtension2 { + + private List fTextHoverSpecifications; + + private List fInstantiatedTextHovers; + + private ITextHover fBestHover; + + public BestMatchHover() { + installTextHovers(); + } + +// public BestMatchHover(IEditorPart editor) { +// this(); +// setEditor(editor); +// } + + /** + * Installs all text hovers. + */ + private void installTextHovers() { + + // initialize lists - indicates that the initialization happened + fTextHoverSpecifications = new ArrayList(2); + fInstantiatedTextHovers = new ArrayList(2); + + // populate list + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .getDefault().getJavaEditorTextHoverDescriptors(); + for (int i = 0; i < hoverDescs.length; i++) { + // ensure that we don't add ourselves to the list + if (!PreferenceConstants.ID_BESTMATCH_HOVER.equals(hoverDescs[i] + .getId())) + fTextHoverSpecifications.add(hoverDescs[i]); + } + } + + private void checkTextHovers() { + if (fTextHoverSpecifications.size() == 0) + return; + + for (Iterator iterator = new ArrayList(fTextHoverSpecifications) + .iterator(); iterator.hasNext();) { + JavaEditorTextHoverDescriptor spec = (JavaEditorTextHoverDescriptor) iterator + .next(); + + IJavaEditorTextHover hover = spec.createTextHover(); + if (hover != null) { + hover.setEditor(getEditor()); + addTextHover(hover); + fTextHoverSpecifications.remove(spec); + } + } + } + + protected void addTextHover(ITextHover hover) { + if (!fInstantiatedTextHovers.contains(hover)) + fInstantiatedTextHovers.add(hover); + } + + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) + */ + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + + checkTextHovers(); + fBestHover = null; + + if (fInstantiatedTextHovers == null) + return null; + + for (Iterator iterator = fInstantiatedTextHovers.iterator(); iterator + .hasNext();) { + ITextHover hover = (ITextHover) iterator.next(); + + String s = hover.getHoverInfo(textViewer, hoverRegion); + if (s != null && s.trim().length() > 0) { + fBestHover = hover; + return s; + } + } + + return null; + } + + /* + * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() + * @since 3.0 + */ + public IInformationControlCreator getHoverControlCreator() { + if (fBestHover instanceof ITextHoverExtension) + return ((ITextHoverExtension) fBestHover).getHoverControlCreator(); + + return null; + } + + /* + * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() + * @since 3.0 + */ + public IInformationControlCreator getInformationPresenterControlCreator() { + if (fBestHover instanceof IInformationProviderExtension2) + return ((IInformationProviderExtension2) fBestHover) + .getInformationPresenterControlCreator(); + + return null; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java new file mode 100644 index 0000000..01081bd --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java @@ -0,0 +1,367 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.text.Collator; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.StringTokenizer; + +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.EditorUtility; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.swt.SWT; +import org.osgi.framework.Bundle; + +/** + * Describes a Java editor text hover. + * + * @since 2.1 + */ +public class JavaEditorTextHoverDescriptor implements Comparable { + + private static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT = "net.sourceforge.phpeclipse.phpEditorTextHovers"; //$NON-NLS-1$ + + private static final String HOVER_TAG = "hover"; //$NON-NLS-1$ + + private static final String ID_ATTRIBUTE = "id"; //$NON-NLS-1$ + + private static final String CLASS_ATTRIBUTE = "class"; //$NON-NLS-1$ + + private static final String LABEL_ATTRIBUTE = "label"; //$NON-NLS-1$ + + private static final String ACTIVATE_PLUG_IN_ATTRIBUTE = "activate"; //$NON-NLS-1$ + + private static final String DESCRIPTION_ATTRIBUTE = "description"; //$NON-NLS-1$ + + public static final String NO_MODIFIER = "0"; //$NON-NLS-1$ + + public static final String DISABLED_TAG = "!"; //$NON-NLS-1$ + + public static final String VALUE_SEPARATOR = ";"; //$NON-NLS-1$ + + private int fStateMask; + + private String fModifierString; + + private boolean fIsEnabled; + + private IConfigurationElement fElement; + + /** + * Returns all Java editor text hovers contributed to the workbench. + */ + public static JavaEditorTextHoverDescriptor[] getContributedHovers() { + IExtensionRegistry registry = Platform.getExtensionRegistry(); + IConfigurationElement[] elements = registry + .getConfigurationElementsFor(JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT); + JavaEditorTextHoverDescriptor[] hoverDescs = createDescriptors(elements); + initializeFromPreferences(hoverDescs); + return hoverDescs; + } + + /** + * Computes the state mask for the given modifier string. + * + * @param modifiers + * the string with the modifiers, separated by '+', '-', ';', ',' + * or '.' + * @return the state mask or -1 if the input is invalid + */ + public static int computeStateMask(String modifiers) { + if (modifiers == null) + return -1; + + if (modifiers.length() == 0) + return SWT.NONE; + + int stateMask = 0; + StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + ",;.:+-* "); //$NON-NLS-1$ + while (modifierTokenizer.hasMoreTokens()) { + int modifier = EditorUtility + .findLocalizedModifier(modifierTokenizer.nextToken()); + if (modifier == 0 || (stateMask & modifier) == modifier) + return -1; + stateMask = stateMask | modifier; + } + return stateMask; + } + + /** + * Creates a new Java Editor text hover descriptor from the given + * configuration element. + */ + private JavaEditorTextHoverDescriptor(IConfigurationElement element) { + Assert.isNotNull(element); + fElement = element; + } + + /** + * Creates the Java editor text hover. + */ + public IJavaEditorTextHover createTextHover() { + String pluginId = fElement.getDeclaringExtension().getNamespace(); + boolean isHoversPlugInActivated = Platform.getBundle(pluginId) + .getState() == Bundle.ACTIVE; + if (isHoversPlugInActivated || canActivatePlugIn()) { + try { + return (IJavaEditorTextHover) fElement + .createExecutableExtension(CLASS_ATTRIBUTE); + } catch (CoreException x) { + PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin + .getPluginId(), 0, JavaHoverMessages + .getString("JavaTextHover.createTextHover"), null)); //$NON-NLS-1$ + } + } + + return null; + } + + // ---- XML Attribute accessors + // --------------------------------------------- + + /** + * Returns the hover's id. + */ + public String getId() { + return fElement.getAttribute(ID_ATTRIBUTE); + } + + /** + * Returns the hover's class name. + */ + public String getHoverClassName() { + return fElement.getAttribute(CLASS_ATTRIBUTE); + } + + /** + * Returns the hover's label. + */ + public String getLabel() { + String label = fElement.getAttribute(LABEL_ATTRIBUTE); + if (label != null) + return label; + + // Return simple class name + label = getHoverClassName(); + int lastDot = label.lastIndexOf('.'); + if (lastDot >= 0 && lastDot < label.length() - 1) + return label.substring(lastDot + 1); + else + return label; + } + + /** + * Returns the hover's description. + * + * @return the hover's description or null if not provided + */ + public String getDescription() { + return fElement.getAttribute(DESCRIPTION_ATTRIBUTE); + } + + public boolean canActivatePlugIn() { + return Boolean.valueOf( + fElement.getAttribute(ACTIVATE_PLUG_IN_ATTRIBUTE)) + .booleanValue(); + } + + public boolean equals(Object obj) { + if (obj == null || !obj.getClass().equals(this.getClass()) + || getId() == null) + return false; + return getId().equals(((JavaEditorTextHoverDescriptor) obj).getId()); + } + + public int hashCode() { + return getId().hashCode(); + } + + /* + * Implements a method from IComparable + */ + public int compareTo(Object o) { + return Collator.getInstance().compare(getLabel(), + ((JavaEditorTextHoverDescriptor) o).getLabel()); + } + + // /** + // * @param descriptor a JavaEditorTextHoverDescriptor + // * @return true if this contributed hover depends on the + // other one + // */ + // public boolean dependsOn(JavaEditorTextHoverDescriptor descriptor) { + // if (descriptor == null) + // return false; + // + // IPluginDescriptor thisPluginDescriptor= + // fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); + // IPluginDescriptor otherPluginDescriptor= + // descriptor.fElement.getDeclaringExtension().getDeclaringPluginDescriptor(); + // return dependsOn(thisPluginDescriptor, otherPluginDescriptor); + // } + + // private boolean dependsOn(IPluginDescriptor descriptor0, + // IPluginDescriptor descriptor1) { + // + // IPluginRegistry registry= Platform.getPluginRegistry(); + // IPluginPrerequisite[] prerequisites= + // descriptor0.getPluginPrerequisites(); + // + // for (int i= 0; i < prerequisites.length; i++) { + // IPluginPrerequisite prerequisite= prerequisites[i]; + // String id= prerequisite.getUniqueIdentifier(); + // IPluginDescriptor descriptor= registry.getPluginDescriptor(id); + // + // if (descriptor != null && (descriptor.equals(descriptor1) || + // dependsOn(descriptor, descriptor1))) + // return true; + // } + // + // return false; + // } + + private static JavaEditorTextHoverDescriptor[] createDescriptors( + IConfigurationElement[] elements) { + List result = new ArrayList(elements.length); + for (int i = 0; i < elements.length; i++) { + IConfigurationElement element = elements[i]; + if (HOVER_TAG.equals(element.getName())) { + JavaEditorTextHoverDescriptor desc = new JavaEditorTextHoverDescriptor( + element); + result.add(desc); + } + } + Collections.sort(result); + return (JavaEditorTextHoverDescriptor[]) result + .toArray(new JavaEditorTextHoverDescriptor[result.size()]); + } + + private static void initializeFromPreferences( + JavaEditorTextHoverDescriptor[] hovers) { + String compiledTextHoverModifiers = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getString( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS); + + StringTokenizer tokenizer = new StringTokenizer( + compiledTextHoverModifiers, VALUE_SEPARATOR); + HashMap idToModifier = new HashMap(tokenizer.countTokens() / 2); + + while (tokenizer.hasMoreTokens()) { + String id = tokenizer.nextToken(); + if (tokenizer.hasMoreTokens()) + idToModifier.put(id, tokenizer.nextToken()); + } + + String compiledTextHoverModifierMasks = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getString( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS); + + tokenizer = new StringTokenizer(compiledTextHoverModifierMasks, + VALUE_SEPARATOR); + HashMap idToModifierMask = new HashMap(tokenizer.countTokens() / 2); + + while (tokenizer.hasMoreTokens()) { + String id = tokenizer.nextToken(); + if (tokenizer.hasMoreTokens()) + idToModifierMask.put(id, tokenizer.nextToken()); + } + + for (int i = 0; i < hovers.length; i++) { + String modifierString = (String) idToModifier + .get(hovers[i].getId()); + boolean enabled = true; + if (modifierString == null) + modifierString = DISABLED_TAG; + + if (modifierString.startsWith(DISABLED_TAG)) { + enabled = false; + modifierString = modifierString.substring(1); + } + + if (modifierString.equals(NO_MODIFIER)) + modifierString = ""; //$NON-NLS-1$ + + hovers[i].fModifierString = modifierString; + hovers[i].fIsEnabled = enabled; + hovers[i].fStateMask = computeStateMask(modifierString); + if (hovers[i].fStateMask == -1) { + // Fallback: use stored modifier masks + try { + hovers[i].fStateMask = Integer + .parseInt((String) idToModifierMask.get(hovers[i] + .getId())); + } catch (NumberFormatException ex) { + hovers[i].fStateMask = -1; + } + // Fix modifier string + int stateMask = hovers[i].fStateMask; + if (stateMask == -1) + hovers[i].fModifierString = ""; //$NON-NLS-1$ + else + hovers[i].fModifierString = EditorUtility + .getModifierString(stateMask); + } + } + } + + /** + * Returns the configured modifier getStateMask for this hover. + * + * @return the hover modifier stateMask or -1 if no hover is configured + */ + public int getStateMask() { + return fStateMask; + } + + /** + * Returns the modifier String as set in the preference store. + * + * @return the modifier string + */ + public String getModifierString() { + return fModifierString; + } + + /** + * Returns whether this hover is enabled or not. + * + * @return true if enabled + */ + public boolean isEnabled() { + return fIsEnabled; + } + + /** + * Returns this hover descriptors configuration element. + * + * @return the configuration element + * @since 3.0 + */ + public IConfigurationElement getConfigurationElement() { + return fElement; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java new file mode 100644 index 0000000..9e0aad6 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaExpandHover.java @@ -0,0 +1,224 @@ +/******************************************************************************* + * Copyright (c) 2000, 2006 IBM Corporation and others. + * 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 + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.text.java.hover.AnnotationExpansionControl.AnnotationHoverInput; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.IJavaAnnotation; +import net.sourceforge.phpeclipse.phpeditor.JavaMarkerAnnotation; +import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider.ProblemAnnotation; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IInformationControlExtension2; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.CompositeRuler; +import org.eclipse.jface.text.source.IAnnotationAccess; +import org.eclipse.jface.text.source.IAnnotationAccessExtension; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IAnnotationPresentation; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.ImageUtilities; +import org.eclipse.jface.viewers.IDoubleClickListener; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; + +/** + * + * + * @since 3.0 + */ +public class JavaExpandHover extends AnnotationExpandHover { + + /** Id of the no breakpoint fake annotation */ + public static final String NO_BREAKPOINT_ANNOTATION = "net.sourceforge.phpdt.internal.ui.NoBreakpointAnnotation"; //$NON-NLS-1$ + + private static class NoBreakpointAnnotation extends Annotation implements + IAnnotationPresentation { + + public NoBreakpointAnnotation() { + super(NO_BREAKPOINT_ANNOTATION, false, JavaHoverMessages + .getString("NoBreakpointAnnotation.addBreakpoint")); + } + + /* + * @see org.eclipse.jface.text.source.IAnnotationPresentation#paint(org.eclipse.swt.graphics.GC, + * org.eclipse.swt.widgets.Canvas, + * org.eclipse.swt.graphics.Rectangle) + */ + public void paint(GC gc, Canvas canvas, Rectangle bounds) { + // draw affordance so the user know she can click here to get a + // breakpoint + Image fImage = PHPUiImages.get(PHPUiImages.IMG_FIELD_PUBLIC); + ImageUtilities.drawImage(fImage, gc, canvas, bounds, SWT.CENTER); + } + + /* + * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() + */ + public int getLayer() { + return IAnnotationPresentation.DEFAULT_LAYER; + } + } + + private AnnotationPreferenceLookup fLookup = new AnnotationPreferenceLookup(); + + private IPreferenceStore fStore = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + + public JavaExpandHover(CompositeRuler ruler, IAnnotationAccess access, + IDoubleClickListener doubleClickListener) { + super(ruler, access, doubleClickListener); + } + + /* + * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getHoverInfoForLine(org.eclipse.jface.text.source.ISourceViewer, + * int) + */ + protected Object getHoverInfoForLine(final ISourceViewer viewer, + final int line) { + final boolean showTemporaryProblems = PreferenceConstants + .getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_CORRECTION_INDICATION); + IAnnotationModel model = viewer.getAnnotationModel(); + IDocument document = viewer.getDocument(); + + if (model == null) + return null; + + List exact = new ArrayList(); + HashMap messagesAtPosition = new HashMap(); + + Iterator e = model.getAnnotationIterator(); + while (e.hasNext()) { + Annotation annotation = (Annotation) e.next(); + + if (fAnnotationAccess instanceof IAnnotationAccessExtension) + if (!((IAnnotationAccessExtension) fAnnotationAccess) + .isPaintable(annotation)) + continue; + + if (annotation instanceof IJavaAnnotation + && !isIncluded((IJavaAnnotation) annotation, + showTemporaryProblems)) + continue; + + AnnotationPreference pref = fLookup + .getAnnotationPreference(annotation); + if (pref != null) { + String key = pref.getVerticalRulerPreferenceKey(); + if (key != null && !fStore.getBoolean(key)) + continue; + } + + Position position = model.getPosition(annotation); + if (position == null) + continue; + + if (compareRulerLine(position, document, line) == 1) { + + if (isDuplicateMessage(messagesAtPosition, position, annotation + .getText())) + continue; + + exact.add(annotation); + } + } + + sort(exact, model); + + if (exact.size() > 0) + setLastRulerMouseLocation(viewer, line); + + if (exact.size() > 0) { + Annotation first = (Annotation) exact.get(0); + if (!isBreakpointAnnotation(first)) + exact.add(0, new NoBreakpointAnnotation()); + } + + if (exact.size() <= 1) + return null; + + AnnotationHoverInput input = new AnnotationHoverInput(); + input.fAnnotations = (Annotation[]) exact.toArray(new Annotation[0]); + input.fViewer = viewer; + input.fRulerInfo = fCompositeRuler; + input.fAnnotationListener = fgListener; + input.fDoubleClickListener = fDblClickListener; + input.redoAction = new AnnotationExpansionControl.ICallback() { + + public void run(IInformationControlExtension2 control) { + control.setInput(getHoverInfoForLine(viewer, line)); + } + + }; + input.model = model; + + return input; + } + + private boolean isIncluded(IJavaAnnotation annotation, + boolean showTemporaryProblems) { + + // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138601 + if (annotation instanceof ProblemAnnotation + && JavaMarkerAnnotation.TASK_ANNOTATION_TYPE.equals(annotation + .getType())) + return false; + + if (!annotation.isProblem()) + return true; + + if (annotation.isMarkedDeleted() && !annotation.hasOverlay()) + return true; + + if (annotation.hasOverlay() && !annotation.isMarkedDeleted()) + return true; + + if (annotation.hasOverlay()) + return (!isIncluded(annotation.getOverlay(), showTemporaryProblems)); + + return showTemporaryProblems; // && + // JavaCorrectionProcessor.hasCorrections((Annotation)annotation); + } + + /* + * @see org.eclipse.ui.internal.texteditor.AnnotationExpandHover#getOrder(org.eclipse.jface.text.source.Annotation) + */ + protected int getOrder(Annotation annotation) { + if (isBreakpointAnnotation(annotation)) + return 1000; + else + return super.getOrder(annotation); + } + + private boolean isBreakpointAnnotation(Annotation a) { + if (a instanceof JavaMarkerAnnotation) { + JavaMarkerAnnotation jma = (JavaMarkerAnnotation) a; + // HACK to get breakpoints to show up first + return jma.getType().equals("org.eclipse.debug.core.breakpoint"); //$NON-NLS-1$ + } + return false; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaInformationProvider.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java new file mode 100644 index 0000000..f59d8ce --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java @@ -0,0 +1,116 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import java.io.IOException; + +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.ui.text.HTMLPrinter; +import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; + +/** + * Provides source as hover info for Java elements. + */ +public class JavaSourceHover extends AbstractJavaEditorTextHover { + + private final int LABEL_FLAGS = JavaElementLabels.ALL_FULLY_QUALIFIED + | JavaElementLabels.M_PRE_RETURNTYPE + | JavaElementLabels.M_PARAMETER_TYPES + | JavaElementLabels.M_PARAMETER_NAMES + | JavaElementLabels.M_EXCEPTIONS + | JavaElementLabels.F_PRE_TYPE_SIGNATURE; + + /* + * @see JavaElementHover + */ + protected String getHoverInfo(IJavaElement[] result) { + int nResults = result.length; + StringBuffer buffer = new StringBuffer(); + + if (nResults > 1) { + + for (int i = 0; i < result.length; i++) { + HTMLPrinter.startBulletList(buffer); + IJavaElement curr = result[i]; + if (curr instanceof IMember) + HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr)); + HTMLPrinter.endBulletList(buffer); + } + + } else { + + IJavaElement curr = result[0]; + if (curr instanceof IMember && curr instanceof ISourceReference) { + HTMLPrinter.addSmallHeader(buffer, + getInfoText(((IMember) curr))); + try { + String source = ((ISourceReference) curr).getSource(); + source = removeLeadingComments(source); + HTMLPrinter.addParagraph(buffer, "
"); //$NON-NLS-1$
+					HTMLPrinter.addParagraph(buffer, source);
+					HTMLPrinter.addParagraph(buffer, "
"); //$NON-NLS-1$ + } catch (JavaModelException ex) { + // only write small header + } + } + } + + if (buffer.length() > 0) { + HTMLPrinter.insertPageProlog(buffer, 0); + HTMLPrinter.addPageEpilog(buffer); + return buffer.toString(); + } + + return null; + } + + private String getInfoText(IMember member) { + return JavaElementLabels.getElementLabel(member, LABEL_FLAGS); + } + + private String removeLeadingComments(String source) { + PHPCodeReader reader = new PHPCodeReader(); + IDocument document = new Document(source); + int i; + try { + reader.configureForwardReader(document, 0, document.getLength(), + true, false); + int c = reader.read(); + while (c != -1 && (c == '\r' || c == '\n')) { + c = reader.read(); + } + i = reader.getOffset(); + reader.close(); + } catch (IOException ex) { + i = 0; + } finally { + try { + if (reader != null) + reader.close(); + } catch (IOException ex) { + PHPeclipsePlugin.log(ex); + } + } + + if (i < 0) + return source; + return source.substring(i); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaTypeHover.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/ProblemHover.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java new file mode 100644 index 0000000..31b529d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/SourceViewerInformationControl.java @@ -0,0 +1,446 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.java.hover; + +import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IInformationControl; +import org.eclipse.jface.text.IInformationControlExtension; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + * Source viewer based implementation of IInformationControl. + * Displays information in a source viewer. + * + * @since 3.0 + */ +public class SourceViewerInformationControl implements IInformationControl, + IInformationControlExtension, DisposeListener { + + /** Border thickness in pixels. */ + private static final int BORDER = 1; + + /** The control's shell */ + private Shell fShell; + + /** The control's text widget */ + private StyledText fText; + + /** The control's source viewer */ + private SourceViewer fViewer; + + /** + * The optional status field. + * + * @since 3.0 + */ + private Label fStatusField; + + /** + * The separator for the optional status field. + * + * @since 3.0 + */ + private Label fSeparator; + + /** + * The font of the optional status text label. + * + * @since 3.0 + */ + private Font fStatusTextFont; + + /** + * Creates a default information control with the given shell as parent. The + * given information presenter is used to process the information to be + * displayed. The given styles are applied to the created styled text + * widget. + * + * @param parent + * the parent shell + * @param shellStyle + * the additional styles for the shell + * @param style + * the additional styles for the styled text widget + */ + public SourceViewerInformationControl(Shell parent, int shellStyle, + int style) { + this(parent, shellStyle, style, null); + } + + /** + * Creates a default information control with the given shell as parent. The + * given information presenter is used to process the information to be + * displayed. The given styles are applied to the created styled text + * widget. + * + * @param parent + * the parent shell + * @param shellStyle + * the additional styles for the shell + * @param style + * the additional styles for the styled text widget + * @param statusFieldText + * the text to be used in the optional status field or + * null if the status field should be hidden + * @since 3.0 + */ + public SourceViewerInformationControl(Shell parent, int shellStyle, + int style, String statusFieldText) { + GridLayout layout; + GridData gd; + + fShell = new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); + Display display = fShell.getDisplay(); + fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); + + Composite composite = fShell; + layout = new GridLayout(1, false); + int border = ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; + layout.marginHeight = border; + layout.marginWidth = border; + composite.setLayout(layout); + gd = new GridData(GridData.FILL_HORIZONTAL); + composite.setLayoutData(gd); + + if (statusFieldText != null) { + composite = new Composite(composite, SWT.NONE); + layout = new GridLayout(1, false); + layout.marginHeight = 0; + layout.marginWidth = 0; + composite.setLayout(layout); + gd = new GridData(GridData.FILL_BOTH); + composite.setLayoutData(gd); + composite.setForeground(display + .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + composite.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } + + // Source viewer + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getCombinedPreferenceStore(); + fViewer = new JavaSourceViewer(composite, null, null, false, style, + store); + fViewer.configure(new PHPSourceViewerConfiguration(PHPeclipsePlugin + .getDefault().getJavaTextTools().getColorManager(), store, + null, null)); + fViewer.setEditable(false); + + fText = fViewer.getTextWidget(); + gd = new GridData(GridData.BEGINNING | GridData.FILL_BOTH); + fText.setLayoutData(gd); + fText.setForeground(parent.getDisplay().getSystemColor( + SWT.COLOR_INFO_FOREGROUND)); + fText.setBackground(parent.getDisplay().getSystemColor( + SWT.COLOR_INFO_BACKGROUND)); + + fText.addKeyListener(new KeyListener() { + + public void keyPressed(KeyEvent e) { + if (e.character == 0x1B) // ESC + fShell.dispose(); + } + + public void keyReleased(KeyEvent e) { + } + }); + + // Status field + if (statusFieldText != null) { + + // Horizontal separator line + fSeparator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL + | SWT.LINE_DOT); + fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + // Status field label + fStatusField = new Label(composite, SWT.RIGHT); + fStatusField.setText(statusFieldText); + Font font = fStatusField.getFont(); + FontData[] fontDatas = font.getFontData(); + for (int i = 0; i < fontDatas.length; i++) + fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); + fStatusTextFont = new Font(fStatusField.getDisplay(), fontDatas); + fStatusField.setFont(fStatusTextFont); + GridData gd2 = new GridData(GridData.FILL_VERTICAL + | GridData.FILL_HORIZONTAL + | GridData.HORIZONTAL_ALIGN_BEGINNING + | GridData.VERTICAL_ALIGN_BEGINNING); + fStatusField.setLayoutData(gd2); + + // Regarding the color see bug 41128 + fStatusField.setForeground(display + .getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); + + fStatusField.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } + + addDisposeListener(this); + } + + /** + * Creates a default information control with the given shell as parent. The + * given information presenter is used to process the information to be + * displayed. The given styles are applied to the created styled text + * widget. + * + * @param parent + * the parent shell + * @param style + * the additional styles for the styled text widget + */ + public SourceViewerInformationControl(Shell parent, int style) { + this(parent, SWT.NO_TRIM, style); + } + + /** + * Creates a default information control with the given shell as parent. The + * given information presenter is used to process the information to be + * displayed. The given styles are applied to the created styled text + * widget. + * + * @param parent + * the parent shell + * @param style + * the additional styles for the styled text widget + * @param statusFieldText + * the text to be used in the optional status field or + * null if the status field should be hidden + * @since 3.0 + */ + public SourceViewerInformationControl(Shell parent, int style, + String statusFieldText) { + this(parent, SWT.NO_TRIM, style, statusFieldText); + } + + /** + * Creates a default information control with the given shell as parent. No + * information presenter is used to process the information to be displayed. + * No additional styles are applied to the styled text widget. + * + * @param parent + * the parent shell + */ + public SourceViewerInformationControl(Shell parent) { + this(parent, SWT.NONE); + } + + /** + * Creates a default information control with the given shell as parent. No + * information presenter is used to process the information to be displayed. + * No additional styles are applied to the styled text widget. + * + * @param parent + * the parent shell + * @param statusFieldText + * the text to be used in the optional status field or + * null if the status field should be hidden + * @since 3.0 + */ +// public SourceViewerInformationControl(Shell parent, String statusFieldText) { +// this(parent, SWT.NONE, statusFieldText); +// } + + /* + * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object) + */ + public void setInput(Object input) { + if (input instanceof String) + setInformation((String) input); + else + setInformation(null); + } + + /* + * @see IInformationControl#setInformation(String) + */ + public void setInformation(String content) { + if (content == null) { + fViewer.setInput(null); + return; + } + + IDocument doc = new Document(content); + PHPeclipsePlugin.getDefault().getJavaTextTools() + .setupJavaDocumentPartitioner(doc); + + fViewer.setInput(doc); + } + + /* + * @see IInformationControl#setVisible(boolean) + */ + public void setVisible(boolean visible) { + fShell.setVisible(visible); + } + + /** + * {@inheritDoc} + * + * @since 3.0 + */ + public void widgetDisposed(DisposeEvent event) { + if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) + fStatusTextFont.dispose(); + + fStatusTextFont = null; + fShell = null; + fText = null; + } + + /** + * {@inheritDoc} + */ + public final void dispose() { + if (fShell != null && !fShell.isDisposed()) + fShell.dispose(); + else + widgetDisposed(null); + } + + /* + * @see IInformationControl#setSize(int, int) + */ + public void setSize(int width, int height) { + + if (fStatusField != null) { + GridData gd = (GridData) fViewer.getTextWidget().getLayoutData(); + Point statusSize = fStatusField.computeSize(SWT.DEFAULT, + SWT.DEFAULT, true); + Point separatorSize = fSeparator.computeSize(SWT.DEFAULT, + SWT.DEFAULT, true); + gd.heightHint = height - statusSize.y - separatorSize.y; + } + fShell.setSize(width, height); + + if (fStatusField != null) + fShell.pack(true); + } + + /* + * @see IInformationControl#setLocation(Point) + */ + public void setLocation(Point location) { + Rectangle trim = fShell.computeTrim(0, 0, 0, 0); + Point textLocation = fText.getLocation(); + location.x += trim.x - textLocation.x; + location.y += trim.y - textLocation.y; + fShell.setLocation(location); + } + + /* + * @see IInformationControl#setSizeConstraints(int, int) + */ + public void setSizeConstraints(int maxWidth, int maxHeight) { + maxWidth = maxHeight; + } + + /* + * @see IInformationControl#computeSizeHint() + */ + public Point computeSizeHint() { + return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); + } + + /* + * @see IInformationControl#addDisposeListener(DisposeListener) + */ + public void addDisposeListener(DisposeListener listener) { + fShell.addDisposeListener(listener); + } + + /* + * @see IInformationControl#removeDisposeListener(DisposeListener) + */ + public void removeDisposeListener(DisposeListener listener) { + fShell.removeDisposeListener(listener); + } + + /* + * @see IInformationControl#setForegroundColor(Color) + */ + public void setForegroundColor(Color foreground) { + fText.setForeground(foreground); + } + + /* + * @see IInformationControl#setBackgroundColor(Color) + */ + public void setBackgroundColor(Color background) { + fText.setBackground(background); + } + + /* + * @see IInformationControl#isFocusControl() + */ + public boolean isFocusControl() { + return fText.isFocusControl(); + } + + /* + * @see IInformationControl#setFocus() + */ + public void setFocus() { + fShell.forceFocus(); + fText.setFocus(); + } + + /* + * @see IInformationControl#addFocusListener(FocusListener) + */ + public void addFocusListener(FocusListener listener) { + fText.addFocusListener(listener); + } + + /* + * @see IInformationControl#removeFocusListener(FocusListener) + */ + public void removeFocusListener(FocusListener listener) { + fText.removeFocusListener(listener); + } + + /* + * @see IInformationControlExtension#hasContents() + */ + public boolean hasContents() { + return fText.getCharCount() > 0; + } + + protected ISourceViewer getViewer() { + return fViewer; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ILinkedPositionListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionListener.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java new file mode 100644 index 0000000..6f1157d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionManager.java @@ -0,0 +1,831 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.link; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.BadPositionCategoryException; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.DocumentEvent; +import org.eclipse.jface.text.IAutoEditStrategy; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension; +import org.eclipse.jface.text.IDocumentListener; +import org.eclipse.jface.text.IPositionUpdater; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.TypedPosition; +//import org.eclipse.jface.text.contentassist.ICompletionProposal; + +/** + * This class manages linked positions in a document. Positions are linked by + * type names. If positions have the same type name, they are considered as + * linked. + * + * The manager remains active on a document until any of the following actions + * occurs: + * + *
    + *
  • A document change is performed which would invalidate any of the above + * constraints.
  • + * + *
  • The method uninstall() is called.
  • + * + *
  • Another instance of LinkedPositionManager tries to gain + * control of the same document. + *
+ */ +public class LinkedPositionManager implements IDocumentListener, + IPositionUpdater, IAutoEditStrategy { + + // This class still exists to properly handle code assist. + // This is due to the fact that it cannot be distinguished betweeen document + // changes which are + // issued by code assist and document changes which origin from another text + // viewer. + // There is a conflict in interest since in the latter case the linked mode + // should be left, but in the former case + // the linked mode should remain. + // To support content assist, document changes have to be propagated to + // connected positions + // by registering replace commands using IDocumentExtension. + // if it wasn't for the support of content assist, the documentChanged() + // method could be reduced to + // a simple call to leave(true) + private class Replace implements IDocumentExtension.IReplace { + + private Position fReplacePosition; + + private int fReplaceDeltaOffset; + + private int fReplaceLength; + + private String fReplaceText; + + public Replace(Position position, int deltaOffset, int length, + String text) { + fReplacePosition = position; + fReplaceDeltaOffset = deltaOffset; + fReplaceLength = length; + fReplaceText = text; + } + + public void perform(IDocument document, IDocumentListener owner) { + document.removeDocumentListener(owner); + try { + document.replace(fReplacePosition.getOffset() + + fReplaceDeltaOffset, fReplaceLength, fReplaceText); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + // TBD + } + document.addDocumentListener(owner); + } + } + + private static class PositionComparator implements Comparator { + /* + * @see Comparator#compare(Object, Object) + */ + public int compare(Object object0, Object object1) { + Position position0 = (Position) object0; + Position position1 = (Position) object1; + + return position0.getOffset() - position1.getOffset(); + } + } + + private static final String LINKED_POSITION_PREFIX = "LinkedPositionManager.linked.position"; //$NON-NLS-1$ + + private static final Comparator fgPositionComparator = new PositionComparator(); + + private static final Map fgActiveManagers = new HashMap(); + + private static int fgCounter = 0; + + private IDocument fDocument; + + private ILinkedPositionListener fListener; + + private String fPositionCategoryName; + + private boolean fMustLeave; + + /** + * Flag that records the state of this manager. As there are many different + * entities that may call leave or exit, these cannot always be sure whether + * the linked position infrastructure is still active. This is especially + * true for multithreaded situations. + */ + private boolean fIsActive = false; + + /** + * Creates a LinkedPositionManager for a + * IDocument. + * + * @param document + * the document to use with linked positions. + * @param canCoexist + * true if this manager can coexist with an + * already existing one + */ + public LinkedPositionManager(IDocument document, boolean canCoexist) { + Assert.isNotNull(document); + fDocument = document; + fPositionCategoryName = LINKED_POSITION_PREFIX + (fgCounter++); + install(canCoexist); + } + + /** + * Creates a LinkedPositionManager for a + * IDocument. + * + * @param document + * the document to use with linked positions. + */ + public LinkedPositionManager(IDocument document) { + this(document, false); + } + + /** + * Sets a listener to notify changes of current linked position. + */ + public void setLinkedPositionListener(ILinkedPositionListener listener) { + fListener = listener; + } + + /** + * Adds a linked position to the manager with the type being the content of + * the document at the specified range. There are the following constraints + * for linked positions: + * + *
    + *
  • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
  • + * + *
  • The string at any position must not contain line delimiters.
  • + *
+ * + * @param offset + * the offset of the position. + * @param length + * the length of the position. + */ + public void addPosition(int offset, int length) throws BadLocationException { + String type = fDocument.get(offset, length); + addPosition(offset, length, type); + } + + /** + * Adds a linked position of the specified position type to the manager. + * There are the following constraints for linked positions: + * + *
    + *
  • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
  • + * + *
  • The string at any position must not contain line delimiters.
  • + *
+ * + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param type + * the position type name - any positions with the same type are + * linked. + */ + public void addPosition(int offset, int length, String type) + throws BadLocationException { + Position[] positions = getPositions(fDocument); + + if (positions != null) { + for (int i = 0; i < positions.length; i++) + if (collides(positions[i], offset, length)) + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ + } + + String content = fDocument.get(offset, length); + + if (containsLineDelimiters(content)) + throw new BadLocationException( + LinkedPositionMessages + .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ + + try { + fDocument.addPosition(fPositionCategoryName, new TypedPosition( + offset, length, type)); + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + } + } + + /** + * Adds a linked position to the manager. The current document content at + * the specified range is taken as the position type. + *

+ * There are the following constraints for linked positions: + * + *

    + *
  • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
  • + * + *
  • The string at any position must not contain line delimiters.
  • + *
+ * + * It is usually best to set the first item in + * additionalChoices to be equal with the text inserted at + * the current position. + *

+ * + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param additionalChoices + * a number of additional choices to be displayed when selecting + * a position of this type. + */ +// public void addPosition(int offset, int length, +// ICompletionProposal[] additionalChoices) +// throws BadLocationException { +// String type = fDocument.get(offset, length); +// addPosition(offset, length, type, additionalChoices); +// } + + /** + * Adds a linked position of the specified position type to the manager. + * There are the following constraints for linked positions: + * + *
    + *
  • Any two positions have spacing of at least one character. This + * implies that two positions must not overlap.
  • + * + *
  • The string at any position must not contain line delimiters.
  • + *
+ * + * It is usually best to set the first item in + * additionalChoices to be equal with the text inserted at + * the current position. + * + * @param offset + * the offset of the position. + * @param length + * the length of the position. + * @param type + * the position type name - any positions with the same type are + * linked. + * @param additionalChoices + * a number of additional choices to be displayed when selecting + * a position of this type. + */ +// public void addPosition(int offset, int length, String type, +// ICompletionProposal[] additionalChoices) +// throws BadLocationException { +// Position[] positions = getPositions(fDocument); +// +// if (positions != null) { +// for (int i = 0; i < positions.length; i++) +// if (collides(positions[i], offset, length)) +// throw new BadLocationException( +// LinkedPositionMessages +// .getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ +// } +// +// String content = fDocument.get(offset, length); +// +// if (containsLineDelimiters(content)) +// throw new BadLocationException( +// LinkedPositionMessages +// .getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ +// +// try { +// fDocument.addPosition(fPositionCategoryName, new ProposalPosition( +// offset, length, type, additionalChoices)); +// } catch (BadPositionCategoryException e) { +// PHPeclipsePlugin.log(e); +// Assert.isTrue(false); +// } +// } + + /** + * Tests if a manager is already active for a document. + */ +// public static boolean hasActiveManager(IDocument document) { +// return fgActiveManagers.get(document) != null; +// } + + private void install(boolean canCoexist) { + + if (fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // is already active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + else { + fIsActive = true; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionManager activated: + // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ + } + + if (!canCoexist) { + LinkedPositionManager manager = (LinkedPositionManager) fgActiveManagers + .get(fDocument); + if (manager != null) + manager.leave(true); + } + + fgActiveManagers.put(fDocument, this); + fDocument.addPositionCategory(fPositionCategoryName); + fDocument.addPositionUpdater(this); + fDocument.addDocumentListener(this); + + fMustLeave = false; + } + + /** + * Leaves the linked mode. If unsuccessful, the linked positions are + * restored to the values at the time they were added. + */ + public void uninstall(boolean success) { + + if (!fIsActive) + // we migth also just return + ;// JavaPlugin(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // activated: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + else { + fDocument.removeDocumentListener(this); + + try { + Position[] positions = getPositions(fDocument); + if ((!success) && (positions != null)) { + // restore + for (int i = 0; i != positions.length; i++) { + TypedPosition position = (TypedPosition) positions[i]; + fDocument.replace(position.getOffset(), position + .getLength(), position.getType()); + } + } + + fDocument.removePositionCategory(fPositionCategoryName); + + fIsActive = false; + // JavaPlugin.log(new Status(IStatus.INFO, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // deactivated: "+fPositionCategoryName, new Exception())); + // //$NON-NLS-1$ + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + + } finally { + fDocument.removePositionUpdater(this); + fgActiveManagers.remove(fDocument); + } + } + + } + + /** + * Returns the position at the given offset, null if there is + * no position. + * + * @since 2.1 + */ + public Position getPosition(int offset) { + Position[] positions = getPositions(fDocument); + if (positions == null) + return null; + + for (int i = positions.length - 1; i >= 0; i--) { + Position position = positions[i]; + if (offset >= position.getOffset() + && offset <= position.getOffset() + position.getLength()) + return positions[i]; + } + + return null; + } + + /** + * Returns the first linked position. + * + * @return returns null if no linked position exist. + */ + public Position getFirstPosition() { + return getNextPosition(-1); + } + + public Position getLastPosition() { + Position[] positions = getPositions(fDocument); + for (int i = positions.length - 1; i >= 0; i--) { + String type = ((TypedPosition) positions[i]).getType(); + int j; + for (j = 0; j != i; j++) + if (((TypedPosition) positions[j]).getType().equals(type)) + break; + + if (j == i) + return positions[i]; + } + + return null; + } + + /** + * Returns the next linked position with an offset greater than + * offset. If another position with the same type and offset + * lower than offset exists, the position is skipped. + * + * @return returns null if no linked position exist. + */ + public Position getNextPosition(int offset) { + Position[] positions = getPositions(fDocument); + return findNextPosition(positions, offset); + } + + private static Position findNextPosition(Position[] positions, int offset) { + // skip already visited types + for (int i = 0; i != positions.length; i++) { + if (positions[i].getOffset() > offset) { + String type = ((TypedPosition) positions[i]).getType(); + int j; + for (j = 0; j != i; j++) + if (((TypedPosition) positions[j]).getType().equals(type)) + break; + + if (j == i) + return positions[i]; + } + } + + return null; + } + + /** + * Returns the position with the greatest offset smaller than + * offset. + * + * @return returns null if no linked position exist. + */ + public Position getPreviousPosition(int offset) { + Position[] positions = getPositions(fDocument); + if (positions == null) + return null; + + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, offset); + String currentType = currentPosition == null ? null : currentPosition + .getType(); + + Position lastPosition = null; + Position position = getFirstPosition(); + + while (position != null && position.getOffset() < offset) { + if (!((TypedPosition) position).getType().equals(currentType)) + lastPosition = position; + position = findNextPosition(positions, position.getOffset()); + } + + return lastPosition; + } + + private Position[] getPositions(IDocument document) { + + if (!fIsActive) + // we migth also just return an empty array + ;// JavaPlugin(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionManager + // is not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + + try { + Position[] positions = document.getPositions(fPositionCategoryName); + Arrays.sort(positions, fgPositionComparator); + return positions; + + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + } + + return null; + } + + public static boolean includes(Position position, int offset, int length) { + return (offset >= position.getOffset()) + && (offset + length <= position.getOffset() + + position.getLength()); + } + +// public static boolean excludes(Position position, int offset, int length) { +// return (offset + length <= position.getOffset()) +// || (position.getOffset() + position.getLength() <= offset); +// } + + /* + * Collides if spacing if positions intersect each other or are adjacent. + */ + private static boolean collides(Position position, int offset, int length) { + return (offset <= position.getOffset() + position.getLength()) + && (position.getOffset() <= offset + length); + } + + private void leave(boolean success) { + try { + uninstall(success); + + if (fListener != null) + fListener.exit((success ? LinkedPositionUI.COMMIT : 0) + | LinkedPositionUI.UPDATE_CARET); + } finally { + fMustLeave = false; + } + } + + private void abort() { + uninstall(true); // don't revert anything + + if (fListener != null) + fListener.exit(LinkedPositionUI.COMMIT); // don't let the UI + // restore anything + + // don't set fMustLeave, as we will get re-registered by a document + // event + } + + /* + * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + + if (fMustLeave) { + event.getDocument().removeDocumentListener(this); + return; + } + + IDocument document = event.getDocument(); + + Position[] positions = getPositions(document); + Position position = findCurrentPosition(positions, event.getOffset()); + + // modification outside editable position + if (position == null) { + // check for destruction of constraints (spacing of at least 1) + if ((event.getText() == null || event.getText().length() == 0) + && (findCurrentPosition(positions, event.getOffset()) != null) + && // will never become true, see condition above + (findCurrentPosition(positions, event.getOffset() + + event.getLength()) != null)) { + leave(true); + } + + // modification intersects editable position + } else { + // modificaction inside editable position + if (includes(position, event.getOffset(), event.getLength())) { + if (containsLineDelimiters(event.getText())) + leave(true); + + // modificaction exceeds editable position + } else { + leave(true); + } + } + } + + /* + * @see IDocumentListener#documentChanged(DocumentEvent) + */ + public void documentChanged(DocumentEvent event) { + + // have to handle code assist, so can't just leave the linked mode + // leave(true); + + IDocument document = event.getDocument(); + + Position[] positions = getPositions(document); + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, event.getOffset()); + + // ignore document changes (assume it won't invalidate constraints) + if (currentPosition == null) + return; + + int deltaOffset = event.getOffset() - currentPosition.getOffset(); + + if (fListener != null) { + int length = event.getText() == null ? 0 : event.getText().length(); + fListener.setCurrentPosition(currentPosition, deltaOffset + length); + } + + for (int i = 0; i != positions.length; i++) { + TypedPosition p = (TypedPosition) positions[i]; + + if (p.getType().equals(currentPosition.getType()) + && !p.equals(currentPosition)) { + Replace replace = new Replace(p, deltaOffset, + event.getLength(), event.getText()); + ((IDocumentExtension) document) + .registerPostNotificationReplace(this, replace); + } + } + } + + /* + * @see IPositionUpdater#update(DocumentEvent) + */ + public void update(DocumentEvent event) { + + int eventOffset = event.getOffset(); + int eventOldLength = event.getLength(); + int eventNewLength = event.getText() == null ? 0 : event.getText() + .length(); + int deltaLength = eventNewLength - eventOldLength; + + Position[] positions = getPositions(event.getDocument()); + + for (int i = 0; i != positions.length; i++) { + + Position position = positions[i]; + + if (position.isDeleted()) + continue; + + int offset = position.getOffset(); + int length = position.getLength(); + int end = offset + length; + + if (offset > eventOffset + eventOldLength) // position comes way + // after change - shift + position.setOffset(offset + deltaLength); + else if (end < eventOffset) // position comes way before change - + // leave alone + ; + else if (offset <= eventOffset + && end >= eventOffset + eventOldLength) { + // event completely internal to the position - adjust length + position.setLength(length + deltaLength); + } else if (offset < eventOffset) { + // event extends over end of position - adjust length + int newEnd = eventOffset + eventNewLength; + position.setLength(newEnd - offset); + } else if (end > eventOffset + eventOldLength) { + // event extends from before position into it - adjust offset + // and length + // offset becomes end of event, length ajusted acordingly + // we want to recycle the overlapping part + int newOffset = eventOffset + eventNewLength; + position.setOffset(newOffset); + position.setLength(length + deltaLength); + } else { + // event consumes the position - delete it + position.delete(); + // JavaPlugin.log(new Status(IStatus.INFO, + // JavaPlugin.getPluginId(), IStatus.OK, "linked position + // deleted -> must leave: "+fPositionCategoryName, null)); + // //$NON-NLS-1$ + fMustLeave = true; + } + } + + if (fMustLeave) + abort(); + } + + private static Position findCurrentPosition(Position[] positions, int offset) { + for (int i = 0; i != positions.length; i++) + if (includes(positions[i], offset, 0)) + return positions[i]; + + return null; + } + + private boolean containsLineDelimiters(String string) { + + if (string == null) + return false; + + String[] delimiters = fDocument.getLegalLineDelimiters(); + + for (int i = 0; i != delimiters.length; i++) + if (string.indexOf(delimiters[i]) != -1) + return true; + + return false; + } + + /** + * Test if ok to modify through UI. + */ + public boolean anyPositionIncludes(int offset, int length) { + Position[] positions = getPositions(fDocument); + + Position position = findCurrentPosition(positions, offset); + if (position == null) + return false; + + return includes(position, offset, length); + } + + /** + * Returns the position that includes the given range. + * + * @param offset + * @param length + * @return position that includes the given range + */ + public Position getEmbracingPosition(int offset, int length) { + Position[] positions = getPositions(fDocument); + + Position position = findCurrentPosition(positions, offset); + if (position != null && includes(position, offset, length)) + return position; + + return null; + } + + /* + * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.DocumentCommand) + */ + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + + if (fMustLeave) { + leave(true); + return; + } + + // don't interfere with preceding auto edit strategies + if (command.getCommandCount() != 1) { + leave(true); + return; + } + + Position[] positions = getPositions(document); + TypedPosition currentPosition = (TypedPosition) findCurrentPosition( + positions, command.offset); + + // handle edits outside of a position + if (currentPosition == null) { + leave(true); + return; + } + + if (!command.doit) + return; + + command.doit = false; + command.owner = this; + command.caretOffset = command.offset + command.length; + + int deltaOffset = command.offset - currentPosition.getOffset(); + + if (fListener != null) + fListener.setCurrentPosition(currentPosition, deltaOffset + + command.text.length()); + + for (int i = 0; i != positions.length; i++) { + TypedPosition position = (TypedPosition) positions[i]; + + try { + if (position.getType().equals(currentPosition.getType()) + && !position.equals(currentPosition)) + command.addCommand(position.getOffset() + deltaOffset, + command.length, command.text, this); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + } + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java new file mode 100644 index 0000000..dd4d986 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/LinkedPositionUI.java @@ -0,0 +1,973 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.link; + +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.BadPositionCategoryException; +import org.eclipse.jface.text.DefaultPositionUpdater; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IPositionUpdater; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.IRewriteTarget; +import org.eclipse.jface.text.ITextInputListener; +import org.eclipse.jface.text.ITextListener; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.ITextViewerExtension; +import org.eclipse.jface.text.ITextViewerExtension2; +import org.eclipse.jface.text.ITextViewerExtension5; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextEvent; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.custom.VerifyKeyListener; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.events.ShellEvent; +import org.eclipse.swt.events.ShellListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +/** + * A user interface for LinkedPositionManager, using + * ITextViewer. + */ +public class LinkedPositionUI implements ILinkedPositionListener, + ITextInputListener, ITextListener, ModifyListener, VerifyListener, + VerifyKeyListener, PaintListener, IPropertyChangeListener, + ShellListener { + + /** + * A listener for notification when the user cancelled the edit operation. + */ + public interface ExitListener { + void exit(boolean accept); + } + + public static class ExitFlags { + public int flags; + + public boolean doit; + + public ExitFlags(int flags, boolean doit) { + this.flags = flags; + this.doit = doit; + } + } + + public interface ExitPolicy { + ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, + int offset, int length); + } + + // leave flags + private static final int UNINSTALL = 1; // uninstall linked position manager + + public static final int COMMIT = 2; // commit changes + + private static final int DOCUMENT_CHANGED = 4; // document has changed + + public static final int UPDATE_CARET = 8; // update caret + + private static final IPreferenceStore fgStore = PHPeclipsePlugin + .getDefault().getPreferenceStore(); + + private static final String CARET_POSITION_PREFIX = "LinkedPositionUI.caret.position"; //$NON-NLS-1$ + + private static int fgCounter = 0; + + private final ITextViewer fViewer; + + private final LinkedPositionManager fManager; + + private final IPositionUpdater fUpdater; + + private final String fPositionCategoryName; + + private Color fFrameColor; + + private int fFinalCaretOffset = -1; // no final caret offset + + private Position fFinalCaretPosition; + + private Position fFramePosition; + + private int fInitialOffset = -1; + + private int fCaretOffset; + + private ExitPolicy fExitPolicy; + + private ExitListener fExitListener; + + private boolean fNeedRedraw; + + private String fContentType; + + private Position fPreviousPosition; + + // private ContentAssistant2 fAssistant; + + /** + * Flag that records the state of this ui object. As there are many + * different entities that may call leave or exit, these cannot always be + * sure whether the linked position infrastructure is still active. This is + * especially true for multithreaded situations. + */ + private boolean fIsActive = false; + + /** + * Creates a user interface for LinkedPositionManager. + * + * @param viewer + * the text viewer. + * @param manager + * the LinkedPositionManager managing a + * IDocument of the ITextViewer. + */ + public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) { + Assert.isNotNull(viewer); + Assert.isNotNull(manager); + + fViewer = viewer; + fManager = manager; + + fPositionCategoryName = CARET_POSITION_PREFIX + (fgCounter++); + fUpdater = new DefaultPositionUpdater(fPositionCategoryName); + + fManager.setLinkedPositionListener(this); + + initializeHighlightColor(viewer); + } + + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty().equals( + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) { + initializeHighlightColor(fViewer); + redrawRegion(); + } + } + + private void initializeHighlightColor(ITextViewer viewer) { + + if (fFrameColor != null) + fFrameColor.dispose(); + + StyledText text = viewer.getTextWidget(); + if (text != null) { + Display display = text.getDisplay(); + fFrameColor = createColor(fgStore, + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, display); + } + } + + /** + * Creates a color from the information stored in the given preference + * store. Returns null if there is no such information + * available. + */ + private Color createColor(IPreferenceStore store, String key, + Display display) { + + RGB rgb = null; + + if (store.contains(key)) { + + if (store.isDefault(key)) + rgb = PreferenceConverter.getDefaultColor(store, key); + else + rgb = PreferenceConverter.getColor(store, key); + + if (rgb != null) + return new Color(display, rgb); + } + + return null; + } + + /** + * Sets the initial offset. + * + * @param offset + */ +// public void setInitialOffset(int offset) { +// fInitialOffset = offset; +// } + + /** + * Sets the final position of the caret when the linked mode is exited + * successfully by leaving the last linked position using TAB. The set + * position will be a TAB stop as well as the positions configured in the + * LinkedPositionManager. + */ + public void setFinalCaretOffset(int offset) { + fFinalCaretOffset = offset; + } + + /** + * Sets a CancelListener which is notified if the linked mode + * is exited unsuccessfully by hitting ESC. + */ + public void setCancelListener(ExitListener listener) { + fExitListener = listener; + } + + /** + * Sets an ExitPolicy which decides when and how the linked + * mode is exited. + */ + public void setExitPolicy(ExitPolicy policy) { + fExitPolicy = policy; + } + + /* + * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, + * int) + */ + public void setCurrentPosition(Position position, int caretOffset) { + if (!fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + + if (!fFramePosition.equals(position)) { + fNeedRedraw = true; + fFramePosition = position; + } + + fCaretOffset = caretOffset; + } + + /** + * Enters the linked mode. The linked mode can be left by calling + * exit. + * + * @see #exit(boolean) + */ + public void enter() { + if (fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // already active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + else { + fIsActive = true; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionUI activated: "+fPositionCategoryName, + // new Exception())); //$NON-NLS-1$ + } + + // track final caret + IDocument document = fViewer.getDocument(); + document.addPositionCategory(fPositionCategoryName); + document.addPositionUpdater(fUpdater); + + try { + if (fFinalCaretOffset != -1) { + fFinalCaretPosition = new Position(fFinalCaretOffset); + document + .addPosition(fPositionCategoryName, fFinalCaretPosition); + } + } catch (BadLocationException e) { + handleException(fViewer.getTextWidget().getShell(), e); + + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + } + + fViewer.addTextInputListener(this); + fViewer.addTextListener(this); + + ITextViewerExtension extension = (ITextViewerExtension) fViewer; + extension.prependVerifyKeyListener(this); + + StyledText text = fViewer.getTextWidget(); + text.addVerifyListener(this); + text.addModifyListener(this); + text.addPaintListener(this); + text.showSelection(); + + Shell shell = text.getShell(); + shell.addShellListener(this); + + fFramePosition = (fInitialOffset == -1) ? fManager.getFirstPosition() + : fManager.getPosition(fInitialOffset); + if (fFramePosition == null) { + leave(UNINSTALL | COMMIT | UPDATE_CARET); + return; + } + + fgStore.addPropertyChangeListener(this); + + // try { + // fContentType= TextUtilities.getContentType(document, + // IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset); + // if (fViewer instanceof ITextViewerExtension2) { + // ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, + // fContentType); + // } else { + // Assert.isTrue(false); + // } + // + // } catch (BadLocationException e) { + // handleException(fViewer.getTextWidget().getShell(), e); + // } + try { + fContentType = document.getContentType(fFramePosition.offset); + if (fViewer instanceof ITextViewerExtension2) { + ((ITextViewerExtension2) fViewer).prependAutoEditStrategy( + fManager, fContentType); + } else { + Assert.isTrue(false); + } + + } catch (BadLocationException e) { + handleException(fViewer.getTextWidget().getShell(), e); + } + selectRegion(); + // triggerContentAssist(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.link.ILinkedPositionListener#exit(boolean) + */ + public void exit(int flags) { + leave(flags); + } + + /** + * Returns the cursor selection, after having entered the linked mode. + * enter() must be called prior to a call to this method. + */ + public IRegion getSelectedRegion() { + if (!fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + + if (fFramePosition == null) + return new Region(fFinalCaretOffset, 0); + else + return new Region(fFramePosition.getOffset(), fFramePosition + .getLength()); + } + + private void leave(int flags) { + if (!fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + else { + fIsActive = false; + // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), + // IStatus.OK, "LinkedPositionUI deactivated: + // "+fPositionCategoryName, new Exception())); //$NON-NLS-1$ + } + + fInitialOffset = -1; + + if ((flags & UNINSTALL) != 0) + fManager.uninstall((flags & COMMIT) != 0); + + fgStore.removePropertyChangeListener(this); + + if (fFrameColor != null) { + fFrameColor.dispose(); + fFrameColor = null; + } + + StyledText text = fViewer.getTextWidget(); + // bail out if the styled text is null, meaning the viewer has been + // disposed (-> document is null as well) + // see pr https://bugs.eclipse.org/bugs/show_bug.cgi?id=46821 + if (text == null) + return; + + text.removePaintListener(this); + text.removeModifyListener(this); + text.removeVerifyListener(this); + + Shell shell = text.getShell(); + shell.removeShellListener(this); + + // if (fAssistant != null) { + // Display display= text.getDisplay(); + // if (display != null && !display.isDisposed()) { + // display.asyncExec(new Runnable() { + // public void run() { + // if (fAssistant != null) { + // fAssistant.uninstall(); + // fAssistant= null; + // } + // } + // }); + // } + // } + + ITextViewerExtension extension = (ITextViewerExtension) fViewer; + extension.removeVerifyKeyListener(this); + + IRewriteTarget target = extension.getRewriteTarget(); + target.endCompoundChange(); + + if (fViewer instanceof ITextViewerExtension2 && fContentType != null) + ((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, + fContentType); + fContentType = null; + + fViewer.removeTextListener(this); + fViewer.removeTextInputListener(this); + + try { + IDocument document = fViewer.getDocument(); + + if (((flags & COMMIT) != 0) && ((flags & DOCUMENT_CHANGED) == 0) + && ((flags & UPDATE_CARET) != 0)) { + Position[] positions = document + .getPositions(fPositionCategoryName); + if ((positions != null) && (positions.length != 0)) { + + if (fViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension3 = (ITextViewerExtension5) fViewer; + int widgetOffset = extension3 + .modelOffset2WidgetOffset(positions[0] + .getOffset()); + if (widgetOffset >= 0) + text.setSelection(widgetOffset, widgetOffset); + + } else { + IRegion region = fViewer.getVisibleRegion(); + int offset = positions[0].getOffset() + - region.getOffset(); + if ((offset >= 0) && (offset <= region.getLength())) + text.setSelection(offset, offset); + } + } + } + + document.removePositionUpdater(fUpdater); + document.removePositionCategory(fPositionCategoryName); + + if (fExitListener != null) + fExitListener.exit(((flags & COMMIT) != 0) + || ((flags & DOCUMENT_CHANGED) != 0)); + + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + Assert.isTrue(false); + } + + if ((flags & DOCUMENT_CHANGED) == 0) + text.redraw(); + } + + private void next() { + if (!fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + + redrawRegion(); + + if (fFramePosition == fFinalCaretPosition) + fFramePosition = fManager.getFirstPosition(); + else + fFramePosition = fManager.getNextPosition(fFramePosition + .getOffset()); + if (fFramePosition == null) { + if (fFinalCaretPosition != null) + fFramePosition = fFinalCaretPosition; + else + fFramePosition = fManager.getFirstPosition(); + } + if (fFramePosition == null) { + leave(UNINSTALL | COMMIT | UPDATE_CARET); + } else { + selectRegion(); + // triggerContentAssist(); + redrawRegion(); + } + } + + private void previous() { + if (!fIsActive) + ;// JavaPlugin.log(new Status(IStatus.WARNING, + // JavaPlugin.getPluginId(), IStatus.OK, "LinkedPositionUI is + // not active: "+fPositionCategoryName, new + // IllegalStateException())); //$NON-NLS-1$ + + redrawRegion(); + + fFramePosition = fManager.getPreviousPosition(fFramePosition + .getOffset()); + if (fFramePosition == null) { + if (fFinalCaretPosition != null) + fFramePosition = fFinalCaretPosition; + else + fFramePosition = fManager.getLastPosition(); + } + if (fFramePosition == null) { + leave(UNINSTALL | COMMIT | UPDATE_CARET); + } else { + selectRegion(); + // triggerContentAssist(); + redrawRegion(); + } + } + + /** Trigger content assist on choice positions */ + // private void triggerContentAssist() { + // if (fFramePosition instanceof ProposalPosition) { + // + // ProposalPosition pp= (ProposalPosition) fFramePosition; + // initializeContentAssistant(); + // if (fAssistant == null) + // return; + // fAssistant.setCompletions(pp.getChoices()); + // fAssistant.showPossibleCompletions(); + // } else { + // if (fAssistant != null) + // fAssistant.setCompletions(new ICompletionProposal[0]); + // } + // } + /** Lazy initialize content assistant for this linked ui */ + // private void initializeContentAssistant() { + // if (fAssistant != null) + // return; + // fAssistant= new ContentAssistant2(); + // fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); + // fAssistant.install(fViewer); + // } + /* + * @see VerifyKeyListener#verifyKey(VerifyEvent) + */ + public void verifyKey(VerifyEvent event) { + + if (!event.doit || !fIsActive) + return; + + Point selection = fViewer.getSelectedRange(); + int offset = selection.x; + int length = selection.y; + + ExitFlags exitFlags = fExitPolicy == null ? null : fExitPolicy.doExit( + fManager, event, offset, length); + if (exitFlags != null) { + leave(UNINSTALL | exitFlags.flags); + event.doit = exitFlags.doit; + return; + } + + switch (event.character) { + // [SHIFT-]TAB = hop between edit boxes + case 0x09: { + // if tab was treated as a document change, would it exceed variable + // range? + if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { + leave(UNINSTALL | COMMIT); + return; + } + } + + if (event.stateMask == SWT.SHIFT) + previous(); + else + next(); + + event.doit = false; + break; + + // ENTER + case 0x0A: // Ctrl+Enter + case 0x0D: { + // if (fAssistant != null && fAssistant.wasProposalChosen()) { + // next(); + // event.doit= false; + // break; + // } + + // if enter was treated as a document change, would it exceed + // variable range? + if (!LinkedPositionManager.includes(fFramePosition, offset, length) + || (fFramePosition == fFinalCaretPosition)) { + leave(UNINSTALL | COMMIT); + return; + } + } + + leave(UNINSTALL | COMMIT | UPDATE_CARET); + event.doit = false; + break; + + // ESC + case 0x1B: + leave(UNINSTALL | COMMIT); + event.doit = false; + break; + + case ';': + leave(UNINSTALL | COMMIT); + event.doit = true; + break; + + default: + if (event.character != 0) { + if (!controlUndoBehavior(offset, length) + || fFramePosition == fFinalCaretPosition) { + leave(UNINSTALL | COMMIT); + break; + } + } + } + } + + private boolean controlUndoBehavior(int offset, int length) { + + Position position = fManager.getEmbracingPosition(offset, length); + if (position != null) { + + ITextViewerExtension extension = (ITextViewerExtension) fViewer; + IRewriteTarget target = extension.getRewriteTarget(); + + if (fPreviousPosition != null + && !fPreviousPosition.equals(position)) + target.endCompoundChange(); + target.beginCompoundChange(); + } + + fPreviousPosition = position; + return fPreviousPosition != null; + } + + /* + * @see VerifyListener#verifyText(VerifyEvent) + */ + public void verifyText(VerifyEvent event) { + if (!event.doit) + return; + + int offset = 0; + int length = 0; + + if (fViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; + IRegion modelRange = extension.widgetRange2ModelRange(new Region( + event.start, event.end - event.start)); + if (modelRange == null) + return; + + offset = modelRange.getOffset(); + length = modelRange.getLength(); + + } else { + IRegion visibleRegion = fViewer.getVisibleRegion(); + offset = event.start + visibleRegion.getOffset(); + length = event.end - event.start; + } + + // allow changes only within linked positions when coming through UI + if (!fManager.anyPositionIncludes(offset, length)) + leave(UNINSTALL | COMMIT); + } + + /* + * @see PaintListener#paintControl(PaintEvent) + */ + public void paintControl(PaintEvent event) { + if (fFramePosition == null) + return; + + IRegion widgetRange = asWidgetRange(fFramePosition); + if (widgetRange == null) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; + } + + int offset = widgetRange.getOffset(); + int length = widgetRange.getLength(); + + StyledText text = fViewer.getTextWidget(); + + // support for bidi + Point minLocation = getMinimumLocation(text, offset, length); + Point maxLocation = getMaximumLocation(text, offset, length); + + int x1 = minLocation.x; + int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; + int y = minLocation.y + text.getLineHeight() - 1; + + GC gc = event.gc; + gc.setForeground(fFrameColor); + gc.drawLine(x1, y, x2, y); + } + + protected IRegion asWidgetRange(Position position) { + if (fViewer instanceof ITextViewerExtension5) { + + ITextViewerExtension5 extension = (ITextViewerExtension5) fViewer; + return extension.modelRange2WidgetRange(new Region(position + .getOffset(), position.getLength())); + + } else { + + IRegion region = fViewer.getVisibleRegion(); + if (includes(region, position)) + return new Region(position.getOffset() - region.getOffset(), + position.getLength()); + } + + return null; + } + + private static Point getMinimumLocation(StyledText text, int offset, + int length) { + Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); + + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); + + if (location.x < minLocation.x) + minLocation.x = location.x; + if (location.y < minLocation.y) + minLocation.y = location.y; + } + + return minLocation; + } + + private static Point getMaximumLocation(StyledText text, int offset, + int length) { + Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); + + if (location.x > maxLocation.x) + maxLocation.x = location.x; + if (location.y > maxLocation.y) + maxLocation.y = location.y; + } + + return maxLocation; + } + + private void redrawRegion() { + IRegion widgetRange = asWidgetRange(fFramePosition); + if (widgetRange == null) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; + } + + StyledText text = fViewer.getTextWidget(); + if (text != null && !text.isDisposed()) + text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), + true); + } + + private void selectRegion() { + + IRegion widgetRange = asWidgetRange(fFramePosition); + if (widgetRange == null) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; + } + + StyledText text = fViewer.getTextWidget(); + if (text != null && !text.isDisposed()) { + int start = widgetRange.getOffset(); + int end = widgetRange.getLength() + start; + text.setSelection(start, end); + } + } + + private void updateCaret() { + + IRegion widgetRange = asWidgetRange(fFramePosition); + if (widgetRange == null) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + return; + } + + int offset = widgetRange.getOffset() + fCaretOffset; + StyledText text = fViewer.getTextWidget(); + if (text != null && !text.isDisposed()) + text.setCaretOffset(offset); + } + + /* + * @see ModifyListener#modifyText(ModifyEvent) + */ + public void modifyText(ModifyEvent e) { + // reposition caret after StyledText + redrawRegion(); + updateCaret(); + } + + private static void handleException(Shell shell, Exception e) { + String title = LinkedPositionMessages + .getString("LinkedPositionUI.error.title"); //$NON-NLS-1$ + if (e instanceof CoreException) + ExceptionHandler.handle((CoreException) e, shell, title, null); + else if (e instanceof InvocationTargetException) + ExceptionHandler.handle((InvocationTargetException) e, shell, + title, null); + else { + MessageDialog.openError(shell, title, e.getMessage()); + PHPeclipsePlugin.log(e); + } + } + + /* + * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, + * IDocument) + */ + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { + // 5326: leave linked mode on document change + int flags = UNINSTALL | COMMIT + | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); + leave(flags); + } + + /* + * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) + */ + public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { + } + + private static boolean includes(IRegion region, Position position) { + return position.getOffset() >= region.getOffset() + && position.getOffset() + position.getLength() <= region + .getOffset() + + region.getLength(); + } + + /* + * @see org.eclipse.jface.text.ITextListener#textChanged(TextEvent) + */ + public void textChanged(TextEvent event) { + if (!fNeedRedraw) + return; + + redrawRegion(); + fNeedRedraw = false; + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellActivated(ShellEvent event) { + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellClosed(org.eclipse.swt.events.ShellEvent) + */ + public void shellClosed(ShellEvent event) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellDeactivated(ShellEvent event) { + // don't deactivate on focus lost, since the proposal popups may take + // focus + // plus: it doesn't hurt if you can check with another window without + // losing linked mode + // since there is no intrusive popup sticking out. + + // need to check first what happens on reentering based on an open + // action + // Seems to be no problem + + // TODO check whether we can leave it or uncomment it after debugging + // PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell + // deactivated does not mean + // it is not visible any longer. + // leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + + // Better: + // Check with content assistant and only leave if its not the proposal + // shell that took the + // focus away. + + StyledText text; + Display display; + + // if (fAssistant == null || fViewer == null || (text= + // fViewer.getTextWidget()) == null + // || (display= text.getDisplay()) == null || display.isDisposed()) { + if (fViewer == null || (text = fViewer.getTextWidget()) == null + || (display = text.getDisplay()) == null + || display.isDisposed()) { + leave(UNINSTALL | COMMIT); + } else { + // Post in UI thread since the assistant popup will only get the + // focus after we lose it. + display.asyncExec(new Runnable() { + public void run() { + // TODO add isDisposed / isUninstalled / hasLeft check? for + // now: check for content type, + // since it gets nullified in leave() + if (fIsActive) {// && (fAssistant == null || + // !fAssistant.hasFocus())) { + leave(UNINSTALL | COMMIT); + } + } + }); + } + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellDeiconified(org.eclipse.swt.events.ShellEvent) + */ + public void shellDeiconified(ShellEvent event) { + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellIconified(org.eclipse.swt.events.ShellEvent) + */ + public void shellIconified(ShellEvent event) { + leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/link/ProposalPosition.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IHtmlTagConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/IJavaDocTagConstants.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java new file mode 100644 index 0000000..34c8f21 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/JavaDocAutoIndentStrategy.java @@ -0,0 +1,937 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.phpdoc; + +import java.text.BreakIterator; + +//import net.sourceforge.phpdt.core.ICompilationUnit; +//import net.sourceforge.phpdt.core.IJavaElement; +//import net.sourceforge.phpdt.core.IMethod; +//import net.sourceforge.phpdt.core.ISourceRange; +//import net.sourceforge.phpdt.core.IType; +//import net.sourceforge.phpdt.internal.corext.util.Strings; +//import net.sourceforge.phpdt.ui.CodeGeneration; +//import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +//import org.eclipse.core.runtime.CoreException; +//import org.eclipse.core.runtime.Preferences; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchPage; +//import org.eclipse.ui.IWorkbenchWindow; +//import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +import org.eclipse.ui.texteditor.ITextEditorExtension3; + +/** + * Auto indent strategy for java doc comments + */ +public class JavaDocAutoIndentStrategy extends + DefaultIndentLineAutoEditStrategy { + + private String fPartitioning; + + /** + * Creates a new Javadoc auto indent strategy for the given document + * partitioning. + * + * @param partitioning + * the document partitioning + */ + public JavaDocAutoIndentStrategy(String partitioning) { + fPartitioning = partitioning; + } + + private static String getLineDelimiter(IDocument document) { + try { + if (document.getNumberOfLines() > 1) + return document.getLineDelimiter(0); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + + return System.getProperty("line.separator"); //$NON-NLS-1$ + } + + /** + * Copies the indentation of the previous line and add a star. If the + * javadoc just started on this line add standard method tags and close the + * javadoc. + * + * @param d + * the document to work on + * @param c + * the command to deal with + */ + private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) { + + if (c.offset == -1 || d.getLength() == 0) + return; + + try { + // find start of line + int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset); + IRegion info = d.getLineInformationOfOffset(p); + int start = info.getOffset(); + + // find white spaces + int end = findEndOfWhiteSpace(d, start, c.offset); + + StringBuffer buf = new StringBuffer(c.text); + if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness + // not work for class comments + // append to input + String indentation = jdocExtractLinePrefix(d, d + .getLineOfOffset(c.offset)); + buf.append(indentation); + if (end < c.offset) { + if (d.getChar(end) == '/') { + // javadoc started on this line + buf.append(" * "); //$NON-NLS-1$ + + if (PHPeclipsePlugin + .getDefault() + .getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_CLOSE_JAVADOCS) + && isNewComment(d, c.offset, fPartitioning)) { + String lineDelimiter = getLineDelimiter(d); + + String endTag = lineDelimiter + indentation + " */"; //$NON-NLS-1$ + d.replace(c.offset, 0, endTag); //$NON-NLS-1$ + // evaluate method signature + //ICompilationUnit unit = getCompilationUnit(); + + // if + // (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) + // && + // unit != null) + // { + // try { + // JavaModelUtil.reconcile(unit); + // String string= createJavaDocTags(d, c, + // indentation, lineDelimiter, unit); + // if (string != null) { + // d.replace(c.offset, 0, string); + // } + // } catch (CoreException e) { + // // ignore + // } + // } + } + + } + } + } + + c.text = buf.toString(); + + } catch (BadLocationException excp) { + // stop work + } + } + +// private String createJavaDocTags(IDocument document, +// DocumentCommand command, String indentation, String lineDelimiter, +// ICompilationUnit unit) throws CoreException, BadLocationException { +// IJavaElement element = unit.getElementAt(command.offset); +// if (element == null) +// return null; +// +// switch (element.getElementType()) { +// case IJavaElement.TYPE: +// return createTypeTags(document, command, indentation, +// lineDelimiter, (IType) element); +// +// case IJavaElement.METHOD: +// return createMethodTags(document, command, indentation, +// lineDelimiter, (IMethod) element); +// +// default: +// return null; +// } +// } + + /* + * Removes start and end of a comment and corrects indentation and line + * delimiters. + */ +// private String prepareTemplateComment(String comment, String indentation, +// String lineDelimiter) { +// // trim comment start and end if any +// if (comment.endsWith("*/")) //$NON-NLS-1$ +// comment = comment.substring(0, comment.length() - 2); +// comment = comment.trim(); +// if (comment.startsWith("/*")) { //$NON-NLS-1$ +// if (comment.length() > 2 && comment.charAt(2) == '*') { +// comment = comment.substring(3); // remove '/**' +// } else { +// comment = comment.substring(2); // remove '/*' +// } +// } +// // return Strings.changeIndent(comment, 0, +// // CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter); +// return Strings.changeIndent(comment, 0, getTabWidth(), indentation, +// lineDelimiter); +// } + +// public static int getTabWidth() { +// Preferences preferences = PHPeclipsePlugin.getDefault() +// .getPluginPreferences(); +// return preferences +// .getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); +// } + +// private String createTypeTags(IDocument document, DocumentCommand command, +// String indentation, String lineDelimiter, IType type) +// throws CoreException { +// String comment = CodeGeneration.getTypeComment(type +// .getCompilationUnit(), type.getTypeQualifiedName('.'), +// lineDelimiter); +// if (comment != null) { +// return prepareTemplateComment(comment.trim(), indentation, +// lineDelimiter); +// } +// return null; +// } + +// private String createMethodTags(IDocument document, +// DocumentCommand command, String indentation, String lineDelimiter, +// IMethod method) throws CoreException, BadLocationException { +// IRegion partition = TextUtilities.getPartition(document, fPartitioning, +// command.offset, false); +// ISourceRange sourceRange = method.getSourceRange(); +// if (sourceRange == null +// || sourceRange.getOffset() != partition.getOffset()) +// return null; +// +// // IMethod inheritedMethod= getInheritedMethod(method); +// // String comment= CodeGeneration.getMethodComment(method, +// // inheritedMethod, lineDelimiter); +// // if (comment != null) { +// // comment= comment.trim(); +// // boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$ +// // boolean isJavaDoc= partition.getLength() >= 3 && +// // document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$ +// // if (javadocComment == isJavaDoc) { +// // return prepareTemplateComment(comment, indentation, lineDelimiter); +// // } +// // } +// return null; +// } + + /** + * Returns the method inherited from, null if method is newly + * defined. + */ + // private static IMethod getInheritedMethod(IMethod method) throws + // JavaModelException { + // IType declaringType= method.getDeclaringType(); + // ITypeHierarchy typeHierarchy= + // SuperTypeHierarchyCache.getTypeHierarchy(declaringType); + // return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, + // declaringType, + // method.getElementName(), method.getParameterTypes(), + // method.isConstructor()); + // } + protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) { + if (c.offset < 2 || d.getLength() == 0) { + return; + } + try { + if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$ + // modify document command + c.length++; + c.offset--; + } + } catch (BadLocationException excp) { + // stop work + } + } + + /** + * Guesses if the command operates within a newly created javadoc comment or + * not. If in doubt, it will assume that the javadoc is new. + */ + private static boolean isNewComment(IDocument document, int commandOffset, + String partitioning) { + + try { + int lineIndex = document.getLineOfOffset(commandOffset) + 1; + if (lineIndex >= document.getNumberOfLines()) + return true; + + IRegion line = document.getLineInformation(lineIndex); + ITypedRegion partition = TextUtilities.getPartition(document, + partitioning, commandOffset, false); + int partitionEnd = partition.getOffset() + partition.getLength(); + if (line.getOffset() >= partitionEnd) + return false; + + if (document.getLength() == partitionEnd) + return true; // partition goes to end of document - probably + // a new comment + + String comment = document.get(partition.getOffset(), partition + .getLength()); + if (comment.indexOf("/*", 2) != -1) //$NON-NLS-1$ + return true; // enclosed another comment -> probably a new + // comment + + return false; + + } catch (BadLocationException e) { + return false; + } + } + + private boolean isSmartMode() { + IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + if (page != null) { + IEditorPart part = page.getActiveEditor(); + if (part instanceof ITextEditorExtension3) { + ITextEditorExtension3 extension = (ITextEditorExtension3) part; + return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; + } + } + return false; + } + + /* + * @see IAutoIndentStrategy#customizeDocumentCommand + */ + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + + if (!isSmartMode()) + return; + + try { + + if (command.text != null && command.length == 0) { + String[] lineDelimiters = document.getLegalLineDelimiters(); + int index = TextUtilities + .endsWith(lineDelimiters, command.text); + if (index > -1) { + // ends with line delimiter + if (lineDelimiters[index].equals(command.text)) + // just the line delimiter + jdocIndentAfterNewLine(document, command); + return; + } + } + + if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$ + jdocIndentForCommentEnd(document, command); + return; + } + + ITypedRegion partition = TextUtilities.getPartition(document, + fPartitioning, command.offset, true); + int partitionStart = partition.getOffset(); + int partitionEnd = partition.getLength() + partitionStart; + + String text = command.text; + int offset = command.offset; + int length = command.length; + + // partition change + final int PREFIX_LENGTH = "/*".length(); //$NON-NLS-1$ + final int POSTFIX_LENGTH = "*/".length(); //$NON-NLS-1$ + if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd + - POSTFIX_LENGTH) + || text != null + && text.length() >= 2 + && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$ + return; + + if (command.text == null || command.text.length() == 0) + jdocHandleBackspaceDelete(document, command); + + else if (command.text != null && command.length == 0 + && command.text.length() > 0) + jdocWrapParagraphOnInsert(document, command); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + } + + private void flushCommand(IDocument document, DocumentCommand command) + throws BadLocationException { + + if (!command.doit) + return; + + document.replace(command.offset, command.length, command.text); + + command.doit = false; + if (command.text != null) + command.offset += command.text.length(); + command.length = 0; + command.text = null; + } + + protected void jdocWrapParagraphOnInsert(IDocument document, + DocumentCommand command) throws BadLocationException { + + // Assert.isTrue(command.length == 0); + // Assert.isTrue(command.text != null && command.text.length() == 1); + + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) + return; + + int line = document.getLineOfOffset(command.offset); + IRegion region = document.getLineInformation(line); + int lineOffset = region.getOffset(); + int lineLength = region.getLength(); + + String lineContents = document.get(lineOffset, lineLength); + StringBuffer buffer = new StringBuffer(lineContents); + int start = command.offset - lineOffset; + int end = command.length + start; + buffer.replace(start, end, command.text); + + // handle whitespace + if (command.text != null && command.text.length() != 0 + && command.text.trim().length() == 0) { + + String endOfLine = document.get(command.offset, lineOffset + + lineLength - command.offset); + + // end of line + if (endOfLine.length() == 0) { + // move caret to next line + flushCommand(document, command); + + if (isLineTooShort(document, line)) { + int[] caretOffset = { command.offset }; + jdocWrapParagraphFromLine(document, line, caretOffset, + false); + command.offset = caretOffset[0]; + return; + } + + // move caret to next line if possible + if (line < document.getNumberOfLines() - 1 + && isJavaDocLine(document, line + 1)) { + String lineDelimiter = document.getLineDelimiter(line); + String nextLinePrefix = jdocExtractLinePrefix(document, + line + 1); + command.offset += lineDelimiter.length() + + nextLinePrefix.length(); + } + return; + + // inside whitespace at end of line + } else if (endOfLine.trim().length() == 0) { + // simply insert space + return; + } + } + + // change in prefix region + String prefix = jdocExtractLinePrefix(document, line); + boolean wrapAlways = command.offset >= lineOffset + && command.offset <= lineOffset + prefix.length(); + + // must insert the text now because it may include whitepace + flushCommand(document, command); + + if (wrapAlways + || calculateDisplayedWidth(buffer.toString()) > getMargin() + || isLineTooShort(document, line)) { + int[] caretOffset = { command.offset }; + jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways); + + if (!wrapAlways) + command.offset = caretOffset[0]; + } + } + + /** + * Method jdocWrapParagraphFromLine. + * + * @param document + * @param line + * @param always + */ + private void jdocWrapParagraphFromLine(IDocument document, int line, + int[] caretOffset, boolean always) throws BadLocationException { + + String indent = jdocExtractLinePrefix(document, line); + if (!always) { + if (!indent.trim().startsWith("*")) //$NON-NLS-1$ + return; + + if (indent.trim().startsWith("*/")) //$NON-NLS-1$ + return; + + if (!isLineTooLong(document, line) + && !isLineTooShort(document, line)) + return; + } + + boolean caretRelativeToParagraphOffset = false; + int caret = caretOffset[0]; + + int caretLine = document.getLineOfOffset(caret); + int lineOffset = document.getLineOffset(line); + int paragraphOffset = lineOffset + indent.length(); + if (paragraphOffset < caret) { + caret -= paragraphOffset; + caretRelativeToParagraphOffset = true; + } else { + caret -= lineOffset; + } + + StringBuffer buffer = new StringBuffer(); + int currentLine = line; + while (line == currentLine || isJavaDocLine(document, currentLine)) { + + if (buffer.length() != 0 + && !Character.isWhitespace(buffer + .charAt(buffer.length() - 1))) { + buffer.append(' '); + if (currentLine <= caretLine) { + // in this case caretRelativeToParagraphOffset is always + // true + ++caret; + } + } + + String string = getLineContents(document, currentLine); + buffer.append(string); + currentLine++; + } + String paragraph = buffer.toString(); + + if (paragraph.trim().length() == 0) + return; + + caretOffset[0] = caretRelativeToParagraphOffset ? caret : 0; + String delimiter = document.getLineDelimiter(0); + String wrapped = formatParagraph(paragraph, caretOffset, indent, + delimiter, getMargin()); + + int beginning = document.getLineOffset(line); + int end = document.getLineOffset(currentLine); + document.replace(beginning, end - beginning, wrapped.toString()); + + caretOffset[0] = caretRelativeToParagraphOffset ? caretOffset[0] + + beginning : caret + beginning; + } + + /** + * Line break iterator to handle whitespaces as first class citizens. + */ + private static class LineBreakIterator { + + private final String fString; + + private final BreakIterator fIterator = BreakIterator.getLineInstance(); + + private int fStart; + + private int fEnd; + + private int fBufferedEnd; + + public LineBreakIterator(String string) { + fString = string; + fIterator.setText(string); + } + + public int first() { + fBufferedEnd = -1; + fStart = fIterator.first(); + return fStart; + } + + public int next() { + + if (fBufferedEnd != -1) { + fStart = fEnd; + fEnd = fBufferedEnd; + fBufferedEnd = -1; + return fEnd; + } + + fStart = fEnd; + fEnd = fIterator.next(); + + if (fEnd == BreakIterator.DONE) + return fEnd; + + final String string = fString.substring(fStart, fEnd); + + // whitespace + if (string.trim().length() == 0) + return fEnd; + + final String word = string.trim(); + if (word.length() == string.length()) + return fEnd; + + // suspected whitespace + fBufferedEnd = fEnd; + return fStart + word.length(); + } + } + + /** + * Formats a paragraph, using break iterator. + * + * @param offset + * an offset within the paragraph, which will be updated with + * respect to formatting. + */ + private static String formatParagraph(String paragraph, int[] offset, + String prefix, String lineDelimiter, int margin) { + + LineBreakIterator iterator = new LineBreakIterator(paragraph); + + StringBuffer paragraphBuffer = new StringBuffer(); + StringBuffer lineBuffer = new StringBuffer(); + StringBuffer whiteSpaceBuffer = new StringBuffer(); + + int index = offset[0]; + int indexBuffer = -1; + + // line delimiter could be null + if (lineDelimiter == null) + lineDelimiter = ""; //$NON-NLS-1$ + + for (int start = iterator.first(), end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator + .next()) { + + String word = paragraph.substring(start, end); + + // word is whitespace + if (word.trim().length() == 0) { + whiteSpaceBuffer.append(word); + + // first word of line is always appended + } else if (lineBuffer.length() == 0) { + lineBuffer.append(prefix); + lineBuffer.append(whiteSpaceBuffer.toString()); + lineBuffer.append(word); + + } else { + String line = lineBuffer.toString() + + whiteSpaceBuffer.toString() + word.toString(); + + // margin exceeded + if (calculateDisplayedWidth(line) > margin) { + // flush line buffer and wrap paragraph + paragraphBuffer.append(lineBuffer.toString()); + paragraphBuffer.append(lineDelimiter); + lineBuffer.setLength(0); + lineBuffer.append(prefix); + lineBuffer.append(word); + + // flush index buffer + if (indexBuffer != -1) { + offset[0] = indexBuffer; + // correct for caret in whitespace at the end of line + if (whiteSpaceBuffer.length() != 0 && index < start + && index >= start - whiteSpaceBuffer.length()) + offset[0] -= (index - (start - whiteSpaceBuffer + .length())); + indexBuffer = -1; + } + + whiteSpaceBuffer.setLength(0); + + // margin not exceeded + } else { + lineBuffer.append(whiteSpaceBuffer.toString()); + lineBuffer.append(word); + whiteSpaceBuffer.setLength(0); + } + } + + if (index >= start && index < end) { + indexBuffer = paragraphBuffer.length() + lineBuffer.length() + + (index - start); + if (word.trim().length() != 0) + indexBuffer -= word.length(); + } + } + + // flush line buffer + paragraphBuffer.append(lineBuffer.toString()); + paragraphBuffer.append(lineDelimiter); + + // flush index buffer + if (indexBuffer != -1) + offset[0] = indexBuffer; + + // last position is not returned by break iterator + else if (offset[0] == paragraph.length()) + offset[0] = paragraphBuffer.length() - lineDelimiter.length(); + + return paragraphBuffer.toString(); + } + + private static IPreferenceStore getPreferenceStore() { + return PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + /** + * Returns the displayed width of a string, taking in account the displayed + * tab width. The result can be compared against the print margin. + */ + private static int calculateDisplayedWidth(String string) { + + int tabWidth = getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); + if (tabWidth <= 0) { + tabWidth = 2; + } + int column = 0; + for (int i = 0; i < string.length(); i++) + if ('\t' == string.charAt(i)) + column += tabWidth - (column % tabWidth); + else + column++; + + return column; + } + + private String jdocExtractLinePrefix(IDocument d, int line) + throws BadLocationException { + + IRegion region = d.getLineInformation(line); + int lineOffset = region.getOffset(); + int index = findEndOfWhiteSpace(d, lineOffset, lineOffset + + d.getLineLength(line)); + if (d.getChar(index) == '*') { + index++; + if (index != lineOffset + region.getLength() + && d.getChar(index) == ' ') + index++; + } + return d.get(lineOffset, index - lineOffset); + } + + private String getLineContents(IDocument d, int line) + throws BadLocationException { + int offset = d.getLineOffset(line); + int length = d.getLineLength(line); + String lineDelimiter = d.getLineDelimiter(line); + if (lineDelimiter != null) + length = length - lineDelimiter.length(); + String lineContents = d.get(offset, length); + int trim = jdocExtractLinePrefix(d, line).length(); + return lineContents.substring(trim); + } + + private static String getLine(IDocument document, int line) + throws BadLocationException { + IRegion region = document.getLineInformation(line); + return document.get(region.getOffset(), region.getLength()); + } + + /** + * Returns true if the javadoc line is too short, + * false otherwise. + */ + private boolean isLineTooShort(IDocument document, int line) + throws BadLocationException { + + if (!isJavaDocLine(document, line + 1)) + return false; + + String nextLine = getLineContents(document, line + 1); + if (nextLine.trim().length() == 0) + return false; + + return true; + } + + /** + * Returns true if the line is too long, false + * otherwise. + */ + private boolean isLineTooLong(IDocument document, int line) + throws BadLocationException { + String lineContents = getLine(document, line); + return calculateDisplayedWidth(lineContents) > getMargin(); + } + + private static int getMargin() { + return getPreferenceStore() + .getInt( + AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); + } + + private static final String[] fgInlineTags = { + "", "", "", "", "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + }; + + private boolean isInlineTag(String string) { + for (int i = 0; i < fgInlineTags.length; i++) + if (string.startsWith(fgInlineTags[i])) + return true; + return false; + } + + /** + * returns true if the specified line is part of a paragraph and should be + * merged with the previous line. + */ + private boolean isJavaDocLine(IDocument document, int line) + throws BadLocationException { + + if (document.getNumberOfLines() < line) + return false; + + int offset = document.getLineOffset(line); + int length = document.getLineLength(line); + int firstChar = findEndOfWhiteSpace(document, offset, offset + length); + length -= firstChar - offset; + String lineContents = document.get(firstChar, length); + + String prefix = lineContents.trim(); + if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$ + return false; + + lineContents = lineContents.substring(1).trim().toLowerCase(); + + // preserve empty lines + if (lineContents.length() == 0) + return false; + + // preserve @TAGS + if (lineContents.startsWith("@")) //$NON-NLS-1$ + return false; + + // preserve HTML tags which are not inline + if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$ + return false; + + return true; + } + + protected void jdocHandleBackspaceDelete(IDocument document, + DocumentCommand c) { + + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FORMAT_JAVADOCS)) + return; + + try { + String text = document.get(c.offset, c.length); + int line = document.getLineOfOffset(c.offset); + int lineOffset = document.getLineOffset(line); + + // erase line delimiter + String lineDelimiter = document.getLineDelimiter(line); + if (lineDelimiter != null && lineDelimiter.equals(text)) { + + String prefix = jdocExtractLinePrefix(document, line + 1); + + // strip prefix if any + if (prefix.length() > 0) { + int length = document.getLineDelimiter(line).length() + + prefix.length(); + document.replace(c.offset, length, null); + + c.doit = false; + c.length = 0; + return; + } + + // backspace: beginning of a javadoc line + } else if (document.getChar(c.offset - 1) == '*' + && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset + - lineOffset) { + + lineDelimiter = document.getLineDelimiter(line - 1); + String prefix = jdocExtractLinePrefix(document, line); + int length = (lineDelimiter != null ? lineDelimiter.length() + : 0) + + prefix.length(); + document.replace(c.offset - length + 1, length, null); + + c.doit = false; + c.offset -= length - 1; + c.length = 0; + return; + + } else { + document.replace(c.offset, c.length, null); + c.doit = false; + c.length = 0; + } + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + + try { + int line = document.getLineOfOffset(c.offset); + int lineOffset = document.getLineOffset(line); + String prefix = jdocExtractLinePrefix(document, line); + boolean always = c.offset > lineOffset + && c.offset <= lineOffset + prefix.length(); + int[] caretOffset = { c.offset }; + jdocWrapParagraphFromLine(document, document + .getLineOfOffset(c.offset), caretOffset, always); + c.offset = caretOffset[0]; + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + } + } + + /** + * Returns the compilation unit of the CompilationUnitEditor invoking the + * AutoIndentStrategy, might return null on error. + */ +// private static ICompilationUnit getCompilationUnit() { +// +// IWorkbenchWindow window = PlatformUI.getWorkbench() +// .getActiveWorkbenchWindow(); +// if (window == null) +// return null; +// +// IWorkbenchPage page = window.getActivePage(); +// if (page == null) +// return null; +// +// IEditorPart editor = page.getActiveEditor(); +// if (editor == null) +// return null; +// +// IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() +// .getWorkingCopyManager(); +// ICompilationUnit unit = manager.getWorkingCopy(editor.getEditorInput()); +// if (unit == null) +// return null; +// +// return unit; +// } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCodeScanner.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java new file mode 100644 index 0000000..ce2ec13 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/phpdoc/PHPDocCompletionProcessor.java @@ -0,0 +1,208 @@ +package net.sourceforge.phpdt.internal.ui.text.phpdoc; + +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ + +import java.util.Arrays; +//import java.util.Comparator; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; +import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +//import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.ui.IEditorPart; + +/** + * Simple PHPDoc completion processor. + */ +public class PHPDocCompletionProcessor implements IContentAssistProcessor { + +// private static class PHPDocCompletionProposalComparator implements +// Comparator { +// public int compare(Object o1, Object o2) { +// ICompletionProposal c1 = (ICompletionProposal) o1; +// ICompletionProposal c2 = (ICompletionProposal) o2; +// return c1.getDisplayString().compareTo(c2.getDisplayString()); +// } +// }; + + // private IEditorPart fEditor; + // private IWorkingCopyManager fManager; + private char[] fProposalAutoActivationSet; + + private PHPCompletionProposalComparator fComparator; + + private TemplateEngine fTemplateEngine; + + //private boolean fRestrictToMatchingCase; + + private IEditorPart fEditor; + + protected IWorkingCopyManager fManager; + + public PHPDocCompletionProcessor(IEditorPart editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + + // fEditor= editor; + // fManager= JavaPlugin.getDefault().getWorkingCopyManager(); + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("phpdoc"); //$NON-NLS-1$ + if (contextType != null) + fTemplateEngine = new TemplateEngine(contextType); + //fRestrictToMatchingCase = false; + + fComparator = new PHPCompletionProposalComparator(); + } + + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + public void orderProposalsAlphabetically(boolean order) { + fComparator.setOrderAlphabetically(order); + } + + /** + * Tells this processor to restrict is proposals to those starting with + * matching cases. + * + * @param restrict + * true if proposals should be restricted + */ + public void restrictProposalsToMatchingCases(boolean restrict) { + //fRestrictToMatchingCase = restrict; + } + + /** + * @see IContentAssistProcessor#getErrorMessage() + */ + public String getErrorMessage() { + return null; + } + + /** + * @see IContentAssistProcessor#getContextInformationValidator() + */ + public IContextInformationValidator getContextInformationValidator() { + return null; + } + + /** + * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() + */ + public char[] getContextInformationAutoActivationCharacters() { + return null; + } + + /** + * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /** + * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) + */ + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + return null; + } + + /** + * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + //IDocument document = viewer.getDocument(); + + IPHPCompletionProposal[] results = new IPHPCompletionProposal[0]; + + // try { + // if (unit != null) { + // + // int offset= documentOffset; + // int length= 0; + // + // Point selection= viewer.getSelectedRange(); + // if (selection.y > 0) { + // offset= selection.x; + // length= selection.y; + // } + // + // JavaDocCompletionEvaluator evaluator= new + // JavaDocCompletionEvaluator(unit, document, offset, length); + // evaluator.restrictProposalsToMatchingCases(fRestrictToMatchingCase); + // results= evaluator.computeProposals(); + // } + // } catch (JavaModelException e) { + // JavaPlugin.log(e); + // } + + if (fTemplateEngine != null) { + // try { + fTemplateEngine.reset(); + fTemplateEngine.complete(viewer, documentOffset, unit); + // } catch (JavaModelException x) { + // } + + IPHPCompletionProposal[] templateResults = fTemplateEngine + .getResults(); + if (results.length == 0) { + results = templateResults; + } else { + // concatenate arrays + IPHPCompletionProposal[] total = new IPHPCompletionProposal[results.length + + templateResults.length]; + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + System.arraycopy(results, 0, total, templateResults.length, + results.length); + results = total; + } + } + + /* + * Order here and not in result collector to make sure that the order + * applies to all proposals and not just those of the compilation unit. + */ + return order(results); + } + + /** + * Order the given proposals. + */ + private IPHPCompletionProposal[] order(IPHPCompletionProposal[] proposals) { + Arrays.sort(proposals, fComparator); + return proposals; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/AddWordProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/ChangeCaseProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/HtmlTagDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/JavaDocTagDictionary.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java new file mode 100644 index 0000000..2f8a304 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckEngine.java @@ -0,0 +1,356 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpdt.internal.ui.text.spelling; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.DefaultSpellChecker; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckEngine; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellChecker; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellDictionary; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.PersistentSpellDictionary; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; + +/** + * Spell check engine for Java source spell checking. + * + * @since 3.0 + */ +public class SpellCheckEngine implements ISpellCheckEngine, + IPropertyChangeListener { + + /** The dictionary location */ + public static final String DICTIONARY_LOCATION = "dictionaries/"; //$NON-NLS-1$ + + /** The singleton spell checker instance */ + private static ISpellChecker fChecker = null; + + /** The singleton engine instance */ + private static ISpellCheckEngine fEngine = null; + + /** + * Returns the available locales for this spell check engine. + * + * @return The available locales for this engine + */ + public static Set getAvailableLocales() { + + URL url = null; + Locale locale = null; + InputStream stream = null; + + final Set result = new HashSet(); + try { + + final URL location = getDictionaryLocation(); + final Locale[] locales = Locale.getAvailableLocales(); + + for (int index = 0; index < locales.length; index++) { + + locale = locales[index]; + url = new URL( + location, + locale.toString().toLowerCase() + + "." + PHPUIMessages.getString("Spelling.dictionary.file.extension")); //$NON-NLS-1$ //$NON-NLS-2$ + + try { + stream = url.openStream(); + if (stream != null) { + try { + result.add(locale); + } finally { + stream.close(); + } + } + } catch (IOException exception) { + // Do nothing + } + } + } catch (MalformedURLException exception) { + // Do nothing + } + result.add(getDefaultLocale()); + + return result; + } + + /** + * Returns the default locale for this engine. + * + * @return The default locale + */ + public static Locale getDefaultLocale() { + return Locale.US; + } + + /** + * Returns the dictionary location. + * + * @throws MalformedURLException + * if the URL could not be created + * @return The dictionary location, or null iff the location + * is not known + */ + public static URL getDictionaryLocation() throws MalformedURLException { + + final PHPeclipsePlugin plugin = PHPeclipsePlugin.getDefault(); + if (plugin != null) + return plugin.getBundle().getEntry("/" + DICTIONARY_LOCATION); //$NON-NLS-1$ + + return null; + } + + /** + * Returns the singleton instance of the spell check engine. + * + * @return The singleton instance of the spell check engine + */ + public static final synchronized ISpellCheckEngine getInstance() { + + if (fEngine == null) + fEngine = new SpellCheckEngine(); + + return fEngine; + } + + /** The registered locale insenitive dictionaries */ + private final Set fGlobalDictionaries = new HashSet(); + + /** The current locale */ + private Locale fLocale = null; + + /** The registered locale sensitive dictionaries */ + private final Map fLocaleDictionaries = new HashMap(); + + /** The preference store where to listen */ + private IPreferenceStore fPreferences = null; + + /** The user dictionary */ + private ISpellDictionary fUserDictionary = null; + + /** + * Creates a new spell check manager. + */ + private SpellCheckEngine() { + + fGlobalDictionaries.add(new TaskTagDictionary()); + fGlobalDictionaries.add(new HtmlTagDictionary()); + fGlobalDictionaries.add(new JavaDocTagDictionary()); + + try { + + Locale locale = null; + final URL location = getDictionaryLocation(); + + for (final Iterator iterator = getAvailableLocales().iterator(); iterator + .hasNext();) { + + locale = (Locale) iterator.next(); + fLocaleDictionaries.put(locale, new SpellReconcileDictionary( + locale, location)); + } + + } catch (MalformedURLException exception) { + // Do nothing + } + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#createSpellChecker(java.util.Locale,org.eclipse.jface.preference.IPreferenceStore) + */ + public final synchronized ISpellChecker createSpellChecker( + final Locale locale, final IPreferenceStore store) { + + if (fLocale != null && fLocale.equals(locale)) + return fChecker; + + if (fChecker == null) { + + fChecker = new DefaultSpellChecker(store); + store.addPropertyChangeListener(this); + + fPreferences = store; + + ISpellDictionary dictionary = null; + for (Iterator iterator = fGlobalDictionaries.iterator(); iterator + .hasNext();) { + + dictionary = (ISpellDictionary) iterator.next(); + fChecker.addDictionary(dictionary); + } + } + + ISpellDictionary dictionary = null; + if (fLocale != null) { + + dictionary = (ISpellDictionary) fLocaleDictionaries.get(fLocale); + if (dictionary != null) { + + fChecker.removeDictionary(dictionary); + dictionary.unload(); + } + } + fLocale = locale; + + dictionary = (ISpellDictionary) fLocaleDictionaries.get(locale); + if (dictionary == null) { + + if (!getDefaultLocale().equals(locale)) { + + if (fPreferences != null) + fPreferences.removePropertyChangeListener(this); + + fChecker = null; + fLocale = null; + } + + } else + fChecker.addDictionary(dictionary); + + if (fPreferences != null) + propertyChange(new PropertyChangeEvent( + this, + ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY, + null, + fPreferences + .getString(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY))); + + return fChecker; + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#getLocale() + */ + public final Locale getLocale() { + return fLocale; + } + + /* + * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) + */ + public final void propertyChange(final PropertyChangeEvent event) { + + if (fChecker != null + && event.getProperty().equals( + ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { + + if (fUserDictionary != null) { + + fChecker.removeDictionary(fUserDictionary); + fUserDictionary = null; + } + + final String file = (String) event.getNewValue(); + if (file.length() > 0) { + + try { + + final URL url = new URL("file", null, file); //$NON-NLS-1$ + InputStream stream = url.openStream(); + if (stream != null) { + try { + fUserDictionary = new PersistentSpellDictionary(url); + fChecker.addDictionary(fUserDictionary); + } finally { + stream.close(); + } + } + } catch (MalformedURLException exception) { + // Do nothing + } catch (IOException exception) { + // Do nothing + } + } + } + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) + */ + public synchronized final void registerDictionary( + final ISpellDictionary dictionary) { + + fGlobalDictionaries.add(dictionary); + + if (fChecker != null) + fChecker.addDictionary(dictionary); + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#registerDictionary(java.util.Locale,net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) + */ + public synchronized final void registerDictionary(final Locale locale, + final ISpellDictionary dictionary) { + + fLocaleDictionaries.put(locale, dictionary); + + if (fChecker != null && fLocale != null && fLocale.equals(locale)) + fChecker.addDictionary(dictionary); + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#unload() + */ + public synchronized final void unload() { + + ISpellDictionary dictionary = null; + for (final Iterator iterator = fGlobalDictionaries.iterator(); iterator + .hasNext();) { + + dictionary = (ISpellDictionary) iterator.next(); + dictionary.unload(); + } + + for (final Iterator iterator = fLocaleDictionaries.values().iterator(); iterator + .hasNext();) { + + dictionary = (ISpellDictionary) iterator.next(); + dictionary.unload(); + } + + if (fPreferences != null) + fPreferences.removePropertyChangeListener(this); + + fUserDictionary = null; + fChecker = null; + } + + /* + * @see net.sourceforge.phpdt.ui.text.spelling.engine.ISpellCheckEngine#unregisterDictionary(net.sourceforge.phpdt.ui.text.spelling.engine.ISpellDictionary) + */ + public synchronized final void unregisterDictionary( + final ISpellDictionary dictionary) { + + fGlobalDictionaries.remove(dictionary); + fLocaleDictionaries.values().remove(dictionary); + + if (fChecker != null) + fChecker.removeDictionary(dictionary); + + dictionary.unload(); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellCheckIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/TaskTagDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordCorrectionProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/WordIgnoreProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/AbstractSpellDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellCheckPreferenceKeys.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellChecker.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEvent.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/ISpellEventListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/PersistentSpellDictionary.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/RankedWordProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/SpellEvent.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/package.html similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/package.html rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/engine/package.html diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/package.html similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/spelling/package.html rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/package.html diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java new file mode 100644 index 0000000..b6153e4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/AbstractProposal.java @@ -0,0 +1,100 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +//import java.util.WeakHashMap; + +import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Shell; + + +/** + * A PHP identifier proposal. + */ +public abstract class AbstractProposal implements IPHPCompletionProposal { + protected IRegion fSelectedRegion; // initialized by apply() + + protected final ITextViewer fViewer; + + protected ContextInformation fContextInfo; + + public AbstractProposal(ITextViewer viewer) { + fContextInfo = null; + fViewer = viewer; + } + + protected static String textToHTML(String string) { + StringBuffer buffer = new StringBuffer(string.length()); + buffer.append("
"); //$NON-NLS-1$
+
+		for (int i = 0; i != string.length(); i++) {
+			char ch = string.charAt(i);
+
+			switch (ch) {
+			case '&':
+				buffer.append("&"); //$NON-NLS-1$
+				break;
+
+			case '<':
+				buffer.append("<"); //$NON-NLS-1$
+				break;
+
+			case '>':
+				buffer.append(">"); //$NON-NLS-1$
+				break;
+
+			case '\t':
+				buffer.append("    "); //$NON-NLS-1$
+				break;
+
+			case '\n':
+				buffer.append("
"); //$NON-NLS-1$ + break; + + default: + buffer.append(ch); + break; + } + } + + buffer.append("
"); //$NON-NLS-1$ + return buffer.toString(); + } + + /* + * @see ICompletionProposal#getSelection(IDocument) + */ + public Point getSelection(IDocument document) { + return new Point(fSelectedRegion.getOffset(), fSelectedRegion + .getLength()); + } + + protected void handleException(CoreException e) { + PHPeclipsePlugin.log(e); + } + + protected void openErrorDialog(BadLocationException e) { + Shell shell = fViewer.getTextWidget().getShell(); + MessageDialog.openError(shell, TemplateMessages + .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ + } + + public IContextInformation getContextInformation() { + return null; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java new file mode 100644 index 0000000..1ab738f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInEngine.java @@ -0,0 +1,125 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +import java.util.ArrayList; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.swt.graphics.Point; + +public class BuiltInEngine { + + /** The context type. */ + private JavaContextType fContextType; + + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); + + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public BuiltInEngine(JavaContextType contextType) { + // Assert.isNotNull(contextType); + fContextType = contextType; + } + + /** + * Empties the collector. + * + * @param viewer + * the text viewer + * @param unit + * the compilation unit (may be null) + */ + public void reset() { + fProposals.clear(); + } + + /** + * Returns the array of matching templates. + */ + public IPHPCompletionProposal[] getResults() { + return (IPHPCompletionProposal[]) fProposals + .toArray(new IPHPCompletionProposal[fProposals.size()]); + } + + /** + * Inspects the context of the compilation unit around + * completionPosition and feeds the collector with proposals. + * + * @param viewer + * the text viewer + * @param completionPosition + * the context position in the document of the text viewer + * @param compilationUnit + * the compilation unit (may be null) + */ + public void complete(ITextViewer viewer, int completionPosition, + ArrayList identifiers, ICompilationUnit compilationUnit) + // hrows JavaModelException + { + IDocument document = viewer.getDocument(); + + // prohibit recursion + // if (LinkedPositionManager.hasActiveManager(document)) + // return; + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + Point selection = viewer.getSelectedRange(); + // remember selected text + String selectedText = null; + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + // ((CompilationUnitContextType) + // fContextType).setContextParameters(document, completionPosition, + // selection.y); //mpilationUnit); + // JavaContext context = (JavaContext) fContextType.createContext(); + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + int start = context.getStart(); + int end = context.getEnd(); + IRegion region = new Region(start, end - start); + + // Template[] templates= Templates.getInstance().getTemplates(); + String identifier = null; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + PHPElement element = null; + for (int i = 0; i != identifiers.size(); i++) { + element = (PHPElement) identifiers.get(i); + if (element instanceof PHPFunction) { + identifier = ((PHPFunction) element).getName(); + if (context.canEvaluate(identifier)) { + if (maxProposals-- < 0) { + return; + } + fProposals.add(new BuiltInProposal(identifier, + (PHPFunction) element, context, region, viewer)); + } + } + } + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java new file mode 100644 index 0000000..900604a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/BuiltInProposal.java @@ -0,0 +1,179 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.swt.graphics.Image; + +// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +// import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; + +/** + * A PHP identifier proposal. + */ +public class BuiltInProposal extends AbstractProposal { + private final TemplateContext fContext; + + private final PHPFunction fFunction; + + private final IRegion fRegion; + + private final String fBuiltinFunctionName; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param context + * the context in which the template was requested. + * @param image + * the icon of the proposal. + */ + public BuiltInProposal(String functionName, PHPFunction function, + TemplateContext context, IRegion region, ITextViewer viewer) { + super(viewer); + fBuiltinFunctionName = functionName; + fFunction = function; + fContext = context; + // fViewer = viewer; + fRegion = region; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + // if (fTemplateBuffer == null) + // fTemplateBuffer= fContext.evaluate(fTemplate); + + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + + // insert template string + // String templateString = fTemplate; // + // fTemplateBuffer.getString(); + document.replace(start, end - start, fBuiltinFunctionName + "()"); + + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + // TemplatePosition[] variables= fTemplateBuffer.getVariables(); + // for (int i= 0; i != variables.length; i++) { + // TemplatePosition variable= variables[i]; + // + // if (variable.isResolved()) + // continue; + // + // int[] offsets= variable.getOffsets(); + // int length= variable.getLength(); + // + // for (int j= 0; j != offsets.length; j++) + // manager.addPosition(offsets[j] + start, length); + // } + + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(fBuiltinFunctionName.length() + start + + 1); + // editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + + // start); + editor.enter(); + + fSelectedRegion = editor.getSelectedRegion(); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + + } + // catch (CoreException e) { + // handleException(e); + // } + } + + public String getAdditionalProposalInfo() { + return fFunction.getHoverText(); + } + + public IContextInformation getContextInformation() { + if (fContextInfo == null) { + String contextInfoString = fFunction.getHoverText(); + if (contextInfoString != null && contextInfoString.length() > 0) { + // extract the parameter context information for the function: + int i0 = contextInfoString.indexOf('('); + int newline = contextInfoString.indexOf('\n'); + if (i0 >= 0 && (i0 < newline || newline < 0)) { + int i1 = contextInfoString.indexOf(')', i0 + 1); + if (i1 > 0) { + fContextInfo = new ContextInformation(null, + contextInfoString.substring(i0 + 1, i1)); + } else { + fContextInfo = new ContextInformation(null, + contextInfoString); + } + } else { + fContextInfo = new ContextInformation(null, + contextInfoString); + } + } + } + return fContextInfo; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + return fBuiltinFunctionName + + TemplateMessages.getString("TemplateProposal.delimiter") + fFunction.getUsage(); // $NON-NLS-1$ + // //$NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return PHPUiImages.get(PHPUiImages.IMG_BUILTIN); + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + + if (fContext instanceof JavaContext) { + JavaContext context = (JavaContext) fContext; + switch (context.getCharacterBeforeStart()) { + // high relevance after whitespace + case ' ': + case '\r': + case '\n': + case '\t': + return 50; + + default: + return 0; + } + } else { + return 50; + } + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java new file mode 100644 index 0000000..69781c9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java @@ -0,0 +1,299 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.SortedMap; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.swt.graphics.Point; + +public class DeclarationEngine { + + /** The context type. */ + private JavaContextType fContextType; + + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); + + /** Token determines last which declarations are allowed for proposal */ + private TokenName fLastSignificantToken; + + private IProject fProject; + + // private IFile fFile; + private String fFileName; + + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public DeclarationEngine(IProject project, JavaContextType contextType, + TokenName lastSignificantToken, IFile file) { + // Assert.isNotNull(contextType); + fProject = project; + fContextType = contextType; + + fLastSignificantToken = lastSignificantToken; + // fFile = file; + if (file != null) { + fFileName = file.getProjectRelativePath().toString(); + } else { + fFileName = ""; + } + } + + /** + * Empties the collector. + * + * @param viewer + * the text viewer + * @param unit + * the compilation unit (may be null) + */ + public void reset() { + fProposals.clear(); + } + + /** + * Returns the array of matching templates. + */ + public IPHPCompletionProposal[] getResults() { + return (IPHPCompletionProposal[]) fProposals + .toArray(new IPHPCompletionProposal[fProposals.size()]); + } + + /** + * Inspects the context of the compilation unit around + * completionPosition and feeds the collector with proposals. + * + * @param viewer + * the text viewer + * @param completionPosition + * the context position in the document of the text viewer + * @param compilationUnit + * the compilation unit (may be null) + */ + public void completeObject(ITextViewer viewer, int completionPosition, + SortedMap map, ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + + // remember selected text + String selectedText = null; + + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + + int start = context.getStart(); + int end = context.getEnd(); + String prefix = context.getKey(); + IRegion region = new Region(start, end - start); + + String identifier = null; + + SortedMap subMap = map.subMap(prefix, prefix + '\255'); + Iterator iter = subMap.keySet().iterator(); + PHPIdentifierLocation location; + ArrayList list; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + while (iter.hasNext()) { + identifier = (String) iter.next(); + if (context.canEvaluate(identifier)) { + list = (ArrayList) subMap.get(identifier); + for (int i = 0; i < list.size(); i++) { + location = (PHPIdentifierLocation) list.get(i); + int type = location.getType(); + switch (fLastSignificantToken) { + case MINUS_GREATER: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + break; + case VARIABLE: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + // if (fFileName.equals(location.getFilename())) { + // continue; // for loop + // } + break; + case THIS_PHP_COMPLETION: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + // if (!fFileName.equals(location.getFilename())) { + // continue; // for loop + // } + break; + case NEW: + if (type != PHPIdentifierLocation.CLASS + && type != PHPIdentifierLocation.CONSTRUCTOR) { + continue; // for loop + } + break; + default: + if (type == PHPIdentifierLocation.METHOD + || type == PHPIdentifierLocation.CONSTRUCTOR + || type == PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + } + if (maxProposals-- < 0) { + return; + } + fProposals.add(new DeclarationProposal(fProject, + identifier, location, context, region, viewer)); + } + } + } + + } + + /** + * Inspects the context of the compilation unit around + * completionPosition and feeds the collector with proposals. + * + * @param viewer + * the text viewer + * @param completionPosition + * the context position in the document of the text viewer + * @param compilationUnit + * the compilation unit (may be null) + */ + public void complete(ITextViewer viewer, int completionPosition, + SortedMap map, ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + + // remember selected text + String selectedText = null; + + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + // ((CompilationUnitContextType) + // fContextType).setContextParameters(document, completionPosition, + // selection.y); + + // CompilationUnitContext context = (CompilationUnitContext) + // fContextType.createContext(); + JavaContext context = (JavaContext) fContextType.createContext( + document, completionPosition, selection.y, compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + + int start = context.getStart(); + int end = context.getEnd(); + String prefix = context.getKey(); + IRegion region = new Region(start, end - start); + + String identifier = null; + + SortedMap subMap = map.subMap(prefix, prefix + '\255'); + Iterator iter = subMap.keySet().iterator(); + PHPIdentifierLocation location; + ArrayList list; + int maxProposals = PHPeclipsePlugin.MAX_PROPOSALS; + while (iter.hasNext()) { + identifier = (String) iter.next(); + if (context.canEvaluate(identifier)) { + list = (ArrayList) subMap.get(identifier); + for (int i = 0; i < list.size(); i++) { + location = (PHPIdentifierLocation) list.get(i); + int type = location.getType(); + switch (fLastSignificantToken) { + case MINUS_GREATER: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + break; + case VARIABLE: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + if (fFileName.equals(location.getFilename())) { + continue; // for loop + } + break; + case THIS_PHP_COMPLETION: + if (type != PHPIdentifierLocation.METHOD + && type != PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + // check all filenames of the subclasses + if (!fFileName.equals(location.getFilename())) { + continue; // for loop + } + break; + case NEW: + if (type != PHPIdentifierLocation.CLASS + && type != PHPIdentifierLocation.CONSTRUCTOR) { + continue; // for loop + } + break; + default: + if (type == PHPIdentifierLocation.METHOD + || type == PHPIdentifierLocation.CONSTRUCTOR + || type == PHPIdentifierLocation.VARIABLE) { + continue; // for loop + } + } + if (maxProposals-- < 0) { + return; + } + fProposals.add(new DeclarationProposal(fProject, + identifier, location, context, region, viewer)); + } + } + } + + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java new file mode 100644 index 0000000..c483035 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationProposal.java @@ -0,0 +1,286 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +import net.sourceforge.phpdt.internal.corext.phpdoc.PHPDocUtil; +import net.sourceforge.phpdt.internal.corext.template.TemplateMessages; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; + +import org.eclipse.core.resources.IProject; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.swt.graphics.Image; + +// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +// import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +// import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; + +/** + * A PHP identifier proposal. + */ +public class DeclarationProposal extends AbstractProposal { // implements + // IPHPCompletionProposal + // { + private IProject fProject; + + private final TemplateContext fContext; + + private final PHPIdentifierLocation fLocation; + + String fInfo; + + // private TemplateBuffer fTemplateBuffer; + // private String fOldText; + // private final Image fImage_fun; + // private final Image fImage_var; + private final IRegion fRegion; + + // private IRegion fSelectedRegion; // initialized by apply() + + private final String fIdentifierName; + + // private final ITextViewer fViewer; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param context + * the context in which the template was requested. + * @param image + * the icon of the proposal. + */ + public DeclarationProposal(IProject project, String identifierName, + PHPIdentifierLocation location, TemplateContext context, + IRegion region, ITextViewer viewer) { + super(viewer); + // Image image_fun, + // Image image_var) { + fProject = project; + fIdentifierName = identifierName; + fLocation = location; + fContext = context; + fRegion = region; + fInfo = null; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + // if (fTemplateBuffer == null) + // fTemplateBuffer= fContext.evaluate(fTemplate); + + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + + switch (fLocation.getType()) { + case PHPIdentifierLocation.FUNCTION: + document.replace(start, end - start, fIdentifierName + "()"); + break; + case PHPIdentifierLocation.CONSTRUCTOR: + document.replace(start, end - start, fIdentifierName + "()"); + break; + case PHPIdentifierLocation.METHOD: + document.replace(start, end - start, fIdentifierName + "()"); + break; + + default: + document.replace(start, end - start, fIdentifierName); + } + + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + // TemplatePosition[] variables= fTemplateBuffer.getVariables(); + // for (int i= 0; i != variables.length; i++) { + // TemplatePosition variable= variables[i]; + // + // if (variable.isResolved()) + // continue; + // + // int[] offsets= variable.getOffsets(); + // int length= variable.getLength(); + // + // for (int j= 0; j != offsets.length; j++) + // manager.addPosition(offsets[j] + start, length); + // } + + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + switch (fLocation.getType()) { + case PHPIdentifierLocation.FUNCTION: + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); + break; + case PHPIdentifierLocation.CONSTRUCTOR: + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); + break; + case PHPIdentifierLocation.METHOD: + editor + .setFinalCaretOffset(fIdentifierName.length() + start + + 1); + break; + + default: + editor.setFinalCaretOffset(fIdentifierName.length() + start); + } + editor.enter(); + + fSelectedRegion = editor.getSelectedRegion(); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + + } + // catch (CoreException e) { + // handleException(e); + // } + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + if (fInfo == null) { + fInfo = computeProposalInfo(); + } + return fInfo; + } + + private String computeProposalInfo() { + StringBuffer hoverInfoBuffer = new StringBuffer(); + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + String workspaceLocation; + if (fProject != null) { + workspaceLocation = fProject.getLocation().toString() + '/'; + } else { + // should never happen? + workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot() + .getFullPath().toString(); + } + String filename = workspaceLocation + fLocation.getFilename(); + PHPDocUtil.appendPHPDoc(hoverInfoBuffer, filename, fLocation); + return hoverInfoBuffer.toString(); + } + + public IContextInformation getContextInformation() { + if (fContextInfo == null) { + if (fLocation != null) { + fInfo = fLocation.getUsage(); + if (fInfo != null) { + // extract the parameter context information for the + // function: + int i0 = fInfo.indexOf('('); + int newline = fInfo.indexOf('\n'); + if (i0 >= 0 && (i0 < newline || newline < 0)) { + int i1 = fInfo.indexOf(')', i0 + 1); + if (i1 > 0) { + + fContextInfo = new ContextInformation(null, fInfo + .substring(i0 + 1, i1)); + } else { + fContextInfo = new ContextInformation(null, fInfo); + } + } else { + fContextInfo = new ContextInformation(null, fInfo); + } + } + } + } + return fContextInfo; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + String workspaceLocation; + String workspaceName; + if (fProject != null) { + workspaceLocation = fProject.getFullPath().toString() + '/'; + workspaceName = fProject.getName().toString() + '/'; + } else { + // should never happen? + workspaceLocation = PHPeclipsePlugin.getWorkspace().getRoot() + .getFullPath().toString(); + workspaceName = workspaceLocation; + } + String filename = fLocation.getFilename(); + String usage = PHPDocUtil.getUsage(workspaceLocation + filename, fLocation); + String result = fIdentifierName + + TemplateMessages.getString("TemplateProposal.delimiter"); + if (usage.length() > 0) { + result += usage + + TemplateMessages.getString("TemplateProposal.delimiter"); + } + result += workspaceName + filename; + return result; + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + switch (fLocation.getType()) { + case PHPIdentifierLocation.FUNCTION: + return PHPUiImages.get(PHPUiImages.IMG_FUN); + case PHPIdentifierLocation.CLASS: + return PHPUiImages.get(PHPUiImages.IMG_CLASS); + case PHPIdentifierLocation.CONSTRUCTOR: + return PHPUiImages.get(PHPUiImages.IMG_CLASS); + case PHPIdentifierLocation.METHOD: + return PHPUiImages.get(PHPUiImages.IMG_FUN); + case PHPIdentifierLocation.DEFINE: + return PHPUiImages.get(PHPUiImages.IMG_DEFINE); + case PHPIdentifierLocation.VARIABLE: + return PHPUiImages.get(PHPUiImages.IMG_VAR); + case PHPIdentifierLocation.GLOBAL_VARIABLE: + return PHPUiImages.get(PHPUiImages.IMG_VAR); + } + return PHPUiImages.get(PHPUiImages.IMG_FUN); + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + + if (fContext instanceof JavaContext) { + JavaContext context = (JavaContext) fContext; + switch (context.getCharacterBeforeStart()) { + // high relevance after whitespace + case ' ': + case '\r': + case '\n': + case '\t': + return 80; + case '>': // -> + case ':': // :: + return 85; + default: + return 0; + } + } else { + return 80; + } + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java new file mode 100644 index 0000000..2cd8210 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/LocalVariableProposal.java @@ -0,0 +1,143 @@ +package net.sourceforge.phpdt.internal.ui.text.template; + +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.swt.graphics.Image; + +/** + * A PHP local identifier proposal. + */ +public class LocalVariableProposal extends AbstractProposal { + + private final String fIdentifierName; + + private final IRegion fRegion; + + private final int fRelevance; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param image + * the icon of the proposal. + */ + public LocalVariableProposal(String identifierName, IRegion region, + ITextViewer viewer) { + this(identifierName, region, viewer, 99); + } + + public LocalVariableProposal(String identifierName, IRegion region, + ITextViewer viewer, int relevance) { + super(viewer); + fIdentifierName = identifierName; + fRegion = region; + fRelevance = relevance; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + // if (fTemplateBuffer == null) + // fTemplateBuffer= fContext.evaluate(fTemplate); + + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + + document.replace(start, end - start, fIdentifierName); + + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(fIdentifierName.length() + start); + editor.enter(); + + fSelectedRegion = editor.getSelectedRegion(); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + + } + // catch (CoreException e) { + // handleException(e); + // } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj instanceof LocalVariableProposal) { + return fIdentifierName + .equals(((LocalVariableProposal) obj).fIdentifierName); + } + return false; + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + StringBuffer hoverInfoBuffer = new StringBuffer(); + if (fRelevance > 95) { + hoverInfoBuffer.append("function source variable -"); + } else { + hoverInfoBuffer.append("editor source variable -"); + } + hoverInfoBuffer.append(fIdentifierName); + return hoverInfoBuffer.toString(); + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + return fIdentifierName; // $NON-NLS-1$ //$NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return PHPUiImages.get(PHPUiImages.IMG_VAR); + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + return fRelevance; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return fIdentifierName.hashCode(); + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java new file mode 100644 index 0000000..317e01c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/SQLProposal.java @@ -0,0 +1,141 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpdt.internal.ui.text.template; + +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.swt.graphics.Image; + +/** + * A PHP identifier proposal. + */ +public class SQLProposal extends AbstractProposal { + private final TemplateContext fContext; + + private final Image fImage_var; + + private final IRegion fRegion; + + private final String fColumnName; + + private final String fTableName; + + private int fRelevance; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param context + * the context in which the template was requested. + * @param image + * the icon of the proposal. + */ + public SQLProposal(String tableName, TemplateContext context, + IRegion region, ITextViewer viewer, Image image_var) { + super(viewer); + fTableName = tableName; + fColumnName = null; + fContext = context; + fImage_var = image_var; + fRegion = region; + fRelevance = 0; + } + + public SQLProposal(String tableName, String columnName, + TemplateContext context, IRegion region, ITextViewer viewer, + Image image_var) { + super(viewer); + fTableName = tableName; + fColumnName = columnName; + fContext = context; + fImage_var = image_var; + fRegion = region; + fRelevance = 0; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + try { + int start = fRegion.getOffset(); + int end = fRegion.getOffset() + fRegion.getLength(); + String resultString = fTableName; + if (fColumnName != null) { + resultString = fColumnName; + } + // insert template string + document.replace(start, end - start, resultString); + // translate positions + LinkedPositionManager manager = new LinkedPositionManager(document); + LinkedPositionUI editor = new LinkedPositionUI(fViewer, manager); + editor.setFinalCaretOffset(resultString.length() + start); + editor.enter(); + fSelectedRegion = editor.getSelectedRegion(); + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(e); + } + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + if (fColumnName == null) { + return textToHTML(fTableName); + } + return fColumnName + " (Table: " + fTableName + ")"; + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + if (fColumnName == null) { + return fTableName; + } + return fColumnName + " (Table: " + fTableName + ")"; // $NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return fImage_var; + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + return fRelevance; + } + + /** + * @param relevance + * The relevance to set. + */ + public void setRelevance(int relevance) { + fRelevance = relevance; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariable.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/MultiVariableGuess.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/PositionBasedCompletionProposal.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java new file mode 100644 index 0000000..9a39d38 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateEngine.java @@ -0,0 +1,170 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.template.contentassist; + +import java.util.ArrayList; + +import net.sourceforge.phpdt.core.ICompilationUnit; +//incastrix +//import net.sourceforge.phpdt.internal.corext.Assert; +import org.eclipse.core.runtime.Assert; +import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContext; +import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.templates.GlobalTemplateVariables; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.swt.graphics.Point; + +public class TemplateEngine { + + private static final String $_LINE_SELECTION = "${" + GlobalTemplateVariables.LineSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$ + + private static final String $_WORD_SELECTION = "${" + GlobalTemplateVariables.WordSelection.NAME + "}"; //$NON-NLS-1$ //$NON-NLS-2$ + + /** The context type. */ + private TemplateContextType fContextType; + + /** The result proposals. */ + private ArrayList fProposals = new ArrayList(); + + /** + * Creates the template engine for a particular context type. See + * TemplateContext for supported context types. + */ + public TemplateEngine(TemplateContextType contextType) { + Assert.isNotNull(contextType); + fContextType = contextType; + } + + /** + * Empties the collector. + */ + public void reset() { + fProposals.clear(); + } + + /** + * Returns the array of matching templates. + */ + public TemplateProposal[] getResults() { + return (TemplateProposal[]) fProposals + .toArray(new TemplateProposal[fProposals.size()]); + } + + /** + * Inspects the context of the compilation unit around + * completionPosition and feeds the collector with proposals. + * + * @param viewer + * the text viewer + * @param completionPosition + * the context position in the document of the text viewer + * @param compilationUnit + * the compilation unit (may be null) + */ + public void complete(ITextViewer viewer, int completionPosition, + ICompilationUnit compilationUnit) { + IDocument document = viewer.getDocument(); + + if (!(fContextType instanceof CompilationUnitContextType)) + return; + + Point selection = viewer.getSelectedRange(); + + // remember selected text + String selectedText = null; + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + CompilationUnitContext context = ((CompilationUnitContextType) fContextType) + .createContext(document, completionPosition, selection.y, + compilationUnit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + int start = context.getStart(); + int end = context.getEnd(); + IRegion region = new Region(start, end - start); + + Template[] templates = PHPeclipsePlugin.getDefault().getTemplateStore() + .getTemplates(); + + if (selection.y == 0) { + for (int i = 0; i != templates.length; i++) + if (context.canEvaluate(templates[i])) + fProposals.add(new TemplateProposal(templates[i], context, + region, PHPUiImages + .get(PHPUiImages.IMG_OBJS_TEMPLATE))); + + } else { + + if (context.getKey().length() == 0) + context.setForceEvaluation(true); + + boolean multipleLinesSelected = areMultipleLinesSelected(viewer); + + for (int i = 0; i != templates.length; i++) { + Template template = templates[i]; + if (context.canEvaluate(template) + && template.getContextTypeId().equals( + context.getContextType().getId()) + && (!multipleLinesSelected + && template.getPattern().indexOf( + $_WORD_SELECTION) != -1 || (multipleLinesSelected && template + .getPattern().indexOf($_LINE_SELECTION) != -1))) { + fProposals.add(new TemplateProposal(templates[i], context, + region, PHPUiImages + .get(PHPUiImages.IMG_OBJS_TEMPLATE))); + } + } + } + } + + /** + * Returns true if one line is completely selected or if + * multiple lines are selected. Being completely selected means that all + * characters except the new line characters are selected. + * + * @return true if one or multiple lines are selected + * @since 2.1 + */ + private boolean areMultipleLinesSelected(ITextViewer viewer) { + if (viewer == null) + return false; + + Point s = viewer.getSelectedRange(); + if (s.y == 0) + return false; + + try { + + IDocument document = viewer.getDocument(); + int startLine = document.getLineOfOffset(s.x); + int endLine = document.getLineOfOffset(s.x + s.y); + IRegion line = document.getLineInformation(startLine); + return startLine != endLine + || (s.x == line.getOffset() && s.y == line.getLength()); + + } catch (BadLocationException x) { + return false; + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java new file mode 100644 index 0000000..15ea398 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/TemplateProposal.java @@ -0,0 +1,478 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.template.contentassist; + +import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContext; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.EditorHighlightingSynchronizer; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.MessageDialog; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.BadPositionCategoryException; +import org.eclipse.jface.text.DocumentEvent; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; +import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.link.ILinkedModeListener; +import org.eclipse.jface.text.link.LinkedModeModel; +import org.eclipse.jface.text.link.LinkedModeUI; +import org.eclipse.jface.text.link.LinkedPosition; +import org.eclipse.jface.text.link.LinkedPositionGroup; +import org.eclipse.jface.text.link.ProposalPosition; +import org.eclipse.jface.text.templates.DocumentTemplateContext; +import org.eclipse.jface.text.templates.GlobalTemplateVariables; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateBuffer; +import org.eclipse.jface.text.templates.TemplateContext; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.TemplateVariable; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; + +/** + * A template proposal. + */ +public class TemplateProposal implements IPHPCompletionProposal, + ICompletionProposalExtension2, ICompletionProposalExtension3 { + + private final Template fTemplate; + + private final TemplateContext fContext; + + private final Image fImage; + + private IRegion fRegion; + + private int fRelevance; + + private IRegion fSelectedRegion; // initialized by apply() + + private String fDisplayString; + + /** + * Creates a template proposal with a template and its context. + * + * @param template + * the template + * @param context + * the context in which the template was requested + * @param region + * the region this proposal applies to + * @param image + * the icon of the proposal + */ + public TemplateProposal(Template template, TemplateContext context, + IRegion region, Image image) { + Assert.isNotNull(template); + Assert.isNotNull(context); + Assert.isNotNull(region); + + fTemplate = template; + fContext = context; + fImage = image; + fRegion = region; + + fDisplayString = null; + + if (context instanceof JavaContext) { + switch (((JavaContext) context).getCharacterBeforeStart()) { + // high relevance after whitespace + case ' ': + case '\r': + case '\n': + case '\t': + fRelevance = 90; + break; + default: + fRelevance = 0; + } + } else { + fRelevance = 90; + } + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public final void apply(IDocument document) { + // not called anymore + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, + * char, int, int) + */ + public void apply(ITextViewer viewer, char trigger, int stateMask, + int offset) { + + try { + + fContext.setReadOnly(false); + TemplateBuffer templateBuffer; + try { + templateBuffer = fContext.evaluate(fTemplate); + } catch (TemplateException e1) { + fSelectedRegion = fRegion; + return; + } + + int start = getReplaceOffset(); + int end = getReplaceEndOffset(); + end = Math.max(end, offset); + + // insert template string + IDocument document = viewer.getDocument(); + String templateString = templateBuffer.getString(); + document.replace(start, end - start, templateString); + + // translate positions + LinkedModeModel model = new LinkedModeModel(); + TemplateVariable[] variables = templateBuffer.getVariables(); + + MultiVariableGuess guess = fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext) + .getMultiVariableGuess() + : null; + + boolean hasPositions = false; + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + + if (variable.isUnambiguous()) + continue; + + LinkedPositionGroup group = new LinkedPositionGroup(); + + int[] offsets = variable.getOffsets(); + int length = variable.getLength(); + + LinkedPosition first; + if (guess != null && variable instanceof MultiVariable) { + first = new VariablePosition(document, offsets[0] + start, + length, guess, (MultiVariable) variable); + guess.addSlave((VariablePosition) first); + } else { + String[] values = variable.getValues(); + ICompletionProposal[] proposals = new ICompletionProposal[values.length]; + for (int j = 0; j < values.length; j++) { + ensurePositionCategoryInstalled(document, model); + Position pos = new Position(offsets[0] + start, length); + document.addPosition(getCategory(), pos); + proposals[j] = new PositionBasedCompletionProposal( + values[j], pos, length); + } + + if (proposals.length > 1) + first = new ProposalPosition(document, offsets[0] + + start, length, proposals); + else + first = new LinkedPosition(document, + offsets[0] + start, length); + } + + for (int j = 0; j != offsets.length; j++) + if (j == 0) + group.addPosition(first); + else + group.addPosition(new LinkedPosition(document, + offsets[j] + start, length)); + + model.addGroup(group); + hasPositions = true; + } + + if (hasPositions) { + model.forceInstall(); + PHPEditor editor = getJavaEditor(); + if (editor != null) { + model + .addLinkingListener(new EditorHighlightingSynchronizer( + editor)); + } + + LinkedModeUI ui = new EditorLinkedModeUI(model, viewer); + ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + + start, 0, Integer.MAX_VALUE); + ui.enter(); + + fSelectedRegion = ui.getSelectedRegion(); + } else + fSelectedRegion = new Region(getCaretOffset(templateBuffer) + + start, 0); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(viewer.getTextWidget().getShell(), e); + fSelectedRegion = fRegion; + } catch (BadPositionCategoryException e) { + PHPeclipsePlugin.log(e); + openErrorDialog(viewer.getTextWidget().getShell(), e); + fSelectedRegion = fRegion; + } + + } + + /** + * Returns the currently active java editor, or null if it + * cannot be determined. + * + * @return the currently active java editor, or null + */ + private PHPEditor getJavaEditor() { + IEditorPart part = PHPeclipsePlugin.getActivePage().getActiveEditor(); + if (part instanceof PHPEditor) + return (PHPEditor) part; + else + return null; + } + + /** + * Returns the offset of the range in the document that will be replaced by + * applying this template. + * + * @return the offset of the range in the document that will be replaced by + * applying this template + */ + private int getReplaceOffset() { + int start; + if (fContext instanceof DocumentTemplateContext) { + DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; + start = docContext.getStart(); + } else { + start = fRegion.getOffset(); + } + return start; + } + + /** + * Returns the end offset of the range in the document that will be replaced + * by applying this template. + * + * @return the end offset of the range in the document that will be replaced + * by applying this template + */ + private int getReplaceEndOffset() { + int end; + if (fContext instanceof DocumentTemplateContext) { + DocumentTemplateContext docContext = (DocumentTemplateContext) fContext; + end = docContext.getEnd(); + } else { + end = fRegion.getOffset() + fRegion.getLength(); + } + return end; + } + + private void ensurePositionCategoryInstalled(final IDocument document, + LinkedModeModel model) { + if (!document.containsPositionCategory(getCategory())) { + document.addPositionCategory(getCategory()); + final InclusivePositionUpdater updater = new InclusivePositionUpdater( + getCategory()); + document.addPositionUpdater(updater); + + model.addLinkingListener(new ILinkedModeListener() { + + /* + * @see org.eclipse.jface.text.link.ILinkedModeListener#left(org.eclipse.jface.text.link.LinkedModeModel, + * int) + */ + public void left(LinkedModeModel environment, int flags) { + try { + document.removePositionCategory(getCategory()); + } catch (BadPositionCategoryException e) { + // ignore + } + document.removePositionUpdater(updater); + } + + public void suspend(LinkedModeModel environment) { + } + + public void resume(LinkedModeModel environment, int flags) { + } + }); + } + } + + private String getCategory() { + return "TemplateProposalCategory_" + toString(); //$NON-NLS-1$ + } + + private int getCaretOffset(TemplateBuffer buffer) { + + TemplateVariable[] variables = buffer.getVariables(); + for (int i = 0; i != variables.length; i++) { + TemplateVariable variable = variables[i]; + if (variable.getType().equals(GlobalTemplateVariables.Cursor.NAME)) + return variable.getOffsets()[0]; + } + + return buffer.getString().length(); + } + + /* + * @see ICompletionProposal#getSelection(IDocument) + */ + public Point getSelection(IDocument document) { + return new Point(fSelectedRegion.getOffset(), fSelectedRegion + .getLength()); + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + try { + fContext.setReadOnly(true); + TemplateBuffer templateBuffer; + try { + templateBuffer = fContext.evaluate(fTemplate); + } catch (TemplateException e1) { + return null; + } + + return templateBuffer.getString(); + + } catch (BadLocationException e) { + handleException(PHPeclipsePlugin.getActiveWorkbenchShell(), + new CoreException(new Status(IStatus.ERROR, + PHPeclipsePlugin.getPluginId(), IStatus.OK, "", e))); //$NON-NLS-1$ + return null; + } + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + if (fDisplayString == null) { + fDisplayString = fTemplate.getName() + + TemplateContentAssistMessages + .getString("TemplateProposal.delimiter") + fTemplate.getDescription(); //$NON-NLS-1$ + } + return fDisplayString; + } + +// public void setDisplayString(String displayString) { +// fDisplayString = displayString; +// } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return fImage; + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } + + private void openErrorDialog(Shell shell, Exception e) { + MessageDialog.openError(shell, TemplateContentAssistMessages + .getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ + } + + private void handleException(Shell shell, CoreException e) { + ExceptionHandler.handle(e, shell, TemplateContentAssistMessages + .getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ + } + + /* + * @see IJavaCompletionProposal#getRelevance() + */ + public int getRelevance() { + return fRelevance; + } + +// public void setRelevance(int relevance) { +// fRelevance = relevance; +// } + +// public Template getTemplate() { +// return fTemplate; +// } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator() + */ + public IInformationControlCreator getInformationControlCreator() { + return new TemplateInformationControlCreator(); + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, + * boolean) + */ + public void selected(ITextViewer viewer, boolean smartToggle) { + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) + */ + public void unselected(ITextViewer viewer) { + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, + * int, org.eclipse.jface.text.DocumentEvent) + */ + public boolean validate(IDocument document, int offset, DocumentEvent event) { + try { + int replaceOffset = getReplaceOffset(); + if (offset >= replaceOffset) { + String content = document.get(replaceOffset, offset + - replaceOffset); + return fTemplate.getName().startsWith(content); + } + } catch (BadLocationException e) { + // concurrent modification - ignore + } + return false; + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementString() + */ + public CharSequence getPrefixCompletionText(IDocument document, + int completionOffset) { + return fTemplate.getName(); + } + + /* + * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementOffset() + */ + public int getPrefixCompletionStart(IDocument document, int completionOffset) { + return getReplaceOffset(); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/contentassist/VariablePosition.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProcessor.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java new file mode 100644 index 0000000..13ec454 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/preferences/TemplateVariableProposal.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.text.template.preferences; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.templates.TemplateVariableResolver; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Shell; + +/** + * A proposal for insertion of template variables. + */ +public class TemplateVariableProposal implements ICompletionProposal { + + private TemplateVariableResolver fVariable; + + private int fOffset; + + private int fLength; + + private ITextViewer fViewer; + + private Point fSelection; + + /** + * Creates a template variable proposal. + * + * @param variable + * the template variable + * @param offset + * the offset to replace + * @param length + * the length to replace + * @param viewer + * the viewer + */ + public TemplateVariableProposal(TemplateVariableResolver variable, + int offset, int length, ITextViewer viewer) { + fVariable = variable; + fOffset = offset; + fLength = length; + fViewer = viewer; + } + + /* + * @see ICompletionProposal#apply(IDocument) + */ + public void apply(IDocument document) { + + try { + String variable = fVariable.getType().equals("dollar") ? "$$" : "${" + fVariable.getType() + '}'; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + document.replace(fOffset, fLength, variable); + fSelection = new Point(fOffset + variable.length(), 0); + + } catch (BadLocationException e) { + PHPeclipsePlugin.log(e); + + Shell shell = fViewer.getTextWidget().getShell(); + MessageDialog + .openError( + shell, + TemplatePreferencesMessages + .getString("TemplateVariableProposal.error.title"), e.getMessage()); //$NON-NLS-1$ + } + } + + /* + * @see ICompletionProposal#getSelection(IDocument) + */ + public Point getSelection(IDocument document) { + return fSelection; + } + + /* + * @see ICompletionProposal#getAdditionalProposalInfo() + */ + public String getAdditionalProposalInfo() { + return null; + } + + /* + * @see ICompletionProposal#getDisplayString() + */ + public String getDisplayString() { + return fVariable.getType() + " - " + fVariable.getDescription(); //$NON-NLS-1$ + } + + /* + * @see ICompletionProposal#getImage() + */ + public Image getImage() { + return null; + } + + /* + * @see ICompletionProposal#getContextInformation() + */ + public IContextInformation getContextInformation() { + return null; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/DirectorySelector.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java new file mode 100644 index 0000000..11c733f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ExceptionHandler.java @@ -0,0 +1,85 @@ +package net.sourceforge.phpdt.internal.ui.util; + +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.swt.widgets.Shell; + +public class ExceptionHandler { + private static ExceptionHandler fgInstance = new ExceptionHandler(); + + public static void log(Throwable t, String message) { + PHPeclipsePlugin.getDefault().getLog().log( + new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + IStatus.ERROR, message, t)); + } + +// public static void handle(CoreException e, String title, String message) { +// handle(e, PHPeclipsePlugin.getActiveWorkbenchShell(), title, message); +// } + + public static void handle(CoreException e, Shell parent, String title, + String message) { + fgInstance.perform(e, parent, title, message); + } + +// public static void handle(InvocationTargetException e, String title, +// String message) { +// handle(e, PHPeclipsePlugin.getActiveWorkbenchShell(), title, message); +// } + + public static void handle(InvocationTargetException e, Shell parent, + String title, String message) { + fgInstance.perform(e, parent, title, message); + } + + protected void perform(CoreException e, Shell shell, String title, + String message) { + PHPeclipsePlugin.log(e); + IStatus status = e.getStatus(); + if (status != null) { + ErrorDialog.openError(shell, title, message, status); + } else { + displayMessageDialog(e, e.getMessage(), shell, title, message); + } + } + + protected void perform(InvocationTargetException e, Shell shell, + String title, String message) { + Throwable target = e.getTargetException(); + if (target instanceof CoreException) { + perform((CoreException) target, shell, title, message); + } else { + PHPeclipsePlugin.log(e); + if (e.getMessage() != null && e.getMessage().length() > 0) { + displayMessageDialog(e, e.getMessage(), shell, title, message); + } else { + displayMessageDialog(e, target.getMessage(), shell, title, + message); + } + } + } + + private void displayMessageDialog(Throwable t, String exceptionMessage, + Shell shell, String title, String message) { + StringWriter msg = new StringWriter(); + if (message != null) { + msg.write(message); + msg.write("\n\n"); + } + if (exceptionMessage == null || exceptionMessage.length() == 0) + msg.write(PHPUIMessages + .getString("ExceptionDialog.seeErrorLogMessage")); + else + msg.write(exceptionMessage); + MessageDialog.openError(shell, title, msg.toString()); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/FilteredList.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPElementVisitor.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java new file mode 100644 index 0000000..94a266a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileSelector.java @@ -0,0 +1,114 @@ +package net.sourceforge.phpdt.internal.ui.util; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.dialogs.ElementListSelectionDialog; +import org.eclipse.ui.model.IWorkbenchAdapter; + +public class PHPFileSelector extends ResourceSelector { + static class FileLabelProvider extends LabelProvider { + /** + * Returns the implementation of IWorkbenchAdapter for the given object. + * + * @param o + * the object to look up. + * @return IWorkbenchAdapter or null if the adapter is + * not defined or the object is not adaptable. + */ + protected final IWorkbenchAdapter getAdapter(Object o) { + if (!(o instanceof IAdaptable)) { + return null; + } + return (IWorkbenchAdapter) ((IAdaptable) o) + .getAdapter(IWorkbenchAdapter.class); + } + + /* + * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element instanceof IFile) { + // query the element for its label + IWorkbenchAdapter adapter = getAdapter(element); + if (adapter == null) { + return ""; //$NON-NLS-1$ + } + String filename = adapter.getLabel(element); + IPath path = ((IFile) element).getFullPath(); + String filePathname = path != null ? path.toString() : ""; //$NON-NLS-1$ + return filename + " (" + filePathname + ")"; + } + return super.getText(element); + } + } + + protected PHPProjectSelector phpProjectSelector; + + public PHPFileSelector(Composite parent, PHPProjectSelector aProjectSelector) { + super(parent); + Assert.isNotNull(aProjectSelector); + phpProjectSelector = aProjectSelector; + + browseDialogTitle = "File Selection"; + } + + protected Object[] getPHPFiles() { + IProject phpProject = phpProjectSelector.getSelection(); + if (phpProject == null) + return new Object[0]; + + PHPElementVisitor visitor = new PHPElementVisitor(); + try { + phpProject.accept(visitor); + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + return visitor.getCollectedPHPFiles(); + } + + public IFile getSelection() { + String fileName = getSelectionText(); + if (fileName != null && !fileName.equals("")) { + IPath filePath = new Path(fileName); + IProject project = phpProjectSelector.getSelection(); + if (project != null && project.exists(filePath)) + return project.getFile(filePath); + } + + return null; + } + + protected void handleBrowseSelected() { + // ElementListSelectionDialog dialog = new + // ElementListSelectionDialog(getShell(), new WorkbenchLabelProvider()); + ElementListSelectionDialog dialog = new ElementListSelectionDialog( + getShell(), new FileLabelProvider()); + + dialog.setTitle(browseDialogTitle); + dialog.setMessage(browseDialogMessage); + dialog.setElements(getPHPFiles()); + + if (dialog.open() == ElementListSelectionDialog.OK) { + textField.setText(((IResource) dialog.getFirstResult()) + .getProjectRelativePath().toString()); + } + } + + protected String validateResourceSelection() { + IFile selection = getSelection(); + return selection == null ? EMPTY_STRING : selection + .getProjectRelativePath().toString(); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java new file mode 100644 index 0000000..b571a1c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java @@ -0,0 +1,213 @@ +/* + * Created on 09.08.2003 + * + */ + +/*duplicated incastrix*/ +package net.sourceforge.phpdt.internal.ui.util; + +import java.io.File; +import java.util.List; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil; + +import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.PlatformUI; + +public class PHPFileUtil { + // private static String[] PHP_EXTENSIONS = null; + + public final static String[] SMARTY_EXTENSIONS = { "tpl" }; + + public static boolean isPHPFile(IFile file) { + return isPHPFileName(file.getFullPath().toString()); + } + + // public final static String getFileExtension(String name) { + // int index = name.lastIndexOf('.'); + // if (index == -1) + // return null; + // if (index == (name.length() - 1)) + // return null; //$NON-NLS-1$ + // return name.substring(index + 1); + // } + + /** + * Returns true iff str.toLowerCase().endsWith(".php") implementation is not + * creating extra strings. + */ + public final static boolean isPHPFileName(String name) { + + // avoid handling a file without base name, e.g. ".php", which is a + // valid + // Eclipse resource name + File file = new File(name); + if (file.getName().startsWith(".")) { + return false; + } + IWorkbench workbench = PlatformUI.getWorkbench(); + IEditorRegistry registry = workbench.getEditorRegistry(); + IEditorDescriptor[] descriptors = registry.getEditors(name); + + for (int i = 0; i < descriptors.length; i++) { + if (descriptors[i].getId().equals(PHPeclipsePlugin.EDITOR_ID)) { + return true; + } + } + // String extension = getFileExtension(name); + // if (extension == null) { + // return false; + // } + // extension = extension.toLowerCase(); + // PHP_EXTENSIONS = getExtensions(); + // if (PHP_EXTENSIONS == null) { + // return false; + // } + // for (int i = 0; i < PHP_EXTENSIONS.length; i++) { + // if (extension.equals(PHP_EXTENSIONS[i])) { + // return true; + // } + // } + return false; + } + + /** + * Returns true iff the file extension is a valid PHP Unit name + * implementation is not creating extra strings. + */ +// public final static boolean isValidPHPUnitName(String filename) { +// return PHPFileUtil.isPHPFileName(filename); +// } + + /** + * @return Returns the PHP extensions. + */ + // public static String[] getExtensions() { + // if (PHP_EXTENSIONS == null) { + // ArrayList list = new ArrayList(); + // final IPreferenceStore store = + // PHPeclipsePlugin.getDefault().getPreferenceStore(); + // String extensions = + // store.getString(PHPeclipsePlugin.PHP_EXTENSION_PREFS); + // extensions = extensions.trim(); + // if (extensions.length() != 0) { + // StringTokenizer tokenizer = new StringTokenizer(extensions, " ,;:/-|"); + // String token; + // while (tokenizer.hasMoreTokens()) { + // token = tokenizer.nextToken(); + // if (token != null && token.length() >= 1) { + // list.add(token); + // } + // } + // if (list.size() != 0) { + // PHP_EXTENSIONS = new String[list.size()]; + // for (int i = 0; i < list.size(); i++) { + // PHP_EXTENSIONS[i] = (String) list.get(i); + // } + // } + // } + // } + // return PHP_EXTENSIONS; + // } + /** + * @param php_extensions + * The PHP extensions to set. + */ + // public static void setExtensions(String[] php_extensions) { + // PHP_EXTENSIONS = php_extensions; + // } + /** + * Creata the file for the given absolute file path + * + * @param absoluteFilePath + * @param project + * @return the file for the given absolute file path or null + * if no existing file can be found + */ +// public static IFile createFile(IPath absoluteFilePath, IProject project) { +// if (absoluteFilePath == null || project == null) { +// return null; +// } +// +// String projectPath = project.getFullPath().toString(); +// String filePath = absoluteFilePath.toString().substring( +// projectPath.length() + 1); +// return project.getFile(filePath); +// +// } + + /** + * Determine the path of an include name string + * + * @param includeNameString + * @param resource + * @param project + * @return the path for the given include filename or null if + * no existing file can be found + */ + public static IPath determineFilePath(String includeNameString, + IResource resource, IProject project) { + IPath documentRootPath = ProjectPrefUtil.getDocumentRoot(project); + IPath resourcePath = resource.getProjectRelativePath(); + + IPath path = null; + + // script location based + path = project.getFullPath().append(resourcePath.removeLastSegments(1)) + .append(includeNameString); + //path = + if (fileExists(path, false)) { + return path; + } + // project root based + path = project.getFullPath().append(includeNameString); + if (fileExists(path, false)) { + return path; + } + + // DocumentRoot (absolute path) based + path = documentRootPath.append(includeNameString); + if (fileExists(path, true)) { + return path; + } + + // IncludePaths settings (absolute path) based + List includePaths = ProjectPrefUtil.getIncludePaths(project); + if (includePaths.size() > 0) { + for (int i = 0; i < includePaths.size(); i++) { + path = new Path(includePaths.get(i).toString()) + .append(includeNameString); + if (fileExists(path, true)) { + return path; + } + } + } + return null; + } + + private static boolean fileExists(IPath path, boolean absolute) { + File file = path.toFile(); + if (file.exists()) { + return true; + } + if (!absolute) { + IFile ifile = FileBuffers.getWorkspaceFileAtLocation(path); + if (ifile != null) { + IResource resource = ifile; + if (resource.exists()) { + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java new file mode 100644 index 0000000..b33471e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPProjectSelector.java @@ -0,0 +1,44 @@ +package net.sourceforge.phpdt.internal.ui.util; + +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IProject; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.dialogs.ElementListSelectionDialog; +import org.eclipse.ui.model.WorkbenchLabelProvider; + +public class PHPProjectSelector extends ResourceSelector { + + public PHPProjectSelector(Composite parent) { + super(parent); + + browseDialogTitle = "Project Selection"; + } + + public IProject getSelection() { + String projectName = getSelectionText(); + if (projectName != null && !projectName.equals("")) + return PHPeclipsePlugin.getWorkspace().getRoot().getProject( + projectName); + + return null; + } + + protected void handleBrowseSelected() { + ElementListSelectionDialog dialog = new ElementListSelectionDialog( + getShell(), new WorkbenchLabelProvider()); + dialog.setTitle(browseDialogTitle); + dialog.setMessage(browseDialogMessage); + dialog.setElements(JavaCore.getPHPProjects()); + + if (dialog.open() == ElementListSelectionDialog.OK) { + textField.setText(((IProject) dialog.getFirstResult()).getName()); + } + } + + protected String validateResourceSelection() { + IProject project = getSelection(); + return project == null ? EMPTY_STRING : project.getName(); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PixelConverter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/ResourceSelector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StreamUtil.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/StringMatcher.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TabFolderLayout.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TableLayoutComposite.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TableLayoutComposite.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TableLayoutComposite.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TableLayoutComposite.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/TwoArrayQuickSorter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ContainerCheckedTreeViewer.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/FilterUpdater.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ISelectionListenerWithAST.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IViewPartInputProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageDescriptorRegistry.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java new file mode 100644 index 0000000..b3cecff --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java @@ -0,0 +1,461 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.viewsupport; + +import net.sourceforge.phpdt.core.Flags; +import net.sourceforge.phpdt.core.IField; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.IMethod; +//import net.sourceforge.phpdt.core.IPackageFragmentRoot; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.ui.PHPUIMessages; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.ui.JavaElementImageDescriptor; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.jface.resource.ImageDescriptor; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +//import org.eclipse.ui.ISharedImages; +//import org.eclipse.ui.ide.IDE.SharedImages; +import org.eclipse.ui.model.IWorkbenchAdapter; + +/** + * Default strategy of the Java plugin for the construction of Java element + * icons. + */ +public class JavaElementImageProvider { + + /** + * Flags for the JavaImageLabelProvider: Generate images with overlays. + */ + public final static int OVERLAY_ICONS = 0x1; + + /** + * Generate small sized images. + */ + public final static int SMALL_ICONS = 0x2; + + /** + * Use the 'light' style for rendering types. + */ + public final static int LIGHT_TYPE_ICONS = 0x4; + + public static final Point SMALL_SIZE = new Point(16, 16); + + public static final Point BIG_SIZE = new Point(22, 16); + + private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; + + private static ImageDescriptor DESC_OBJ_PROJECT; + +// private static ImageDescriptor DESC_OBJ_FOLDER; +// { +// ISharedImages images = PHPeclipsePlugin.getDefault().getWorkbench() +// .getSharedImages(); +// DESC_OBJ_PROJECT_CLOSED = images +// .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT_CLOSED); +// DESC_OBJ_PROJECT = images +// .getImageDescriptor(SharedImages.IMG_OBJ_PROJECT); +// DESC_OBJ_FOLDER = images +// .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); +// } + + private ImageDescriptorRegistry fRegistry; + + public JavaElementImageProvider() { + fRegistry = null; // lazy initialization + } + + /** + * Returns the icon for a given element. The icon depends on the element + * type and element properties. If configured, overlay icons are constructed + * for ISourceReferences. + * + * @param flags + * Flags as defined by the JavaImageLabelProvider + */ + public Image getImageLabel(Object element, int flags) { + return getImageLabel(computeDescriptor(element, flags)); + } + + private Image getImageLabel(ImageDescriptor descriptor) { + if (descriptor == null) + return null; + return getRegistry().get(descriptor); + } + + private ImageDescriptorRegistry getRegistry() { + if (fRegistry == null) { + fRegistry = PHPeclipsePlugin.getImageDescriptorRegistry(); + } + return fRegistry; + } + + private ImageDescriptor computeDescriptor(Object element, int flags) { + if (element instanceof IJavaElement) { + return getJavaImageDescriptor((IJavaElement) element, flags); + } else if (element instanceof IFile) { + IFile file = (IFile) element; + if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$ + return getCUResourceImageDescriptor(file, flags); // image for + // a CU not + // on the + // build + // path + } + return getWorkbenchImageDescriptor(file, flags); + } else if (element instanceof IAdaptable) { + return getWorkbenchImageDescriptor((IAdaptable) element, flags); + } + return null; + } + + private static boolean showOverlayIcons(int flags) { + return (flags & OVERLAY_ICONS) != 0; + } + + private static boolean useSmallSize(int flags) { + return (flags & SMALL_ICONS) != 0; + } + + private static boolean useLightIcons(int flags) { + return (flags & LIGHT_TYPE_ICONS) != 0; + } + + /** + * Returns an image descriptor for a compilatio unit not on the class path. + * The descriptor includes overlays, if specified. + */ + public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) { + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor( + PHPUiImages.DESC_OBJS_CUNIT_RESOURCE, 0, size); + } + + /** + * Returns an image descriptor for a java element. The descriptor includes + * overlays, if specified. + */ + public ImageDescriptor getJavaImageDescriptor(IJavaElement element, + int flags) { + int adornmentFlags = computeJavaAdornmentFlags(element, flags); + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor(getBaseImageDescriptor(element, + flags), adornmentFlags, size); + } + + /** + * Returns an image descriptor for a IAdaptable. The descriptor includes + * overlays, if specified (only error ticks apply). Returns + * null if no image could be found. + */ + public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, + int flags) { + IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) adaptable + .getAdapter(IWorkbenchAdapter.class); + if (wbAdapter == null) { + return null; + } + ImageDescriptor descriptor = wbAdapter.getImageDescriptor(adaptable); + if (descriptor == null) { + return null; + } + + Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; + return new JavaElementImageDescriptor(descriptor, 0, size); + } + + // ---- Computation of base image key + // ------------------------------------------------- + + /** + * Returns an image descriptor for a java element. This is the base image, + * no overlays. + */ + public ImageDescriptor getBaseImageDescriptor(IJavaElement element, + int renderFlags) { + IType type = null; + boolean isInterface = false; + try { + switch (element.getElementType()) { + case IJavaElement.INITIALIZER: + return PHPUiImages.DESC_MISC_PRIVATE; // 23479 + case IJavaElement.METHOD: + IMember member = (IMember) element; + type = member.getDeclaringType(); + isInterface = (type != null) + && member.getDeclaringType().isInterface(); + return getMethodImageDescriptor(isInterface, member.getFlags()); + case IJavaElement.FIELD: + IField field = (IField) element; + return getFieldImageDescriptor(field.getDeclaringType() + .isInterface(), field.getFlags()); + + case IJavaElement.PACKAGE_DECLARATION: + return PHPUiImages.DESC_OBJS_PACKDECL; + + case IJavaElement.IMPORT_DECLARATION: + return PHPUiImages.DESC_OBJS_IMPDECL; + + case IJavaElement.IMPORT_CONTAINER: + return PHPUiImages.DESC_OBJS_IMPCONT; + + case IJavaElement.TYPE: { + type = (IType) element; + isInterface = type.isInterface(); + + if (useLightIcons(renderFlags)) { + return isInterface ? PHPUiImages.DESC_OBJS_INTERFACEALT + : PHPUiImages.DESC_OBJS_CLASSALT; + } + boolean isInner = type.getDeclaringType() != null; + return getTypeImageDescriptor(isInterface, isInner, type + .getFlags()); + } + + case IJavaElement.PACKAGE_FRAGMENT_ROOT: { + //IPackageFragmentRoot root = (IPackageFragmentRoot) element; + // if (root.isArchive()) { + // IPath attach= root.getSourceAttachmentPath(); + // if (root.isExternal()) { + // if (attach == null) { + // return PHPUiImages.DESC_OBJS_EXTJAR; + // } else { + // return PHPUiImages.DESC_OBJS_EXTJAR_WSRC; + // } + // } else { + // if (attach == null) { + // return PHPUiImages.DESC_OBJS_JAR; + // } else { + // return PHPUiImages.DESC_OBJS_JAR_WSRC; + // } + // } + // } else { + return PHPUiImages.DESC_OBJS_PACKFRAG_ROOT; + // } + } + + case IJavaElement.PACKAGE_FRAGMENT: + return getPackageFragmentIcon(element, renderFlags); + + case IJavaElement.COMPILATION_UNIT: + return PHPUiImages.DESC_OBJS_CUNIT; + + case IJavaElement.CLASS_FILE: + /* + * this is too expensive for large packages try { IClassFile + * cfile= (IClassFile)element; if (cfile.isClass()) return + * PHPUiImages.IMG_OBJS_CFILECLASS; return + * PHPUiImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // + * fall through; } + */ + return PHPUiImages.DESC_OBJS_CFILE; + + case IJavaElement.JAVA_PROJECT: + IJavaProject jp = (IJavaProject) element; + if (jp.getProject().isOpen()) { + IProject project = jp.getProject(); + IWorkbenchAdapter adapter = (IWorkbenchAdapter) project + .getAdapter(IWorkbenchAdapter.class); + if (adapter != null) { + ImageDescriptor result = adapter + .getImageDescriptor(project); + if (result != null) + return result; + } + return DESC_OBJ_PROJECT; + } + return DESC_OBJ_PROJECT_CLOSED; + + case IJavaElement.JAVA_MODEL: + return PHPUiImages.DESC_OBJS_JAVA_MODEL; + } + + Assert.isTrue(false, PHPUIMessages + .getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ + return null; //$NON-NLS-1$ + + } catch (JavaModelException e) { + if (e.isDoesNotExist()) + return PHPUiImages.DESC_OBJS_UNKNOWN; + PHPeclipsePlugin.log(e); + return PHPUiImages.DESC_OBJS_GHOST; + } + } + + protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, + int renderFlags) throws JavaModelException { + // IPackageFragment fragment= (IPackageFragment)element; + // boolean containsJavaElements= false; + // try { + // containsJavaElements= fragment.hasChildren(); + // } catch(JavaModelException e) { + // // assuming no children; + // } + // if(!containsJavaElements && (fragment.getNonJavaResources().length > + // 0)) + // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES; + // else if (!containsJavaElements) + // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE; + return PHPUiImages.DESC_OBJS_PACKAGE; + } + + public void dispose() { + } + + // ---- Methods to compute the adornments flags + // --------------------------------- + + private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { + int flags = 0; + if (showOverlayIcons(renderFlags) && element instanceof IMember) { + try { + IMember member = (IMember) element; + + if (element.getElementType() == IJavaElement.METHOD + && ((IMethod) element).isConstructor()) + flags |= JavaElementImageDescriptor.CONSTRUCTOR; + + int modifiers = member.getFlags(); + if (Flags.isAbstract(modifiers) && confirmAbstract(member)) + flags |= JavaElementImageDescriptor.ABSTRACT; + if (Flags.isFinal(modifiers) || isInterfaceField(member)) + flags |= JavaElementImageDescriptor.FINAL; + // if (Flags.isSynchronized(modifiers) && + // confirmSynchronized(member)) + // flags |= JavaElementImageDescriptor.SYNCHRONIZED; + if (Flags.isStatic(modifiers) || isInterfaceField(member)) + flags |= JavaElementImageDescriptor.STATIC; + + // if (member.getElementType() == IJavaElement.TYPE) { + // if (JavaModelUtil.hasMainMethod((IType) member)) { + // flags |= JavaElementImageDescriptor.RUNNABLE; + // } + // } + } catch (JavaModelException e) { + // do nothing. Can't compute runnable adornment or get flags + } + } + return flags; + } + + private static boolean confirmAbstract(IMember element) + throws JavaModelException { + // never show the abstract symbol on interfaces or members in interfaces + if (element.getElementType() == IJavaElement.TYPE) { + return ((IType) element).isClass(); + } + return element.getDeclaringType().isClass(); + } + + private static boolean isInterfaceField(IMember element) + throws JavaModelException { + // always show the final && static symbol on interface fields + if (element.getElementType() == IJavaElement.FIELD) { + return element.getDeclaringType().isInterface(); + } + return false; + } + +// private static boolean confirmSynchronized(IJavaElement member) { +// // Synchronized types are allowed but meaningless. +// return member.getElementType() != IJavaElement.TYPE; +// } + + public static ImageDescriptor getMethodImageDescriptor( + boolean isInInterface, int flags) { + if (Flags.isPublic(flags) || isInInterface) + return PHPUiImages.DESC_MISC_PUBLIC; + if (Flags.isProtected(flags)) + return PHPUiImages.DESC_MISC_PROTECTED; + if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_MISC_PRIVATE; + + return PHPUiImages.DESC_MISC_DEFAULT; + } + + public static ImageDescriptor getFieldImageDescriptor( + boolean isInInterface, int flags) { + if (Flags.isPublic(flags) || isInInterface) + return PHPUiImages.DESC_FIELD_PUBLIC; + if (Flags.isProtected(flags)) + return PHPUiImages.DESC_FIELD_PROTECTED; + if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_FIELD_PRIVATE; + + return PHPUiImages.DESC_FIELD_DEFAULT; + } + + public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, + boolean isInner, int flags) { + if (isInner) { + if (isInterface) { + return getInnerInterfaceImageDescriptor(flags); + } else { + return getInnerClassImageDescriptor(flags); + } + } else { + if (isInterface) { + return getInterfaceImageDescriptor(flags); + } else { + return getClassImageDescriptor(flags); + } + } + } + + private static ImageDescriptor getClassImageDescriptor(int flags) { + if (Flags.isPublic(flags) || Flags.isProtected(flags) + || Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_CLASS; + else + return PHPUiImages.DESC_OBJS_CLASS_DEFAULT; + } + + private static ImageDescriptor getInnerClassImageDescriptor(int flags) { + if (Flags.isPublic(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PUBLIC; + else if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PRIVATE; + else if (Flags.isProtected(flags)) + return PHPUiImages.DESC_OBJS_INNER_CLASS_PROTECTED; + else + return PHPUiImages.DESC_OBJS_INNER_CLASS_DEFAULT; + } + + private static ImageDescriptor getInterfaceImageDescriptor(int flags) { + if (Flags.isPublic(flags) || Flags.isProtected(flags) + || Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INTERFACE; + else + return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; + } + + private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) { + if (Flags.isPublic(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; + else if (Flags.isPrivate(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; + else if (Flags.isProtected(flags)) + return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; + else + return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ListContentProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilterAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java new file mode 100644 index 0000000..a05ac16 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemMarkerManager.java @@ -0,0 +1,204 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.viewsupport; + +import java.util.HashSet; + +import net.sourceforge.phpdt.internal.ui.util.SWTUtil; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.CompilationUnitAnnotationModelEvent; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IMarkerDelta; +import org.eclipse.core.resources.IProject; +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.runtime.CoreException; +import org.eclipse.jface.text.source.AnnotationModelEvent; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IAnnotationModelListener; +import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; +//incastrix +//import org.eclipse.jface.util.ListenerList; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.swt.widgets.Display; + +/** + * Listens to resource deltas and filters for marker changes of type + * IMarker.PROBLEM Viewers showing error ticks should register as listener to + * this type. + */ +public class ProblemMarkerManager implements IResourceChangeListener, + IAnnotationModelListener, IAnnotationModelListenerExtension { + + /** + * Visitors used to look if the element change delta containes a marker + * change. + */ + private static class ProjectErrorVisitor implements IResourceDeltaVisitor { + + private HashSet fChangedElements; + + public ProjectErrorVisitor(HashSet changedElements) { + fChangedElements = changedElements; + } + + public boolean visit(IResourceDelta delta) throws CoreException { + IResource res = delta.getResource(); + if (res instanceof IProject + && delta.getKind() == IResourceDelta.CHANGED) { + try { + IProject project = (IProject) res; + if (!project.isAccessible() + || !project + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + // only track open Java projects + return false; + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + return false; + } + } + checkInvalidate(delta, res); + return true; + } + + private void checkInvalidate(IResourceDelta delta, IResource resource) { + int kind = delta.getKind(); + if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED + || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { + // invalidate the resource and all parents + while (resource.getType() != IResource.ROOT + && fChangedElements.add(resource)) { + resource = resource.getParent(); + } + } + } + + private boolean isErrorDelta(IResourceDelta delta) { + if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) { + IMarkerDelta[] markerDeltas = delta.getMarkerDeltas(); + for (int i = 0; i < markerDeltas.length; i++) { + if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) { + int kind = markerDeltas[i].getKind(); + if (kind == IResourceDelta.ADDED + || kind == IResourceDelta.REMOVED) + return true; + int severity = markerDeltas[i].getAttribute( + IMarker.SEVERITY, -1); + int newSeverity = markerDeltas[i].getMarker() + .getAttribute(IMarker.SEVERITY, -1); + if (newSeverity != severity) + return true; + } + } + } + return false; + } + } + + private ListenerList fListeners; + + public ProblemMarkerManager() { + fListeners = new ListenerList(); + } + + /* + * @see IResourceChangeListener#resourceChanged + */ + public void resourceChanged(IResourceChangeEvent event) { + HashSet changedElements = new HashSet(); + + try { + IResourceDelta delta = event.getDelta(); + if (delta != null) + delta.accept(new ProjectErrorVisitor(changedElements)); + } catch (CoreException e) { + PHPeclipsePlugin.log(e.getStatus()); + } + + if (!changedElements.isEmpty()) { + IResource[] changes = (IResource[]) changedElements + .toArray(new IResource[changedElements.size()]); + fireChanges(changes, true); + } + } + + /* + * (non-Javadoc) + * + * @see IAnnotationModelListener#modelChanged(IAnnotationModel) + */ + public void modelChanged(IAnnotationModel model) { + // no action + } + + /* + * (non-Javadoc) + * + * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) + */ + public void modelChanged(AnnotationModelEvent event) { + if (event instanceof CompilationUnitAnnotationModelEvent) { + CompilationUnitAnnotationModelEvent cuEvent = (CompilationUnitAnnotationModelEvent) event; + if (cuEvent.includesProblemMarkerAnnotationChanges()) { + IResource[] changes = new IResource[] { cuEvent + .getUnderlyingResource() }; + fireChanges(changes, false); + } + } + } + + /** + * Adds a listener for problem marker changes. + */ + public void addListener(IProblemChangedListener listener) { + if (fListeners.isEmpty()) { + PHPeclipsePlugin.getWorkspace().addResourceChangeListener(this); + PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider() + .addGlobalAnnotationModelListener(this); + } + fListeners.add(listener); + } + + /** + * Removes a IProblemChangedListener. + */ + public void removeListener(IProblemChangedListener listener) { + fListeners.remove(listener); + if (fListeners.isEmpty()) { + PHPeclipsePlugin.getWorkspace().removeResourceChangeListener(this); + PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider() + .removeGlobalAnnotationModelListener(this); + } + } + + private void fireChanges(final IResource[] changes, + final boolean isMarkerChange) { + Display display = SWTUtil.getStandardDisplay(); + if (display != null && !display.isDisposed()) { + display.asyncExec(new Runnable() { + public void run() { + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + IProblemChangedListener curr = (IProblemChangedListener) listeners[i]; + curr.problemsChanged(changes, isMarkerChange); + } + } + }); + } + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTableViewer.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ProblemTreeViewer.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ResourceToItemsMapper.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/IStatusChangeListener.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java new file mode 100644 index 0000000..dc7cfda --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewClassCreationWizard.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.wizards; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.ui.wizards.NewClassWizardPage; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +public class NewClassCreationWizard extends NewElementWizard { + + private NewClassWizardPage fPage; + + public NewClassCreationWizard() { + super(); + setDefaultPageImageDescriptor(PHPUiImages.DESC_WIZBAN_NEWCLASS); + setDialogSettings(PHPeclipsePlugin.getDefault().getDialogSettings()); + setWindowTitle(NewWizardMessages + .getString("NewClassCreationWizard.title")); //$NON-NLS-1$ + } + + /* + * @see Wizard#createPages + */ + public void addPages() { + super.addPages(); + fPage = new NewClassWizardPage(); + addPage(fPage); + fPage.init(getSelection()); + } + + /* + * (non-Javadoc) + * + * @see net.sourceforge.phpdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor) + */ + protected void finishPage(IProgressMonitor monitor) + throws InterruptedException, CoreException { + fPage.createType(monitor); // use the full progress monitor + ICompilationUnit cu = JavaModelUtil.toOriginal(fPage.getCreatedType() + .getCompilationUnit()); + if (cu != null) { + IResource resource = cu.getResource(); + selectAndReveal(resource); + openResource((IFile) resource); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.wizard.IWizard#performFinish() + */ + public boolean performFinish() { + // warnAboutTypeCommentDeprecation(); + return super.performFinish(); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java new file mode 100644 index 0000000..3f95c8c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewElementWizard.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.wizards; + +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.ui.actions.WorkbenchRunnableAdapter; +import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; + +public abstract class NewElementWizard extends Wizard implements INewWizard { + + private IWorkbench fWorkbench; + + private IStructuredSelection fSelection; + + public NewElementWizard() { + setNeedsProgressMonitor(true); + } + + protected void openResource(final IFile resource) { + final IWorkbenchPage activePage = PHPeclipsePlugin.getActivePage(); + if (activePage != null) { + final Display display = getShell().getDisplay(); + if (display != null) { + display.asyncExec(new Runnable() { + public void run() { + try { + IDE.openEditor(activePage, resource, true); + } catch (PartInitException e) { + PHPeclipsePlugin.log(e); + } + } + }); + } + } + } + + /** + * Subclasses should override to perform the actions of the wizard. This + * method is run in the wizard container's context as a workspace runnable. + */ + protected void finishPage(IProgressMonitor monitor) + throws InterruptedException, CoreException { + } + + protected void handleFinishException(Shell shell, + InvocationTargetException e) { + String title = NewWizardMessages + .getString("NewElementWizard.op_error.title"); //$NON-NLS-1$ + String message = NewWizardMessages + .getString("NewElementWizard.op_error.message"); //$NON-NLS-1$ + ExceptionHandler.handle(e, shell, title, message); + } + + /* + * @see Wizard#performFinish + */ + public boolean performFinish() { + IWorkspaceRunnable op = new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException, + OperationCanceledException { + try { + finishPage(monitor); + } catch (InterruptedException e) { + throw new OperationCanceledException(e.getMessage()); + } + } + }; + try { + getContainer().run(false, true, new WorkbenchRunnableAdapter(op)); + } catch (InvocationTargetException e) { + handleFinishException(getShell(), e); + return false; + } catch (InterruptedException e) { + return false; + } + return true; + } + + // protected void warnAboutTypeCommentDeprecation() { + // String key= IUIConstants.DIALOGSTORE_TYPECOMMENT_DEPRECATED; + // if (OptionalMessageDialog.isDialogEnabled(key)) { + // Templates templates= Templates.getInstance(); + // boolean isOldWorkspace= templates.getTemplates("filecomment").length > 0 + // && templates.getTemplates("typecomment").length > 0; + // //$NON-NLS-1$ //$NON-NLS-2$ + // if (!isOldWorkspace) { + // OptionalMessageDialog.setDialogEnabled(key, false); + // } + // String title= + // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.title"); + // //$NON-NLS-1$ + // String message= + // NewWizardMessages.getString("NewElementWizard.typecomment.deprecated.message"); + // //$NON-NLS-1$ + // OptionalMessageDialog.open(key, getShell(), title, + // OptionalMessageDialog.getDefaultImage(), message, + // OptionalMessageDialog.INFORMATION, new String[] { + // IDialogConstants.OK_LABEL }, 0); + // } + // } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, + * org.eclipse.jface.viewers.IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection currentSelection) { + fWorkbench = workbench; + fSelection = currentSelection; + } + + public IStructuredSelection getSelection() { + return fSelection; + } + + public IWorkbench getWorkbench() { + return fWorkbench; + } + + protected void selectAndReveal(IResource newResource) { + BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench + .getActiveWorkbenchWindow()); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/NewWizardMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/CheckedListDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ComboDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/DialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IDialogFieldListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IListAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/IStringButtonAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ITreeListAdapter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/LayoutUtil.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/ListDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/SelectionButtonDialogFieldGroup.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/Separator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringButtonStatusDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/StringDialogField.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/wizards/dialogfields/TreeListDialogField.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java index 286ee24..24ebd00 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameIdentifierDelegate.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; @@ -291,12 +292,12 @@ public class RenameIdentifierDelegate { scanner.setPHPMode(false); char[] word = info.getOldName().toCharArray(); - int fToken = ITerminalSymbols.TokenNameEOF; + TokenName fToken = ITerminalSymbols.TokenName.EOF; try { fToken = scanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF) { - if (fToken == ITerminalSymbols.TokenNameVariable - || fToken == ITerminalSymbols.TokenNameIdentifier) { + while (fToken != ITerminalSymbols.TokenName.EOF) { + if (fToken == ITerminalSymbols.TokenName.VARIABLE + || fToken == ITerminalSymbols.TokenName.IDENTIFIER) { if (scanner.equalsCurrentTokenSource(word)) { matches.add(new Integer(scanner .getCurrentTokenStartPosition())); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java index 3f2571f..e9cde45 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/core/RenameLocalVariableDelegate.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import net.sourceforge.phpdt.core.ISourceRange; import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; @@ -116,14 +117,14 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { // Scanner firstScanner = new Scanner(true, false); firstScanner.setSource(content.toCharArray()); - int fToken = ITerminalSymbols.TokenNameEOF; + TokenName fToken = ITerminalSymbols.TokenName.EOF; int start = 0; int phpdocStart = -1; try { fToken = firstScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF + while (fToken != ITerminalSymbols.TokenName.EOF && start < offset) { - if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC) { + if (fToken == ITerminalSymbols.TokenName.COMMENT_PHPDOC) { phpdocStart = firstScanner .getCurrentTokenStartPosition(); } else { @@ -160,7 +161,7 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { boolean renameOtherComments = info.isRenameOtherComments(); char[] word = wordStr.toCharArray(); - fToken = ITerminalSymbols.TokenNameEOF; + fToken = ITerminalSymbols.TokenName.EOF; // double quoted string String tokenString; // double quoted string offset @@ -168,8 +169,8 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { int index; try { fToken = secondScanner.getNextToken(); - while (fToken != ITerminalSymbols.TokenNameEOF) { - if (fToken == ITerminalSymbols.TokenNameVariable) { + while (fToken != ITerminalSymbols.TokenName.EOF) { + if (fToken == ITerminalSymbols.TokenName.VARIABLE) { if (secondScanner.equalsCurrentTokenSource(word)) { // the current variable token is equal to the given // word @@ -177,7 +178,7 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { .getCurrentTokenStartPosition() + offset)); } - } else if (fToken == ITerminalSymbols.TokenNameStringDoubleQuote + } else if (fToken == ITerminalSymbols.TokenName.STRINGDOUBLEQUOTE && renameDQString) { // determine the word in double quoted strings: tokenString = new String(secondScanner @@ -189,7 +190,7 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { matches.add(new Integer(offset + tokenOffset + index)); } - } else if (fToken == ITerminalSymbols.TokenNameCOMMENT_PHPDOC + } else if (fToken == ITerminalSymbols.TokenName.COMMENT_PHPDOC && renamePHPdoc) { tokenString = new String(secondScanner .getCurrentTokenSource()); @@ -200,7 +201,7 @@ public class RenameLocalVariableDelegate extends RenameIdentifierDelegate { matches.add(new Integer(offset + tokenOffset + index)); } - } else if ((fToken == ITerminalSymbols.TokenNameCOMMENT_BLOCK || fToken == ITerminalSymbols.TokenNameCOMMENT_LINE) + } else if ((fToken == ITerminalSymbols.TokenName.COMMENT_BLOCK || fToken == ITerminalSymbols.TokenName.COMMENT_LINE) && renameOtherComments) { tokenString = new String(secondScanner .getCurrentTokenSource()); diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/UITexts.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/UITexts.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/UITexts.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java new file mode 100644 index 0000000..0ed5df5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenameLocalVariable.java @@ -0,0 +1,212 @@ +// Copyright (c) 2005 by Leif Frenzel. All rights reserved. +// See http://leiffrenzel.de +// modified for phpeclipse.de project by axelcl +package net.sourceforge.phpdt.ltk.ui.actions; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.core.SourceMethod; +import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; +import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; +import net.sourceforge.phpdt.ltk.core.RenameIdentifierRefactoring; +import net.sourceforge.phpdt.ltk.core.RenameLocalVariableDelegate; +import net.sourceforge.phpdt.ltk.core.RenamePHPProcessor; +import net.sourceforge.phpdt.ltk.ui.UITexts; +import net.sourceforge.phpdt.ltk.ui.wizards.RenameLocalVariableWizard; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; +import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; +import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.texteditor.ITextEditor; + +public class RenameLocalVariable implements IEditorActionDelegate { + + private ISelection selection; + + private IEditorPart targetEditor; + + private boolean onPHPFile; + + private RenameIdentifierInfo info = new RenameIdentifierInfo(); + + public void setActiveEditor(final IAction action, + final IEditorPart targetEditor) { + this.targetEditor = targetEditor; + onPHPFile = false; + IFile file = getFile(); + + if (file != null && PHPFileUtil.isPHPFile(file)) { + onPHPFile = true; + } + } + + public void run(final IAction action) { + if (!onPHPFile) { + refuse(); + } else { + if (selection != null && selection instanceof ITextSelection) { + String word = null; + Point point = null; + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + PHPEditor editor = (PHPEditor) targetEditor; + if (editor != null) { + ITextSelection textSelection = (ITextSelection) editor + .getSelectionProvider().getSelection(); + IDocument doc = editor.getDocumentProvider() + .getDocument(editor.getEditorInput()); + int pos = textSelection.getOffset(); + point = PHPWordExtractor.findWord(doc, pos); + if (point != null) { + try { + word = doc.get(point.x, point.y); + IWorkingCopyManager manager = PHPeclipsePlugin + .getDefault().getWorkingCopyManager(); + ICompilationUnit unit = manager + .getWorkingCopy(editor.getEditorInput()); + SourceMethod method = (SourceMethod) findEnclosingElement( + point.x, unit, IJavaElement.METHOD); + if (word == null || word.charAt(0) != '$' + || method == null + || !(method instanceof SourceMethod)) { + refuseLocalVariable(); + } else { + applySelection((ITextSelection) selection, + word, point, method); + if (saveAll()) { + openWizard(); + } + } + } catch (BadLocationException e) { + } + } + } + } + } + } + } + + /** + * Returns the enclosing element of a particular element type, + * null if no enclosing element of that type exists. + */ + public IJavaElement findEnclosingElement(int start, ICompilationUnit cu, + int elementType) { + if (cu == null) + return null; + + try { + IJavaElement element = cu.getElementAt(start); + if (element == null) { + element = cu; + } + + return element.getAncestor(elementType); + + } catch (JavaModelException e) { + return null; + } + } + + public void selectionChanged(final IAction action, + final ISelection selection) { + this.selection = selection; + } + + // helping methods + // //////////////// + + private void applySelection(final ITextSelection textSelection, + String word, Point point, SourceMethod method) { + if (word != null) { + info.setOldName(word); + info.setNewName(word); + info.setOffset(point.x); + } else { + info.setOldName(textSelection.getText()); + info.setNewName(textSelection.getText()); + info.setOffset(textSelection.getOffset()); + } + info.setMethod(method); + info.setSourceFile(getFile()); + } + + private void refuseLocalVariable() { + String title = UITexts.renameLocalVariable_refuseDlg_title; + String message = UITexts.renameLocalVariable_refuseDlg_message; + MessageDialog.openInformation(getShell(), title, message); + } + + private void refuse() { + String title = UITexts.renameProperty_refuseDlg_title; + String message = UITexts.renameProperty_refuseDlg_message; + MessageDialog.openInformation(getShell(), title, message); + } + + private static boolean saveAll() { + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + return IDE.saveAllEditors(new IResource[] { workspaceRoot }, false); + } + + private void openWizard() { + RenameLocalVariableDelegate delegate = new RenameLocalVariableDelegate( + info); + RefactoringProcessor processor = new RenamePHPProcessor(info, delegate); + RenameIdentifierRefactoring ref = new RenameIdentifierRefactoring( + processor); + RenameLocalVariableWizard wizard = new RenameLocalVariableWizard(ref, + info); + RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation( + wizard); + try { + String titleForFailedChecks = ""; //$NON-NLS-1$ + op.run(getShell(), titleForFailedChecks); + } catch (final InterruptedException irex) { + // operation was cancelled + } + } + + private Shell getShell() { + Shell result = null; + if (targetEditor != null) { + result = targetEditor.getSite().getShell(); + } else { + result = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + } + return result; + } + + private final IFile getFile() { + IFile result = null; + if (targetEditor instanceof ITextEditor) { + ITextEditor editor = (ITextEditor) targetEditor; + IEditorInput input = editor.getEditorInput(); + if (input instanceof IFileEditorInput) { + result = ((IFileEditorInput) input).getFile(); + } + } + return result; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/actions/RenamePHPIdentifier.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/uitexts.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/uitexts.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/uitexts.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/uitexts.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java new file mode 100644 index 0000000..027f590 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierPage.java @@ -0,0 +1,180 @@ +// Copyright (c) 2005 by Leif Frenzel. All rights reserved. +// See http://leiffrenzel.de +package net.sourceforge.phpdt.ltk.ui.wizards; + +import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; +import net.sourceforge.phpdt.ltk.ui.UITexts; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.ltk.ui.refactoring.UserInputWizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +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.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +/** + *

+ * the input page for the Rename Property refactoring, where users can control + * the effects of the refactoring; to be shown in the wizard. + *

+ * + *

+ * We let the user enter the new name for the property, and we let her decide + * whether other property files in the bundle should be affected, and whether + * the operation is supposed to span the entire workspace or only the current + * project. + *

+ * + */ +public class RenameIdentifierPage extends UserInputWizardPage { + + private static final String DS_KEY = RenameIdentifierPage.class.getName(); + + private static final String DS_UPDATE_BUNDLE = "UPDATE_BUNDLE"; //$NON-NLS-1$ + + private static final String DS_ALL_PROJECTS = "ALL_PROJECTS"; //$NON-NLS-1$ + + private final RenameIdentifierInfo info; + + private IDialogSettings dialogSettings; + + private Text txtNewName; + + private Button cbUpdateBundle; + + private Button cbAllProjects; + + public RenameIdentifierPage(final RenameIdentifierInfo info) { + super(RenameIdentifierPage.class.getName()); + this.info = info; + initDialogSettings(); + } + + // interface methods of UserInputWizardPage + // ///////////////////////////////////////// + + public void createControl(final Composite parent) { + Composite composite = createRootComposite(parent); + setControl(composite); + + createLblNewName(composite); + createTxtNewName(composite); + createCbUpdateBundle(composite); + createCbAllProjects(composite); + + validate(); + } + + // UI creation methods + // //////////////////// + + private Composite createRootComposite(final Composite parent) { + Composite result = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(2, false); + gridLayout.marginWidth = 10; + gridLayout.marginHeight = 10; + result.setLayout(gridLayout); + initializeDialogUnits(result); + Dialog.applyDialogFont(result); + return result; + } + + private void createLblNewName(final Composite composite) { + Label lblNewName = new Label(composite, SWT.NONE); + lblNewName.setText(UITexts.renamePropertyInputPage_lblNewName); + } + + private void createTxtNewName(Composite composite) { + txtNewName = new Text(composite, SWT.BORDER); + txtNewName.setText(info.getOldName()); + txtNewName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtNewName.selectAll(); + txtNewName.addKeyListener(new KeyAdapter() { + public void keyReleased(final KeyEvent e) { + info.setNewName(txtNewName.getText()); + validate(); + } + }); + } + + private void createCbUpdateBundle(final Composite composite) { + String texts = UITexts.renamePropertyInputPage_cbUpdateBundle; + cbUpdateBundle = createCheckbox(composite, texts); + cbUpdateBundle.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbUpdateBundle.getSelection(); + dialogSettings.put(DS_UPDATE_BUNDLE, selected); + info.setUpdateProject(selected); + } + }); + initUpdateBundleOption(); + } + + private void createCbAllProjects(final Composite composite) { + String text = UITexts.renamePropertyInputPage_cbAllProjects; + cbAllProjects = createCheckbox(composite, text); + cbAllProjects.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbAllProjects.getSelection(); + dialogSettings.put(DS_ALL_PROJECTS, selected); + info.setAllProjects(selected); + // for demonstration purposes, we enforce the preview for + // refactorings + // that span the entire workspace + getRefactoringWizard().setForcePreviewReview(selected); + } + }); + initAllProjectsOption(); + } + + private Button createCheckbox(final Composite composite, final String text) { + Button result = new Button(composite, SWT.CHECK); + result.setText(text); + + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + gridData.horizontalSpan = 2; + result.setLayoutData(gridData); + + return result; + } + + // helping methods + // //////////////// + + private void initDialogSettings() { + IDialogSettings ds = PHPeclipsePlugin.getDefault().getDialogSettings(); + dialogSettings = ds.getSection(DS_KEY); + if (dialogSettings == null) { + dialogSettings = ds.addNewSection(DS_KEY); + // init default values + dialogSettings.put(DS_UPDATE_BUNDLE, true); + dialogSettings.put(DS_ALL_PROJECTS, false); + } + } + + private void validate() { + String txt = txtNewName.getText(); + setPageComplete(txt.length() > 0 && !txt.equals(info.getOldName())); + } + + private void initUpdateBundleOption() { + boolean updateRefs = dialogSettings.getBoolean(DS_UPDATE_BUNDLE); + cbUpdateBundle.setSelection(updateRefs); + info.setUpdateProject(updateRefs); + } + + private void initAllProjectsOption() { + boolean allProjects = dialogSettings.getBoolean(DS_ALL_PROJECTS); + cbAllProjects.setSelection(allProjects); + info.setAllProjects(allProjects); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameIdentifierWizard.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java new file mode 100644 index 0000000..b3d4607 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariablePage.java @@ -0,0 +1,214 @@ +// Copyright (c) 2005 by Leif Frenzel. All rights reserved. +// See http://leiffrenzel.de +package net.sourceforge.phpdt.ltk.ui.wizards; + +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.ltk.core.RenameIdentifierInfo; +import net.sourceforge.phpdt.ltk.ui.UITexts; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.ltk.ui.refactoring.UserInputWizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +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.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Text; + +/** + *

+ * the input page for the Rename Property refactoring, where users can control + * the effects of the refactoring; to be shown in the wizard. + *

+ * + *

+ * We let the user enter the new name for the property, and we let her decide + * whether other property files in the bundle should be affected, and whether + * the operation is supposed to span the entire workspace or only the current + * project. + *

+ * + */ +public class RenameLocalVariablePage extends UserInputWizardPage { + + private static final String DS_KEY = RenameLocalVariablePage.class + .getName(); + + private static final String DS_RENAME_DQ_STRINGS = "RENAME_DQ_STRINGS"; //$NON-NLS-1$ + + private static final String DS_RENAME_PHPDOC = "RENAME_PHPDOC"; //$NON-NLS-1$ + + private static final String DS_RENAME_OTHER_COMMENTS = "RENAME_OTHER_COMMENTS"; //$NON-NLS-1$ + + private final RenameIdentifierInfo info; + + private IDialogSettings dialogSettings; + + private Text txtNewName; + + private Button cbRenameDQStrings; + + private Button cbRenamePHPdoc; + + private Button cbRenameOtherComments; + + public RenameLocalVariablePage(final RenameIdentifierInfo info) { + super(RenameLocalVariablePage.class.getName()); + this.info = info; + initDialogSettings(); + } + + public void createControl(final Composite parent) { + Composite composite = createRootComposite(parent); + setControl(composite); + + createLblNewName(composite); + createTxtNewName(composite); + createCbDQStrings(composite); + createCbPHPdoc(composite); + createCbOtherComments(composite); + + validate(); + + // TODO check if we can leave this step out in the future + getRefactoringWizard().setForcePreviewReview(true); + } + + private Composite createRootComposite(final Composite parent) { + Composite result = new Composite(parent, SWT.NONE); + GridLayout gridLayout = new GridLayout(2, false); + gridLayout.marginWidth = 10; + gridLayout.marginHeight = 10; + result.setLayout(gridLayout); + initializeDialogUnits(result); + Dialog.applyDialogFont(result); + return result; + } + + private void createLblNewName(final Composite composite) { + Label lblNewName = new Label(composite, SWT.NONE); + lblNewName.setText(UITexts.renamePropertyInputPage_lblNewName); + } + + private void createTxtNewName(Composite composite) { + txtNewName = new Text(composite, SWT.BORDER); + txtNewName.setText(info.getOldName()); + txtNewName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + txtNewName.selectAll(); + txtNewName.addKeyListener(new KeyAdapter() { + public void keyReleased(final KeyEvent e) { + info.setNewName(txtNewName.getText()); + validate(); + } + }); + } + + private void createCbDQStrings(final Composite composite) { + String texts = UITexts.renameLocalVariable_cbDQStrings; + cbRenameDQStrings = createCheckbox(composite, texts); + cbRenameDQStrings.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbRenameDQStrings.getSelection(); + dialogSettings.put(DS_RENAME_DQ_STRINGS, selected); + info.setRenameDQString(selected); + } + }); + initDQStringsOption(); + } + + private void createCbPHPdoc(final Composite composite) { + String texts = UITexts.renameLocalVariable_cbPHPdoc; + cbRenamePHPdoc = createCheckbox(composite, texts); + cbRenamePHPdoc.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbRenamePHPdoc.getSelection(); + dialogSettings.put(DS_RENAME_PHPDOC, selected); + info.setRenamePHPdoc(selected); + } + }); + initPHPdocOption(); + } + + private void createCbOtherComments(final Composite composite) { + String texts = UITexts.renameLocalVariable_cbOtherDoc; + cbRenameOtherComments = createCheckbox(composite, texts); + cbRenameOtherComments.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(final SelectionEvent event) { + boolean selected = cbRenameOtherComments.getSelection(); + dialogSettings.put(DS_RENAME_OTHER_COMMENTS, selected); + info.setRenameOtherComments(selected); + } + }); + initOtherCommentsOption(); + } + + private Button createCheckbox(final Composite composite, final String text) { + Button result = new Button(composite, SWT.CHECK); + result.setText(text); + + GridData gridData = new GridData(GridData.FILL_HORIZONTAL); + gridData.horizontalSpan = 2; + result.setLayoutData(gridData); + + return result; + } + + private void initDialogSettings() { + IDialogSettings ds = PHPeclipsePlugin.getDefault().getDialogSettings(); + dialogSettings = ds.getSection(DS_KEY); + if (dialogSettings == null) { + dialogSettings = ds.addNewSection(DS_KEY); + // init default values + dialogSettings.put(DS_RENAME_DQ_STRINGS, true); + dialogSettings.put(DS_RENAME_PHPDOC, true); + dialogSettings.put(DS_RENAME_OTHER_COMMENTS, true); + } + } + + private static boolean isVariable(String txt) { + if (txt.length() <= 1) { + return false; + } + if (txt.charAt(0) != '$') { + return false; + } + for (int i = 1; i < txt.length(); i++) { + if (!Scanner.isPHPIdentifierPart(txt.charAt(i))) { + return false; + } + } + return true; + } + + private void validate() { + String txt = txtNewName.getText(); + //Scanner s; + setPageComplete(isVariable(txt) && !txt.equals(info.getOldName())); + } + + private void initDQStringsOption() { + boolean refs = dialogSettings.getBoolean(DS_RENAME_DQ_STRINGS); + cbRenameDQStrings.setSelection(refs); + info.setRenameDQString(refs); + } + + private void initPHPdocOption() { + boolean refs = dialogSettings.getBoolean(DS_RENAME_PHPDOC); + cbRenamePHPdoc.setSelection(refs); + info.setRenamePHPdoc(refs); + } + + private void initOtherCommentsOption() { + boolean refs = dialogSettings.getBoolean(DS_RENAME_OTHER_COMMENTS); + cbRenameOtherComments.setSelection(refs); + info.setRenameOtherComments(refs); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ltk/ui/wizards/RenameLocalVariableWizard.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/CodeGeneration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/CodeGeneration.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IContextMenuConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IJavaElementSearchConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IPackagesViewPart.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ITypeHierarchyViewPart.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java new file mode 100644 index 0000000..1f72bd5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java @@ -0,0 +1,352 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import java.text.Collator; + +import net.sourceforge.phpdt.core.Flags; +import net.sourceforge.phpdt.core.IField; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IPackageFragment; +import net.sourceforge.phpdt.core.IPackageFragmentRoot; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.Signature; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.internal.corext.util.JdtFlags; +import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IStorage; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jface.viewers.ContentViewer; +import org.eclipse.jface.viewers.IBaseLabelProvider; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerSorter; +import org.eclipse.ui.model.IWorkbenchAdapter; + +/** + * Sorter for Java elements. Ordered by element category, then by element name. + * Package fragment roots are sorted as ordered on the classpath. + * + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * @since 2.0 + */ +public class JavaElementSorter extends ViewerSorter { + + private static final int PROJECTS = 1; + + private static final int PACKAGEFRAGMENTROOTS = 2; + + private static final int PACKAGEFRAGMENT = 3; + + private static final int COMPILATIONUNITS = 4; + + private static final int CLASSFILES = 5; + + private static final int RESOURCEFOLDERS = 7; + + private static final int RESOURCES = 8; + + private static final int STORAGE = 9; + + private static final int PACKAGE_DECL = 10; + + private static final int IMPORT_CONTAINER = 11; + + private static final int IMPORT_DECLARATION = 12; + + // Includes all categories ordered using the OutlineSortOrderPage: + // types, initializers, methods & fields + private static final int MEMBERSOFFSET = 15; + + private static final int JAVAELEMENTS = 50; + + private static final int OTHERS = 51; + + private MembersOrderPreferenceCache fMemberOrderCache; + + /** + * Constructor. + */ + public JavaElementSorter() { + super(null); // delay initialization of collator + fMemberOrderCache = PHPeclipsePlugin.getDefault() + .getMemberOrderPreferenceCache(); + } + + /** + * @deprecated Bug 22518. Method never used: does not override + * ViewerSorter#isSorterProperty(Object, String). Method could + * be removed, but kept for API compatibility. + */ +// public boolean isSorterProperty(Object element, Object property) { +// return true; +// } + + /* + * @see ViewerSorter#category + */ + public int category(Object element) { + if (element instanceof IJavaElement) { + try { + IJavaElement je = (IJavaElement) element; + + switch (je.getElementType()) { + case IJavaElement.METHOD: { + IMethod method = (IMethod) je; + if (method.isConstructor()) { + return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); + } + int flags = method.getFlags(); + if (Flags.isStatic(flags)) + return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX); + else + return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); + } + case IJavaElement.FIELD: { + int flags = ((IField) je).getFlags(); + if (Flags.isStatic(flags)) + return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX); + else + return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); + } + // case IJavaElement.INITIALIZER : + // { + // int flags= ((IInitializer) je).getFlags(); + // if (Flags.isStatic(flags)) + // return + // getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); + // else + // return + // getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); + // } + case IJavaElement.TYPE: + return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); + case IJavaElement.PACKAGE_DECLARATION: + return PACKAGE_DECL; + case IJavaElement.IMPORT_CONTAINER: + return IMPORT_CONTAINER; + case IJavaElement.IMPORT_DECLARATION: + return IMPORT_DECLARATION; + case IJavaElement.PACKAGE_FRAGMENT: + IPackageFragment pack = (IPackageFragment) je; + if (pack.getParent().getResource() instanceof IProject) { + return PACKAGEFRAGMENTROOTS; + } + return PACKAGEFRAGMENT; + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + return PACKAGEFRAGMENTROOTS; + case IJavaElement.JAVA_PROJECT: + return PROJECTS; + case IJavaElement.CLASS_FILE: + return CLASSFILES; + case IJavaElement.COMPILATION_UNIT: + return COMPILATIONUNITS; + } + + } catch (JavaModelException e) { + if (!e.isDoesNotExist()) + PHPeclipsePlugin.log(e); + } + return JAVAELEMENTS; + } else if (element instanceof IFile) { + return RESOURCES; + } else if (element instanceof IProject) { + return PROJECTS; + } else if (element instanceof IContainer) { + return RESOURCEFOLDERS; + } else if (element instanceof IStorage) { + return STORAGE; + } + // else if (element instanceof ClassPathContainer) { + // return PACKAGEFRAGMENTROOTS; + // } + return OTHERS; + } + + private int getMemberCategory(int kind) { + int offset = fMemberOrderCache.getCategoryIndex(kind); + return offset + MEMBERSOFFSET; + } + + /* + * @see ViewerSorter#compare + */ + public int compare(Viewer viewer, Object e1, Object e2) { + int cat1 = category(e1); + int cat2 = category(e2); + + if (cat1 != cat2) + return cat1 - cat2; + + if (cat1 == PROJECTS) { + IWorkbenchAdapter a1 = (IWorkbenchAdapter) ((IAdaptable) e1) + .getAdapter(IWorkbenchAdapter.class); + IWorkbenchAdapter a2 = (IWorkbenchAdapter) ((IAdaptable) e2) + .getAdapter(IWorkbenchAdapter.class); + return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2)); + } + + if (cat1 == PACKAGEFRAGMENTROOTS) { + IPackageFragmentRoot root1 = getPackageFragmentRoot(e1); + IPackageFragmentRoot root2 = getPackageFragmentRoot(e2); + if (root1 == null) { + if (root2 == null) { + return 0; + } else { + return 1; + } + } else if (root2 == null) { + return -1; + } + if (!root1.getPath().equals(root2.getPath())) { + int p1 = getClassPathIndex(root1); + int p2 = getClassPathIndex(root2); + if (p1 != p2) { + return p1 - p2; + } + } + e1 = root1; // normalize classpath container to root + e2 = root2; + } + // non - java resources are sorted using the label from the viewers + // label provider + if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS + || cat1 == STORAGE || cat1 == OTHERS) { + return compareWithLabelProvider(viewer, e1, e2); + } + + if (e1 instanceof IMember) { + if (fMemberOrderCache.isSortByVisibility()) { + try { + int flags1 = JdtFlags.getVisibilityCode((IMember) e1); + int flags2 = JdtFlags.getVisibilityCode((IMember) e2); + int vis = fMemberOrderCache.getVisibilityIndex(flags1) + - fMemberOrderCache.getVisibilityIndex(flags2); + if (vis != 0) { + return vis; + } + } catch (JavaModelException ignore) { + } + } + } + + String name1 = ((IJavaElement) e1).getElementName(); + String name2 = ((IJavaElement) e2).getElementName(); + + if (e1 instanceof IType) { // handle anonymous types + if (name1.length() == 0) { + if (name2.length() == 0) { + try { + return getCollator().compare( + ((IType) e1).getSuperclassName(), + ((IType) e2).getSuperclassName()); + } catch (JavaModelException e) { + return 0; + } + } else { + return 1; + } + } else if (name2.length() == 0) { + return -1; + } + } + + int cmp = getCollator().compare(name1, name2); + if (cmp != 0) { + return cmp; + } + + if (e1 instanceof IMethod) { + String[] params1 = ((IMethod) e1).getParameterTypes(); + String[] params2 = ((IMethod) e2).getParameterTypes(); + int len = Math.min(params1.length, params2.length); + for (int i = 0; i < len; i++) { + cmp = getCollator().compare(Signature.toString(params1[i]), + Signature.toString(params2[i])); + if (cmp != 0) { + return cmp; + } + } + return params1.length - params2.length; + } + return 0; + } + + private IPackageFragmentRoot getPackageFragmentRoot(Object element) { + // if (element instanceof ClassPathContainer) { + // // return first package fragment root from the container + // ClassPathContainer cp= (ClassPathContainer)element; + // Object[] roots= cp.getPackageFragmentRoots(); + // if (roots.length > 0) + // return (IPackageFragmentRoot)roots[0]; + // // non resolvable - return null + // return null; + // } + return JavaModelUtil.getPackageFragmentRoot((IJavaElement) element); + } + + private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) { + if (viewer == null || !(viewer instanceof ContentViewer)) { + IBaseLabelProvider prov = ((ContentViewer) viewer) + .getLabelProvider(); + if (prov instanceof ILabelProvider) { + ILabelProvider lprov = (ILabelProvider) prov; + String name1 = lprov.getText(e1); + String name2 = lprov.getText(e2); + if (name1 != null && name2 != null) { + return getCollator().compare(name1, name2); + } + } + } + return 0; // can't compare + } + + private int getClassPathIndex(IPackageFragmentRoot root) { + try { + IPath rootPath = root.getPath(); + IPackageFragmentRoot[] roots = root.getJavaProject() + .getPackageFragmentRoots(); + for (int i = 0; i < roots.length; i++) { + if (roots[i].getPath().equals(rootPath)) { + return i; + } + } + } catch (JavaModelException e) { + } + + return Integer.MAX_VALUE; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ViewerSorter#getCollator() + */ + public final Collator getCollator() { + if (collator == null) { + collator = Collator.getInstance(); + } + return collator; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java new file mode 100644 index 0000000..79fc6e1 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaUI.java @@ -0,0 +1,808 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import net.sourceforge.phpdt.core.IBufferFactory; +//import net.sourceforge.phpdt.core.IJavaElement; +//import net.sourceforge.phpdt.core.IWorkingCopy; +//import net.sourceforge.phpdt.core.JavaCore; +//import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +//import net.sourceforge.phpeclipse.phpeditor.EditorUtility; + +//import org.eclipse.ui.IEditorPart; +//import org.eclipse.ui.ISharedImages; +//import org.eclipse.ui.PartInitException; +//import org.eclipse.ui.internal.SharedImages; +//import org.eclipse.ui.texteditor.IDocumentProvider; + +/** + * Central access point for the Java UI plug-in (id + * "net.sourceforge.phpdt.ui"). This class provides static + * methods for: + *
    + *
  • creating various kinds of selection dialogs to present a collection of + * Java elements to the user and let them make a selection.
  • + *
  • opening a Java editor on a compilation unit.
  • + *
+ *

+ * This class provides static methods and fields only; it is not intended to be + * instantiated or subclassed by clients. + *

+ */ +public final class JavaUI { + +// private static ISharedImages fgSharedImages = null; + + private JavaUI() { + // prevent instantiation of JavaUI. + } + + /** + * The id of the Java plugin (value "net.sourceforge.phpdt.ui"). + */ + // public static final String ID_PLUGIN= "net.sourceforge.phpdt.ui"; + // //$NON-NLS-1$ + /** + * The id of the Java perspective (value + * "net.sourceforge.phpdt.ui.JavaPerspective"). + */ + public static final String ID_PERSPECTIVE= + "net.sourceforge.phpdt.ui.JavaPerspective"; //$NON-NLS-1$ + /** + * The id of the Java hierarchy perspective (value + * "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"). + */ + // public static final String ID_HIERARCHYPERSPECTIVE= + // "net.sourceforge.phpdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ + /** + * The id of the Java action set (value + * "net.sourceforge.phpdt.ui.JavaActionSet"). + */ + // public static final String ID_ACTION_SET= + // "net.sourceforge.phpdt.ui.JavaActionSet"; //$NON-NLS-1$ + /** + * The id of the Java Element Creation action set (value + * "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"). + * + * @since 2.0 + */ + // public static final String ID_ELEMENT_CREATION_ACTION_SET= + // "net.sourceforge.phpdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ + /** + * The id of the Java Coding action set (value + * "net.sourceforge.phpdt.ui.CodingActionSet"). + * + * @since 2.0 + */ + // public static final String ID_CODING_ACTION_SET= + // "net.sourceforge.phpdt.ui.CodingActionSet"; //$NON-NLS-1$ + /** + * The id of the Java action set for open actions (value + * "net.sourceforge.phpdt.ui.A_OpenActionSet"). + * + * @since 2.0 + */ + // public static final String ID_OPEN_ACTION_SET= + // "net.sourceforge.phpdt.ui.A_OpenActionSet"; //$NON-NLS-1$ + /** + * The id of the Java Search action set (value + * net.sourceforge.phpdt.ui.SearchActionSet"). + * + * @since 2.0 + */ + // public static final String ID_SEARCH_ACTION_SET= + // "net.sourceforge.phpdt.ui.SearchActionSet"; //$NON-NLS-1$ + /** + * The editor part id of the editor that presents Java compilation units + * (value "net.sourceforge.phpdt.ui.CompilationUnitEditor"). + */ + // public static final String ID_CU_EDITOR= + // "net.sourceforge.phpdt.ui.PHPUnitEditor"; //$NON-NLS-1$ + /** + * The editor part id of the editor that presents Java binary class files + * (value "net.sourceforge.phpdt.ui.ClassFileEditor"). + */ + // public static final String ID_CF_EDITOR= + // "net.sourceforge.phpdt.ui.ClassFileEditor"; //$NON-NLS-1$ + /** + * The editor part id of the code snippet editor (value + * "net.sourceforge.phpdt.ui.SnippetEditor"). + */ + // public static final String ID_SNIPPET_EDITOR= + // "net.sourceforge.phpdt.ui.SnippetEditor"; //$NON-NLS-1$ + /** + * The view part id of the Packages view (value + * "net.sourceforge.phpdt.ui.PackageExplorer"). + *

+ * When this id is used to access a view part with + * IWorkbenchPage.findView or showView, the + * returned IViewPart can be safely cast to an + * IPackagesViewPart. + *

+ * + * @see IPackagesViewPart + * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) + * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) + */ + public static final String ID_PACKAGES = "net.sourceforge.phpdt.ui.PackageExplorer"; //$NON-NLS-1$ + + /** + * The view part id of the type hierarchy part. (value + * "net.sourceforge.phpdt.ui.TypeHierarchy"). + *

+ * When this id is used to access a view part with + * IWorkbenchPage.findView or showView, the + * returned IViewPart can be safely cast to an + * ITypeHierarchyViewPart. + *

+ * + * @see ITypeHierarchyViewPart + * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) + * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) + */ + public static final String ID_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.TypeHierarchy"; //$NON-NLS-1$ + + /** + * The id of the Java Browsing Perspective (value + * "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"). + * + * @since 2.0 + */ + // public static String ID_BROWSING_PERSPECTIVE= + // "net.sourceforge.phpdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ + /** + * The view part id of the Java Browsing Projects view (value + * "net.sourceforge.phpdt.ui.ProjectsView"). + * + * @since 2.0 + */ + // public static String ID_PROJECTS_VIEW= + // "net.sourceforge.phpdt.ui.ProjectsView"; //$NON-NLS-1$ + /** + * The view part id of the Java Browsing Packages view (value + * "net.sourceforge.phpdt.ui.PackagesView"). + * + * @since 2.0 + */ + // public static String ID_PACKAGES_VIEW= + // "net.sourceforge.phpdt.ui.PackagesView"; //$NON-NLS-1$ + /** + * The view part id of the Java Browsing Types view (value + * "net.sourceforge.phpdt.ui.TypesView"). + * + * @since 2.0 + */ + // public static String ID_TYPES_VIEW= "net.sourceforge.phpdt.ui.TypesView"; + // //$NON-NLS-1$ + /** + * The view part id of the Java Browsing Members view (value + * "net.sourceforge.phpdt.ui.MembersView"). + * + * @since 2.0 + */ + // public static String ID_MEMBERS_VIEW= + // "net.sourceforge.phpdt.ui.MembersView"; //$NON-NLS-1$ + /** + * The class org.eclipse.debug.core.model.IProcess allows attaching String + * properties to processes. The Java UI contributes a property page for + * IProcess that will show the contents of the property with this key. The + * intent of this property is to show the command line a process was + * launched with. + * + * @deprecated + */ + // public final static String ATTR_CMDLINE= + // "net.sourceforge.phpdt.ui.launcher.cmdLine"; //$NON-NLS-1$ + /** + * Returns the shared images for the Java UI. + * + * @return the shared images manager + */ +// public static ISharedImages getSharedImages() { +// if (fgSharedImages == null) +// fgSharedImages = new SharedImages(); +// +// return fgSharedImages; +// } + + /** + * Creates a selection dialog that lists all packages of the given Java + * project. The caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the valid flags are: + * IJavaElementSearchConstants.CONSIDER_BINARIES, + * indicating that packages from binary package fragment roots + * should be included in addition to those from source package + * fragment roots; + * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, + * indicating that packages from required projects should be + * included as well. + * @param filter + * the initial pattern to filter the set of packages. For example + * "com" shows all packages starting with "com". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + * + * @since 2.0 + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IJavaProject project, int style, String filter) throws JavaModelException + // { + // Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | + // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == + // (IJavaElementSearchConstants.CONSIDER_BINARIES | + // IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); + // + // IPackageFragmentRoot[] roots= null; + // if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != + // 0) { + // roots= project.getAllPackageFragmentRoots(); + // } else { + // roots= project.getPackageFragmentRoots(); + // } + // + // List consideredRoots= null; + // if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { + // consideredRoots= Arrays.asList(roots); + // } else { + // consideredRoots= new ArrayList(roots.length); + // for (int i= 0; i < roots.length; i++) { + // IPackageFragmentRoot root= roots[i]; + // if (root.getKind() != IPackageFragmentRoot.K_BINARY) + // consideredRoots.add(root); + // + // } + // } + // + // int flags= JavaElementLabelProvider.SHOW_DEFAULT; + // if (consideredRoots.size() > 1) + // flags= flags | JavaElementLabelProvider.SHOW_ROOT; + // + // List packages= new ArrayList(); + // Iterator iter= consideredRoots.iterator(); + // while(iter.hasNext()) { + // IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); + // packages.addAll(Arrays.asList(root.getChildren())); + // } + // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, + // new JavaElementLabelProvider(flags)); + // dialog.setIgnoreCase(false); + // dialog.setElements(packages.toArray()); // XXX inefficient + // dialog.setFilter(filter); + // return dialog; + // } + /** + * Creates a selection dialog that lists all packages of the given Java + * project. The caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the valid flags are: + * IJavaElementSearchConstants.CONSIDER_BINARIES, + * indicating that packages from binary package fragment roots + * should be included in addition to those from source package + * fragment roots; + * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS, + * indicating that packages from required projects should be + * included as well. + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IJavaProject project, int style) throws JavaModelException { + // return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all packages under the given + * package fragment root. The caller is responsible for opening the dialog + * with Window.open, and subsequently extracting the + * selected package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param root + * the package fragment root + * @param filter + * the initial pattern to filter the set of packages. For example + * "com" shows all packages starting with "com". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + * + * @since 2.0 + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IPackageFragmentRoot root, String filter) throws JavaModelException { + // ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, + // new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); + // dialog.setIgnoreCase(false); + // dialog.setElements(root.getChildren()); + // dialog.setFilter(filter); + // return dialog; + // } + /** + * Creates a selection dialog that lists all packages under the given + * package fragment root. The caller is responsible for opening the dialog + * with Window.open, and subsequently extracting the + * selected package (of type IPackageFragment) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param root + * the package fragment root + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createPackageDialog(Shell parent, + // IPackageFragmentRoot root) throws JavaModelException { + // return createPackageDialog(parent, root, ""); //$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given scope. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed + * @param filter + * the initial pattern to filter the set of types. For example + * "Abstract" shows all types starting with "abstract". The meta + * character '?' representing any character and '*' representing + * any string are supported. Clients can pass an empty string if + * no filtering is required. + * @exception JavaModelException + * if the selection dialog could not be opened + * + * @since 2.0 + */ + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection, String filter) throws JavaModelException { + // int elementKinds= 0; + // if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { + // elementKinds= IJavaSearchConstants.TYPE; + // } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { + // elementKinds= IJavaSearchConstants.INTERFACE; + // } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { + // elementKinds= IJavaSearchConstants.CLASS; + // } else { + // Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ + // } + // if (multipleSelection) { + // MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, + // context, elementKinds, scope); + // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); + // //$NON-NLS-1$ + // dialog.setFilter(filter); + // return dialog; + // } else { + // TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, + // elementKinds, scope); + // dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); + // //$NON-NLS-1$ + // dialog.setFilter(filter); + // return dialog; + // } + // } + /** + * Creates a selection dialog that lists all types in the given scope. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection) throws JavaModelException { + // return createTypeDialog(parent, context, scope, style, multipleSelection, + // "");//$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given scope + * containing a standard main method. The caller is + * responsible for opening the dialog with Window.open, and + * subsequently extracting the selected type(s) (of type IType) + * via SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_BINARIES, + * CONSIDER_EXTERNAL_JARS, or their bitwise OR, + * or 0 + * @param multipleSelection + * true if multiple selection is allowed + * @param filter + * the initial pattern to filter the set of types containg a main + * method. For example "App" shows all types starting with "app". + * The meta character '?' representing any character and '*' + * representing any string are supported. Clients can pass an + * empty string if no filtering is required. + * @return a new selection dialog + * + * @since 2.0 + */ + // public static SelectionDialog createMainTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection, String filter) { + // if (multipleSelection) { + // MultiMainTypeSelectionDialog dialog= new + // MultiMainTypeSelectionDialog(parent, context, scope, style); + // dialog.setFilter(filter); + // return dialog; + // } else { + // MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, + // context, scope, style); + // dialog.setFilter(filter); + // return dialog; + // } + // } + /** + * Creates a selection dialog that lists all types in the given scope + * containing a standard main method. The caller is + * responsible for opening the dialog with Window.open, and + * subsequently extracting the selected type(s) (of type IType) + * via SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param scope + * the scope that limits which types are included + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_BINARIES, + * CONSIDER_EXTERNAL_JARS, or their bitwise OR, + * or 0 + * @param multipleSelection + * true if multiple selection is allowed + * @return a new selection dialog + */ + // public static SelectionDialog createMainTypeDialog(Shell parent, + // IRunnableContext context, IJavaSearchScope scope, int style, boolean + // multipleSelection) { + // return createMainTypeDialog(parent, context, scope, style, + // multipleSelection, "");//$NON-NLS-1$ + // } + /** + * Creates a selection dialog that lists all types in the given project. The + * caller is responsible for opening the dialog with + * Window.open, and subsequently extracting the selected + * type(s) (of type IType) via + * SelectionDialog.getResult. + * + * @param parent + * the parent shell of the dialog to be created + * @param context + * the runnable context used to show progress when the dialog is + * being populated + * @param project + * the Java project + * @param style + * flags defining the style of the dialog; the only valid values + * are IJavaElementSearchConstants.CONSIDER_CLASSES, + * CONSIDER_INTERFACES, or their bitwise OR + * (equivalent to CONSIDER_TYPES) + * @param multipleSelection + * true if multiple selection is allowed + * @return a new selection dialog + * @exception JavaModelException + * if the selection dialog could not be opened + */ + // public static SelectionDialog createTypeDialog(Shell parent, + // IRunnableContext context, IProject project, int style, boolean + // multipleSelection) throws JavaModelException { + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new + // IJavaProject[] { JavaCore.create(project) }); + // return createTypeDialog(parent, context, scope, style, + // multipleSelection); + // } + /** + * Opens a Java editor on the given Java element. The element can be a + * compilation unit or class file. If there already is an open Java editor + * for the given element, it is returned. + * + * @param element + * the input element; either a compilation unit (ICompilationUnit) + * or a class file (
IClassFile) + * @return the editor, or null if wrong element type or + * opening failed + * @exception PartInitException + * if the editor could not be initialized + * @exception JavaModelException + * if this element does not exist or if an exception occurs + * while accessing its underlying resource + */ +// public static IEditorPart openInEditor(IJavaElement element) +// throws JavaModelException, PartInitException { +// return EditorUtility.openInEditor(element); +// } + + /** + * Reveals the source range of the given source reference element in the + * given editor. No checking is done if the editor displays a compilation + * unit or class file that contains the given source reference. The editor + * simply reveals the source range denoted by the given source reference. + * + * @param part + * the editor displaying the compilation unit or class file + * @param element + * the source reference element defining the source range to be + * revealed + * + * @deprecated use revealInEditor(IEditorPart, IJavaElement) + * instead + */ + // public static void revealInEditor(IEditorPart part, ISourceReference + // element) { + // if (element instanceof IJavaElement) + // revealInEditor(part, (IJavaElement) element); + // } + /** + * Reveals the given java element in the given editor. If the element is not + * an instance of ISourceReference this method result in a + * NOP. If it is a source reference no checking is done if the editor + * displays a compilation unit or class file that contains the source + * reference element. The editor simply reveals the source range denoted by + * the given element. + * + * @param part + * the editor displaying a compilation unit or class file + * @param element + * the element to be revealed + * + * @since 2.0 + */ + // public static void revealInEditor(IEditorPart part, IJavaElement element) + // { + // EditorUtility.revealInEditor(part, element); + // } + /** + * Returns the working copy manager for the Java UI plug-in. + * + * @return the working copy manager for the Java UI plug-in + */ +// public static IWorkingCopyManager getWorkingCopyManager() { +// return PHPeclipsePlugin.getDefault().getWorkingCopyManager(); +// } + + /** + * Answers the shared working copies currently registered for the Java + * plug-in. Note that the returned array can include working copies that are + * not on the class path of a Java project. + * + * @return the list of shared working copies + * + * @see net.sourceforge.phpdt.core.JavaCore#getSharedWorkingCopies(net.sourceforge.phpdt.core.IBufferFactory) + * @since 2.0 + */ +// public static IWorkingCopy[] getSharedWorkingCopies() { +// return JavaCore.getSharedWorkingCopies(getBufferFactory()); +// } + + /** + * Answers the shared working copies that are on the class path of a Java + * project currently registered for the Java plug-in. + * + * + * @return the list of shared working copies + * + * @see #getSharedWorkingCopies() + * @since 2.1 + */ + // public static IWorkingCopy[] getSharedWorkingCopiesOnClasspath() { + // IWorkingCopy[] wcs= getSharedWorkingCopies(); + // List result= new ArrayList(wcs.length); + // for (int i = 0; i < wcs.length; i++) { + // IWorkingCopy wc= wcs[i]; + // if (wc instanceof IJavaElement) { + // IJavaElement je= (IJavaElement)wc; + // if (je.getJavaProject().isOnClasspath(je)) { + // result.add(wc); + // } + // } + // } + // return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]); + // } + /** + * Returns the BufferFactory for the Java UI plug-in. + * + * @return the BufferFactory for the Java UI plug-in + * + * @see net.sourceforge.phpdt.core.IBufferFactory + * @since 2.0 + * @deprecated {@link IBufferFactory} has been replaced by + * {@link net.sourceforge.phpdt.core.WorkingCopyOwner}. The + * Java UI plug-in uses the primary working copy owner + * that can be accessed with null in API's that + * require an owner + */ + public static IBufferFactory getBufferFactory() { + return PHPeclipsePlugin.getDefault().getBufferFactory(); + } + + /** + * Returns the DocumentProvider used for Java compilation units. + * + * @return the DocumentProvider for Java compilation units. + * + * @see IDocumentProvider + * @since 2.0 + */ +// public static IDocumentProvider getDocumentProvider() { +// return PHPeclipsePlugin.getDefault() +// .getCompilationUnitDocumentProvider(); +// } + + /** + * Sets the Javadoc location for an archive with the given path. + * + * @param archivePath + * the path of the library; this can be an workspace path or an + * external path in case of an external library. + * @param url + * The Javadoc location to set. This location should contain + * index.html and a file 'package-list'. null + * clears the current documentation location. + * + * @since 2.0 + */ + // public static void setLibraryJavadocLocation(IPath archivePath, URL url) + // { + // JavaDocLocations.setLibraryJavadocLocation(archivePath, url); + // } + /** + * Returns the Javadoc location for an archive or null if no + * location is available. + * + * @param archivePath + * the path of the library. This can be an workspace path or an + * external path in case of an external library. + * + * @since 2.0 + */ + // public static URL getLibraryJavadocLocation(IPath archivePath) { + // return JavaDocLocations.getLibraryJavadocLocation(archivePath); + // } + /** + * Sets the Javadoc location for a Java project. This location is used for + * all types located in the project's source folders. + * + * @param project + * the project + * @param url + * The Javadoc location to set. This location should contain + * index.html and a file 'package-list'. null + * clears the current documentation location. + * + * @since 2.1 + */ + // public static void setProjectJavadocLocation(IJavaProject project, URL + // url) { + // JavaDocLocations.setProjectJavadocLocation(project, url); + // } + /** + * Returns the Javadoc location for a Java project or null if + * no location is available. This location is used for all types located in + * the project's source folders. + * + * @param project + * the project + * + * @since 2.1 + */ + // public static URL getProjectJavadocLocation(IJavaProject project) { + // return JavaDocLocations.getProjectJavadocLocation(project); + // } + /** + * Returns the Javadoc base URL for an element. The base location contains + * the index file. This location doesn't have to exist. Returns + * null if no javadoc location has been attached to the + * element's library or project. Example of a returned URL is http://www. + * junit. org/junit/javadoc. + * + * @param The + * element for which the doc URL is requested. + * + * @since 2.0 + */ + // public static URL getJavadocBaseLocation(IJavaElement element) throws + // JavaModelException { + // return JavaDocLocations.getJavadocBaseLocation(element); + // } + /** + * Returns the Javadoc URL for an element. Example of a returned URL is + * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html. + * This returned location doesn't have to exist. Returns null + * if no javadoc location has been attached to the element's library or + * project. + * + * @param The + * element for which the doc URL is requested. + * @param includeAnchor + * If set, the URL contains an anchor for member references: + * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult). + * Note that this involves type resolving and is a more expensive + * call than without anchor. + * + * @since 2.0 + */ + // public static URL getJavadocLocation(IJavaElement element, boolean + // includeAnchor) throws JavaModelException { + // return JavaDocLocations.getJavadocLocation(element, includeAnchor); + // } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java new file mode 100644 index 0000000..f35947f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java @@ -0,0 +1,223 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import net.sourceforge.phpdt.core.Flags; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; +import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.IDecoration; +import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ILightweightLabelDecorator; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; + +/** + * LabelDecorator that decorates an method's image with override or implements + * overlays. The viewer using this decorator is responsible for updating the + * images on element changes. + * + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * @since 2.0 + */ +public class OverrideIndicatorLabelDecorator implements ILabelDecorator, + ILightweightLabelDecorator { + + private ImageDescriptorRegistry fRegistry; + + private boolean fUseNewRegistry = false; + + /** + * Creates a decorator. The decorator creates an own image registry to cache + * images. + */ +// public OverrideIndicatorLabelDecorator() { +// this(null); +// fUseNewRegistry = true; +// } + + /* + * Creates decorator with a shared image registry. + * + * @param registry The registry to use or null to use the + * Java plugin's image registry. + */ + /** + * Note: This constructor is for internal use only. Clients should not call + * this constructor. + */ + public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) { + fRegistry = registry; + } + + private ImageDescriptorRegistry getRegistry() { + if (fRegistry == null) { + fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() + : PHPeclipsePlugin.getImageDescriptorRegistry(); + } + return fRegistry; + } + + /* + * (non-Javadoc) + * + * @see ILabelDecorator#decorateText(String, Object) + */ + public String decorateText(String text, Object element) { + return text; + } + + /* + * (non-Javadoc) + * + * @see ILabelDecorator#decorateImage(Image, Object) + */ + public Image decorateImage(Image image, Object element) { + int adornmentFlags = computeAdornmentFlags(element); + if (adornmentFlags != 0) { + ImageDescriptor baseImage = new ImageImageDescriptor(image); + Rectangle bounds = image.getBounds(); + return getRegistry().get( + new JavaElementImageDescriptor(baseImage, adornmentFlags, + new Point(bounds.width, bounds.height))); + } + return image; + } + + /** + * Note: This method is for internal use only. Clients should not call this + * method. + */ + public int computeAdornmentFlags(Object element) { + if (element instanceof IMethod) { + if (!PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) { + return 0; + } + + try { + IMethod method = (IMethod) element; + // if (!method.getJavaProject().isOnClasspath(method)) { + // return 0; + // } + + int flags = method.getFlags(); + IType type = method.getDeclaringType();// jsurfer INSERT + if (type != null && type.isClass() && !method.isConstructor() + && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) { + return getOverrideIndicators(method); + } + } catch (JavaModelException e) { + if (!e.isDoesNotExist()) { + PHPeclipsePlugin.log(e); + } + } + } + return 0; + } + + /** + * Note: This method is for internal use only. Clients should not call this + * method. + */ + protected int getOverrideIndicators(IMethod method) + throws JavaModelException { + //IType type = method.getDeclaringType(); + // ITypeHierarchy hierarchy= + // SuperTypeHierarchyCache.getTypeHierarchy(type); + // if (hierarchy != null) { + // return findInHierarchy(type, hierarchy, method.getElementName(), + // method.getParameterTypes()); + // } + return 0; + } + + /** + * Note: This method is for internal use only. Clients should not call this + * method. + */ + // protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, + // String name, String[] paramTypes) throws JavaModelException { + // IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, + // type, name, paramTypes, false); + // if (impl != null) { + // IMethod overridden= + // JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, + // paramTypes, false); + // if (overridden != null) { + // return JavaElementImageDescriptor.OVERRIDES; + // } else { + // return JavaElementImageDescriptor.IMPLEMENTS; + // } + // } + // return 0; + // } + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#addListener(ILabelProviderListener) + */ + public void addListener(ILabelProviderListener listener) { + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#dispose() + */ + public void dispose() { + if (fRegistry != null && fUseNewRegistry) { + fRegistry.dispose(); + } + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#isLabelProperty(Object, String) + */ + public boolean isLabelProperty(Object element, String property) { + return true; + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#removeListener(ILabelProviderListener) + */ + public void removeListener(ILabelProviderListener listener) { + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, + * org.eclipse.jface.viewers.IDecoration) + */ + public void decorate(Object element, IDecoration decoration) { + int adornmentFlags = computeAdornmentFlags(element); + if (adornmentFlags != 0) { + decoration.addOverlay(PHPUiImages.DESC_OVR_OVERRIDES); + } + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java new file mode 100644 index 0000000..60f8e03 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java @@ -0,0 +1,3070 @@ +/******************************************************************************* + * Copyright (c) 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import net.sourceforge.phpdt.core.IClasspathEntry; +import net.sourceforge.phpdt.internal.ui.text.spelling.SpellCheckEngine; +import net.sourceforge.phpdt.internal.ui.text.spelling.engine.ISpellCheckPreferenceKeys; +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; + +import org.eclipse.core.runtime.Platform; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +import org.eclipse.ui.texteditor.AbstractTextEditor; + +// +// import org.phpeclipse.phpdt.internal.ui.JavaPlugin; +// import +// org.phpeclipse.phpdt.internal.ui.preferences.NewJavaProjectPreferencePage; + +/** + * Preference constants used in the JDT-UI preference store. Clients should only + * read the JDT-UI preference store using these values. Clients are not allowed + * to modify the preference store programmatically. + * + * @since 2.0 + */ +public class PreferenceConstants { + + private PreferenceConstants() { + } + + /** + * A named preference that controls return type rendering of methods in the + * UI. + *

+ * Value is of type Boolean: if true return + * types are rendered + *

+ */ + public static final String APPEARANCE_METHOD_RETURNTYPE = "net.sourceforge.phpdt.ui.methodreturntype"; //$NON-NLS-1$ + + /** + * A named preference that controls if override indicators are rendered in + * the UI. + *

+ * Value is of type Boolean: if true override + * indicators are rendered + *

+ */ + public static final String APPEARANCE_OVERRIDE_INDICATOR = "net.sourceforge.phpdt.ui.overrideindicator"; //$NON-NLS-1$ + + /** + * A named preference that defines the pattern used for package name + * compression. + *

+ * Value is of type String. For example foe the given + * package name 'net.sourceforge.phpdt' pattern '.' will compress it to + * '..jdt', '1~' to 'o~.e~.jdt'. + *

+ */ + public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW = "PackagesView.pkgNamePatternForPackagesView"; //$NON-NLS-1$ + + /** + * A named preference that controls if package name compression is turned on + * or off. + *

+ * Value is of type Boolean. + *

+ * + * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW + */ + public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES = "net.sourceforge.phpdt.ui.compresspackagenames"; //$NON-NLS-1$ + + /** + * A named preference that controls if empty inner packages are folded in + * the hierarchical mode of the package explorer. + *

+ * Value is of type Boolean: if true empty + * inner packages are folded. + *

+ * + * @since 2.1 + */ + public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER = "net.sourceforge.phpdt.ui.flatPackagesInPackageExplorer"; //$NON-NLS-1$ + + /** + * A named preference that defines how member elements are ordered by the + * Java views using the JavaElementSorter. + *

+ * Value is of type String: A comma separated list of the + * following entries. Each entry must be in the list, no duplication. List + * order defines the sort order. + *

    + *
  • T : Types
  • + *
  • C : Constructors
  • + *
  • I : Initializers
  • + *
  • M : Methods
  • + *
  • F : Fields
  • + *
  • SI : Static Initializers
  • + *
  • SM : Static Methods
  • + *
  • SF : Static Fields
  • + *
+ *

+ * + * @since 2.1 + */ + public static final String APPEARANCE_MEMBER_SORT_ORDER = "outlinesortoption"; //$NON-NLS-1$ + + /** + * A named preference that defines how member elements are ordered by + * visibility in the Java views using the JavaElementSorter. + *

+ * Value is of type String: A comma separated list of the + * following entries. Each entry must be in the list, no duplication. List + * order defines the sort order. + *

    + *
  • B : Public
  • + *
  • V : Private
  • + *
  • R : Protected
  • + *
  • D : Default
  • + *
+ *

+ * + * @since 3.0 + */ + public static final String APPEARANCE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.visibility.order"; //$NON-NLS-1$ + + /** + * A named preferences that controls if Java elements are also sorted by + * visibility. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER = "net.sourceforge.phpdt.ui.enable.visibility.order"; //$NON-NLS-1$ + + /** + * A named preference that controls if prefix removal during setter/getter + * generation is turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public static final String CODEGEN_USE_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.enable"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of prefixes to be removed from a + * local variable to compute setter and gettter names. + *

+ * Value is of type String: comma separated list of prefixed + *

+ * + * @see #CODEGEN_USE_GETTERSETTER_PREFIX + */ + public static final String CODEGEN_GETTERSETTER_PREFIX = "net.sourceforge.phpdt.ui.gettersetter.prefix.list"; //$NON-NLS-1$ + + /** + * A named preference that controls if suffix removal during setter/getter + * generation is turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public static final String CODEGEN_USE_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.enable"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of suffixes to be removed from a + * local variable to compute setter and getter names. + *

+ * Value is of type String: comma separated list of suffixes + *

+ * + * @see #CODEGEN_USE_GETTERSETTER_SUFFIX + */ + public static final String CODEGEN_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the keyword "this" will be added + * automatically to field accesses in generated methods. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String CODEGEN_KEYWORD_THIS = "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ + + /** + * A named preference that controls whether to use the prefix "is" or the + * prefix "get" for automatically created getters which return a boolean + * field. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String CODEGEN_IS_FOR_GETTERS = "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ + + /** + * A named preference that defines the preferred variable names for + * exceptions in catch clauses. + *

+ * Value is of type String. + *

+ * + * @since 3.0 + */ + public static final String CODEGEN_EXCEPTION_VAR_NAME = "org.eclipse.jdt.ui.exception.name"; //$NON-NLS-1$ + + /** + * A named preference that controls if comment stubs will be added + * automatically to newly created types and methods. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public static final String CODEGEN_ADD_COMMENTS = "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ + + /** + * A name preference that controls if a JavaDoc stub gets added to newly + * created types and methods. + *

+ * Value is of type Boolean. + *

+ * + * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). + */ + // public static final String CODEGEN__JAVADOC_STUBS = CODEGEN_ADD_COMMENTS; + // //$NON-NLS-1$ + /** + * A named preference that controls if a non-phpdoc comment gets added to + * methods generated via the "Override Methods" operation. + *

+ * Value is of type Boolean. + *

+ */ + public static final String CODEGEN__NON_JAVADOC_COMMENTS = "net.sourceforge.phpdt.ui.seecomments"; //$NON-NLS-1$ + + /** + * A named preference that controls if a file comment gets added to newly + * created files. + *

+ * Value is of type Boolean. + *

+ */ + public static final String CODEGEN__FILE_COMMENTS = "net.sourceforge.phpdt.ui.filecomments"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of comma separated package names. + * The list specifies the import order used by the "Organize Imports" + * opeation. + *

+ * Value is of type String: semicolon separated list of + * package names + *

+ */ + // public static final String ORGIMPORTS_IMPORTORDER = + // "net.sourceforge.phpdt.ui.importorder"; //$NON-NLS-1$ + /** + * A named preference that specifies the number of imports added before a + * star-import declaration is used. + *

+ * Value is of type Int: positive value specifing the number + * of non star-import is used + *

+ */ + public static final String ORGIMPORTS_ONDEMANDTHRESHOLD = "net.sourceforge.phpdt.ui.ondemandthreshold"; //$NON-NLS-1$ + + /** + * A named preferences that controls if types that start with a lower case + * letters get added by the "Organize Import" operation. + *

+ * Value is of type Boolean. + *

+ */ + public static final String ORGIMPORTS_IGNORELOWERCASE = "net.sourceforge.phpdt.ui.ignorelowercasenames"; //$NON-NLS-1$ + + /** + * A named preference that speficies whether children of a compilation unit + * are shown in the package explorer. + *

+ * Value is of type Boolean. + *

+ */ + public static final String SHOW_CU_CHILDREN = "net.sourceforge.phpdt.ui.packages.cuchildren"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the package explorer's selection + * is linked to the active editor. + *

+ * Value is of type Boolean. + *

+ */ + public static final String LINK_PACKAGES_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the hierarchy view's selection + * is linked to the active editor. + *

+ * Value is of type Boolean. + *

+ */ + public static final String LINK_TYPEHIERARCHY_TO_EDITOR = "net.sourceforge.phpdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the browsing view's selection is + * linked to the active editor. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public static final String LINK_BROWSING_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether new projects are generated using + * source and output folder. + *

+ * Value is of type Boolean. if true new + * projects are created with a source and output folder. If + * false source and output folder equals to the project. + *

+ */ + public static final String SRCBIN_FOLDERS_IN_NEWPROJ = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ + + /** + * A named preference that specifies the source folder name used when + * creating a new Java project. Value is inactive if + * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. + *

+ * Value is of type String. + *

+ * + * @see #SRCBIN_FOLDERS_IN_NEWPROJ + */ + public static final String SRCBIN_SRCNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ + + /** + * A named preference that specifies the output folder name used when + * creating a new Java project. Value is inactive if + * SRCBIN_FOLDERS_IN_NEWPROJ is set to false. + *

+ * Value is of type String. + *

+ * + * @see #SRCBIN_FOLDERS_IN_NEWPROJ + */ + public static final String SRCBIN_BINNAME = "net.sourceforge.phpdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ + + /** + * A named preference that holds a list of possible JRE libraries used by + * the New Java Project wizard. An library consists of a description and an + * arbitrary number of IClasspathEntrys, that will represent + * the JRE on the new project's classpath. + *

+ * Value is of type String: a semicolon separated list of + * encoded JRE libraries. NEWPROJECT_JRELIBRARY_INDEX defines + * the currently used library. Clients should use the method + * encodeJRELibrary to encode a JRE library into a string and + * the methods decodeJRELibraryDescription(String) and + * decodeJRELibraryClasspathEntries(String) + * to decode the description and the array of classpath entries from an + * encoded string. + *

+ * + * @see #NEWPROJECT_JRELIBRARY_INDEX + * @see #encodeJRELibrary(String, IClasspathEntry[]) + * @see #decodeJRELibraryDescription(String) + * @see #decodeJRELibraryClasspathEntries(String) + */ + public static final String NEWPROJECT_JRELIBRARY_LIST = "net.sourceforge.phpdt.ui.wizards.jre.list"; //$NON-NLS-1$ + + /** + * A named preferences that specifies the current active JRE library. + *

+ * Value is of type Int: an index into the list of possible + * JRE libraries. + *

+ * + * @see #NEWPROJECT_JRELIBRARY_LIST + */ + public static final String NEWPROJECT_JRELIBRARY_INDEX = "net.sourceforge.phpdt.ui.wizards.jre.index"; //$NON-NLS-1$ + + /** + * A named preference that controls if a new type hierarchy gets opened in a + * new type hierarchy perspective or inside the type hierarchy view part. + *

+ * Value is of type String: possible values are + * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE + * or + * OPEN_TYPE_HIERARCHY_IN_VIEW_PART. + *

+ * + * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE + * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART + */ + public static final String OPEN_TYPE_HIERARCHY = "net.sourceforge.phpdt.ui.openTypeHierarchy"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * OPEN_TYPE_HIERARCHY. + * + * @see #OPEN_TYPE_HIERARCHY + */ + public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE = "perspective"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * OPEN_TYPE_HIERARCHY. + * + * @see #OPEN_TYPE_HIERARCHY + */ + public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART = "viewPart"; //$NON-NLS-1$ + + /** + * A named preference that controls the behaviour when double clicking on a + * container in the packages view. + *

+ * Value is of type String: possible values are + * DOUBLE_CLICK_GOES_INTO + * or + * DOUBLE_CLICK_EXPANDS. + *

+ * + * @see #DOUBLE_CLICK_EXPANDS + * @see #DOUBLE_CLICK_GOES_INTO + */ + public static final String DOUBLE_CLICK = "packageview.doubleclick"; //$NON-NLS-1$ + + /** + * A string value used by the named preference DOUBLE_CLICK. + * + * @see #DOUBLE_CLICK + */ + public static final String DOUBLE_CLICK_GOES_INTO = "packageview.gointo"; //$NON-NLS-1$ + + /** + * A string value used by the named preference DOUBLE_CLICK. + * + * @see #DOUBLE_CLICK + */ + public static final String DOUBLE_CLICK_EXPANDS = "packageview.doubleclick.expands"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Java views update their + * presentation while editing or when saving the content of an editor. + *

+ * Value is of type String: possible values are + * UPDATE_ON_SAVE + * or + * UPDATE_WHILE_EDITING. + *

+ * + * @see #UPDATE_ON_SAVE + * @see #UPDATE_WHILE_EDITING + */ + public static final String UPDATE_JAVA_VIEWS = "JavaUI.update"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * UPDATE_JAVA_VIEWS + * + * @see #UPDATE_JAVA_VIEWS + */ + public static final String UPDATE_ON_SAVE = "JavaUI.update.onSave"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * UPDATE_JAVA_VIEWS + * + * @see #UPDATE_JAVA_VIEWS + */ + public static final String UPDATE_WHILE_EDITING = "JavaUI.update.whileEditing"; //$NON-NLS-1$ + + /** + * A named preference that holds the path of the Javadoc command used by the + * Javadoc creation wizard. + *

+ * Value is of type String. + *

+ */ + public static final String JAVADOC_COMMAND = "command"; //$NON-NLS-1$ + + /** + * A named preference that defines whether hint to make hover sticky should + * be shown. + * + * @see JavaUI + * @since 3.0 + */ + public static final String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE = "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ + + /** + * A named preference that defines the key for the hover modifiers. + * + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_TEXT_HOVER_MODIFIERS = "hoverModifiers"; //$NON-NLS-1$ + + /** + * The id of the best match hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_BESTMATCH_HOVER = "net.sourceforge.phpdt.ui.BestMatchHover"; //$NON-NLS-1$ + + /** + * The id of the source code hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_SOURCE_HOVER = "net.sourceforge.phpdt.ui.JavaSourceHover"; //$NON-NLS-1$ + + /** + * The id of the problem hover contributed for extension point + * javaEditorTextHovers. + * + * @since 2.1 + */ + public static String ID_PROBLEM_HOVER = "net.sourceforge.phpdt.ui.ProblemHover"; //$NON-NLS-1$ + + /** + * A named preference that controls whether bracket matching highlighting is + * turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_MATCHING_BRACKETS = "matchingBrackets"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to highlight matching + * brackets. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_MATCHING_BRACKETS_COLOR = "matchingBracketsColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the current line highlighting is + * turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_CURRENT_LINE = "currentLine"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to highlight the current + * line. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_CURRENT_LINE_COLOR = "currentLineColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the print margin is turned on or + * off. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PRINT_MARGIN = "printMargin"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render the print margin. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PRINT_MARGIN_COLOR = "printMarginColor"; //$NON-NLS-1$ + + /** + * Print margin column. Int value. + */ + public final static String EDITOR_PRINT_MARGIN_COLUMN = "printMarginColumn"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used for the find/replace scope. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_FIND_SCOPE_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; + + /** + * A named preference that specifies if the editor uses spaces for tabs. + *

+ * Value is of type Boolean. If true spaces + * instead of tabs are used in the editor. If false the + * editor inserts a tab character when pressing the tab key. + *

+ */ + public final static String EDITOR_SPACES_FOR_TABS = "spacesForTabs"; //$NON-NLS-1$ + + /** + * A named preference that holds the number of spaces used per tab in the + * editor. + *

+ * Value is of type Int: positive int value specifying the + * number of spaces per tab. + *

+ */ + public final static String EDITOR_TAB_WIDTH = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH; // "net.sourceforge.phpdt.ui.editor.tab.width"; + + // //$NON-NLS-1$ + + /** + * A named preference that controls whether the outline view selection + * should stay in sync with with the element at the current cursor position. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE = "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ + + /** + * A named preference that controls if correction indicators are shown in + * the UI. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_CORRECTION_INDICATION = "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows problem + * indicators in text (squiggly lines). + *

+ * Value is of type Boolean. + *

+ */ + // public final static String EDITOR_PROBLEM_INDICATION = + // "problemIndication"; //$NON-NLS-1$ + /** + * A named preference that holds the color used to render problem + * indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_PROBLEM_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + // public final static String EDITOR_PROBLEM_INDICATION_COLOR = + // "problemIndicationColor"; //$NON-NLS-1$ + /** + * PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; A named preference + * that controls whether the editor shows warning indicators in text + * (squiggly lines). + *

+ * Value is of type Boolean. + *

+ */ + // public final static String EDITOR_WARNING_INDICATION = + // "warningIndication"; //$NON-NLS-1$ + /** + * A named preference that holds the color used to render warning + * indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_WARNING_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + // public final static String EDITOR_WARNING_INDICATION_COLOR = + // "warningIndicationColor"; //$NON-NLS-1$ + /** + * A named preference that controls whether the editor shows task indicators + * in text (squiggly lines). + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_TASK_INDICATION = "taskIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render task indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_TASK_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_TASK_INDICATION_COLOR = "taskIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows bookmark + * indicators in text (squiggly lines). + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION = "bookmarkIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render bookmark + * indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_BOOKMARK_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION_COLOR = "bookmarkIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows search + * indicators in text (squiggly lines). + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION = "searchResultIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render search indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_SEARCH_RESULT_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR = "searchResultIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the editor shows unknown + * indicators in text (squiggly lines). + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION = "othersIndication"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render unknown + * indicators. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see #EDITOR_UNKNOWN_INDICATION + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION_COLOR = "othersIndicationColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows error + * indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER = "errorIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows warning + * indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER = "warningIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows task + * indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER = "taskIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows + * bookmark indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER = "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows search + * result indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the overview ruler shows unknown + * indicators. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER = "othersIndicationInOverviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in PHP mode + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_CLOSE_STRINGS_DQ_PHP = "closeStringsPHPDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in PHP mode + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_CLOSE_STRINGS_SQ_PHP = "closeStringsPHPSQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close brackets' feature is + * enabled in PHP mode + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACKETS_PHP = "closeBracketsPHP"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap words' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_WRAP_WORDS = "wrapWords"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap strings' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_WRAP_STRINGS_DQ = "wrapStringsDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'escape strings' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_ESCAPE_STRINGS_DQ = "escapeStringsDQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'wrap strings' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_WRAP_STRINGS_SQ = "wrapStringsSQ"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'escape strings' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_ESCAPE_STRINGS_SQ = "escapeStringsSQ"; //$NON-NLS-1$ + + /** + * A named preference that controls if content assist inserts the common + * prefix of all proposals before presenting choices. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String CODEASSIST_PREFIX_COMPLETION = "content_assist_prefix_completion"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close braces' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACES = "closeBraces"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close php docs' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_JAVADOCS = "closeJavaDocs"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'add JavaDoc tags' feature + * is enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_ADD_JAVADOC_TAGS = "addJavaDocTags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'format Javadoc tags' + * feature is enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_FORMAT_JAVADOCS = "formatJavaDocs"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'smart paste' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SMART_PASTE = "smartPaste"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close strings' feature is + * enabled in HTML mode + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_STRINGS_HTML = "closeStringsHTML"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'close brackets' feature is + * enabled in HTML mode + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_CLOSE_BRACKETS_HTML = "closeBracketsHTML"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the 'smart home-end' feature is + * enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SMART_HOME_END = AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; + + /** + * A named preference that controls whether the 'sub-word navigation' + * feature is enabled. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_SUB_WORD_NAVIGATION = "subWordNavigation"; //$NON-NLS-1$ + + /** + * A named preference that controls if temporary problems are evaluated and + * shown in the UI. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = "handleTemporaryProblems"; //$NON-NLS-1$ + + /** + * A named preference that controls if the overview ruler is shown in the + * UI. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_OVERVIEW_RULER = "overviewRuler"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render linked positions + * inside code templates. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_LINKED_POSITION_COLOR = "linkedPositionColor"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used as the text foreground. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_FOREGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; + + /** + * A named preference that describes if the system default foreground color + * is used as the text foreground. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_FOREGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; + + /** + * A named preference that holds the color used as the text background. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_BACKGROUND_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; + + /** + * A named preference that describes if the system default background color + * is used as the text foreground. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_BACKGROUND_DEFAULT_COLOR = AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; + + /** + * Preference key suffix for bold text style preference keys. + */ + public static final String EDITOR_BOLD_SUFFIX = "_bold"; //$NON-NLS-1$ + + /** + * Preference key suffix for bold text style preference keys. + */ + public static final String EDITOR_ITALIC_SUFFIX = "_italic"; //$NON-NLS-1$ + + /** + * A named preference that holds the color used to render multi line + * comments. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_MULTI_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_MULTILINE_COMMENT; + + /** + * The symbolic font name for the Java editor text font (value + * "net.sourceforge.phpdt.ui.editors.textfont"). + * + * @since 2.1 + */ + public final static String EDITOR_TEXT_FONT = "net.sourceforge.phpdt.ui.editors.textfont"; //$NON-NLS-1$ + + /** + * A named preference that controls whether multi line comments are rendered + * in bold. + *

+ * Value is of type Boolean. If true multi + * line comments are rendered in bold. If false the are + * rendered using no font style attribute. + *

+ */ + public final static String EDITOR_MULTI_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_MULTILINE_COMMENT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render single line + * comments. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR = IPreferenceConstants.PHP_SINGLELINE_COMMENT; + + /** + * A named preference that controls whether sinle line comments are rendered + * in bold. + *

+ * Value is of type Boolean. If true single + * line comments are rendered in bold. If false the are + * rendered using no font style attribute. + *

+ */ + public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_SINGLELINE_COMMENT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_COLOR = IPreferenceConstants.PHP_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_BOLD = IPreferenceConstants.PHP_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_OPERATOR_ITALIC = IPreferenceConstants.PHP_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render operators and + * brackets. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_COLOR = IPreferenceConstants.PHP_BRACE_OPERATOR; + + /** + * A named preference that controls whether operators and brackets are + * rendered in bold. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_BOLD = IPreferenceConstants.PHP_BRACE_OPERATOR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether operators and brackets are + * rendered in italic. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_BRACE_OPERATOR_ITALIC = IPreferenceConstants.PHP_BRACE_OPERATOR + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render the 'return' + * keyword. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_COLOR = IPreferenceConstants.PHP_KEYWORD_RETURN; + + /** + * A named preference that controls whether 'return' keyword is rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_BOLD = IPreferenceConstants.PHP_KEYWORD_RETURN + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that controls whether 'return' keyword is rendered in + * italic. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String EDITOR_PHP_KEYWORD_RETURN_ITALIC = IPreferenceConstants.PHP_KEYWORD_RETURN + + EDITOR_ITALIC_SUFFIX; + + /** + * A named preference that holds the color used to render php start and stop + * tags. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_TAG_COLOR = IPreferenceConstants.PHP_TAG; + + /** + * A named preference that controls whether php start and stop tags are + * rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_TAG_BOLD = IPreferenceConstants.PHP_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php keywords. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVA_KEYWORD_COLOR = IPreferenceConstants.PHP_KEYWORD; + + /** + * A named preference that controls whether keywords are rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVA_KEYWORD_BOLD = IPreferenceConstants.PHP_KEYWORD + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render predefined php + * function names. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_FUNCTIONNAME_COLOR = IPreferenceConstants.PHP_FUNCTIONNAME; + + /** + * A named preference that controls whether function names are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_FUNCTIONNAME_BOLD = IPreferenceConstants.PHP_FUNCTIONNAME + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php variables with + * prefix '$_'. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_VARIABLE_DOLLAR_COLOR = IPreferenceConstants.PHP_VARIABLE_DOLLAR; + + /** + * A named preference that controls whether variables with prefix '$_' are + * rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_VARIABLE_DOLLAR_BOLD = IPreferenceConstants.PHP_VARIABLE_DOLLAR + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php variables. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_VARIABLE_COLOR = IPreferenceConstants.PHP_VARIABLE; + + /** + * A named preference that controls whether variables are rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_VARIABLE_BOLD = IPreferenceConstants.PHP_VARIABLE + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php constants. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_CONSTANT_COLOR = IPreferenceConstants.PHP_CONSTANT; + + /** + * A named preference that controls whether constants are rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_CONSTANT_BOLD = IPreferenceConstants.PHP_CONSTANT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php types. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_PHP_TYPE_COLOR = IPreferenceConstants.PHP_TYPE; + + /** + * A named preference that controls whether types are rendered in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_PHP_TYPE_BOLD = IPreferenceConstants.PHP_TYPE + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render string constants. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_STRING_COLOR_DQ = IPreferenceConstants.PHP_STRING_DQ; + + /** + * A named preference that controls whether string constants are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_STRING_BOLD_DQ = IPreferenceConstants.PHP_STRING_DQ + + EDITOR_BOLD_SUFFIX; + + public final static String EDITOR_STRING_COLOR_SQ = IPreferenceConstants.PHP_STRING_SQ; + + /** + * A named preference that controls whether string constants are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_STRING_BOLD_SQ = IPreferenceConstants.PHP_STRING_SQ + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render php default text. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVA_DEFAULT_COLOR = IPreferenceConstants.PHP_DEFAULT; + + /** + * A named preference that controls whether Java default text is rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVA_DEFAULT_BOLD = IPreferenceConstants.PHP_DEFAULT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render task tags. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_TASK_TAG_COLOR = IPreferenceConstants.TASK_TAG; + + /** + * A named preference that controls whether task tags are rendered in bold. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String EDITOR_TASK_TAG_BOLD = IPreferenceConstants.TASK_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc keywords. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_KEYWORD_COLOR = IPreferenceConstants.PHPDOC_KEYWORD; + + /** + * A named preference that controls whether phpdoc keywords are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVADOC_KEYWORD_BOLD = IPreferenceConstants.PHPDOC_KEYWORD + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc tags. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_TAG_COLOR = IPreferenceConstants.PHPDOC_TAG; + + /** + * A named preference that controls whether phpdoc tags are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVADOC_TAG_BOLD = IPreferenceConstants.PHPDOC_TAG + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc links. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_LINKS_COLOR = IPreferenceConstants.PHPDOC_LINK; + + /** + * A named preference that controls whether phpdoc links are rendered in + * bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVADOC_LINKS_BOLD = IPreferenceConstants.PHPDOC_LINK + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used to render phpdoc default + * text. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String EDITOR_JAVADOC_DEFAULT_COLOR = IPreferenceConstants.PHPDOC_DEFAULT; + + /** + * A named preference that controls whether phpdoc default text is rendered + * in bold. + *

+ * Value is of type Boolean. + *

+ */ + public final static String EDITOR_JAVADOC_DEFAULT_BOLD = IPreferenceConstants.PHPDOC_DEFAULT + + EDITOR_BOLD_SUFFIX; + + /** + * A named preference that holds the color used for 'linked-mode' underline. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String EDITOR_LINK_COLOR = "linkColor"; //$NON-NLS-1$ + + /** + * A named preference that controls whether hover tooltips in the editor are + * turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public static final String EDITOR_SHOW_HOVER = "net.sourceforge.phpdt.ui.editor.showHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when no control key is + * pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_NONE_HOVER = "noneHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL modifier key is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI + * @since 2.1 + */ + public static final String EDITOR_CTRL_HOVER = "ctrlHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * SHIFT modifier key is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_SHIFT_HOVER = "shiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + ALT modifier keys is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_ALT_HOVER = "ctrlAltHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + ALT + SHIFT modifier keys is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_ALT_SHIFT_HOVER = "ctrlAltShiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the + * CTRL + SHIFT modifier keys is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_CTRL_SHIFT_HOVER = "ctrlShiftHover"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover shown when the ALT + * modifier key is pressed. + *

+ * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID, + * EDITOR_DEFAULT_HOVER_CONFIGURED_ID or the hover id of a + * hover contributed as phpEditorTextHovers. + *

+ * + * @see #EDITOR_NO_HOVER_CONFIGURED_ID + * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID + * @see JavaUI ID_*_HOVER + * @since 2.1 + */ + public static final String EDITOR_ALT_SHIFT_HOVER = "altShiftHover"; //$NON-NLS-1$ + + /** + * A string value used by the named preferences for hover configuration to + * descibe that no hover should be shown for the given key modifiers. + * + * @since 2.1 + */ + public static final String EDITOR_NO_HOVER_CONFIGURED_ID = "noHoverConfiguredId"; //$NON-NLS-1$ + + /** + * A string value used by the named preferences for hover configuration to + * descibe that the default hover should be shown for the given key + * modifiers. The default hover is described by the + * EDITOR_DEFAULT_HOVER property. + * + * @since 2.1 + */ + public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID = "defaultHoverConfiguredId"; //$NON-NLS-1$ + + /** + * A named preference that defines the hover named the 'default hover'. + * Value is of type String: possible values are + * EDITOR_NO_HOVER_CONFIGURED_ID + * or the hover id of a hover + * contributed as phpEditorTextHovers. + *

+ *@since 2.1 + */ + public static final String EDITOR_DEFAULT_HOVER = "defaultHover"; //$NON-NLS-1$ + + /** + * A named preference that controls if segmented view (show selected element + * only) is turned on or off. + *

+ * Value is of type Boolean. + *

+ */ + public static final String EDITOR_SHOW_SEGMENTS = "net.sourceforge.phpdt.ui.editor.showSegments"; //$NON-NLS-1$ + + /** + * A named preference that controls if browser like links are turned on or + * off. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS = "browserLikeLinks"; //$NON-NLS-1$ + + /** + * A named preference that controls the key modifier for browser like links. + *

+ * Value is of type String. + *

+ * + * @since 2.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER = "browserLikeLinksKeyModifier"; //$NON-NLS-1$ + + /** + * A named preference that controls whether occurrences are marked in the + * editor. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_MARK_OCCURRENCES = "markOccurrences"; //$NON-NLS-1$ + + /** + * A named preference that controls whether occurrences are sticky in the + * editor. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_STICKY_OCCURRENCES = "stickyOccurrences"; //$NON-NLS-1$ + + /** + * A named preference that controls disabling of the overwrite mode. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_DISABLE_OVERWRITE_MODE = "disable_overwrite_mode"; //$NON-NLS-1$ + + /** + * A named preference that controls saving of a file on loss of editor focus. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_SAVE_ON_BLUR = "save_on_blur"; //$NON-NLS-1$ + + /** + * A named preference that controls the "smart semicolon" smart typing + * handler + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_SMART_SEMICOLON = "smart_semicolon"; //$NON-NLS-1$ + + /** + * A named preference that controls the smart backspace behavior. + *

+ * Value is of type Boolean. + * + * @since 3.0 + */ + public static final String EDITOR_SMART_BACKSPACE = "smart_backspace"; //$NON-NLS-1$ + + /** + * A named preference that controls the "smart opening brace" smart typing + * handler + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_SMART_OPENING_BRACE = "smart_opening_brace"; //$NON-NLS-1$ + + /** + * A named preference that controls the smart tab behaviour. + *

+ * Value is of type Boolean. + * + * @since 3.0 + */ + public static final String EDITOR_SMART_TAB = "smart_tab"; //$NON-NLS-1$ + + public static final String EDITOR_P_RTRIM_ON_SAVE = "editor_p_trim_on_save"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Java comments should be + * spell-checked. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_CHECK_SPELLING = ISpellCheckPreferenceKeys.SPELLING_CHECK_SPELLING; + + /** + * A named preference that controls whether words containing digits should + * be skipped during spell-checking. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_DIGITS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS; + + /** + * A named preference that controls whether mixed case words should be + * skipped during spell-checking. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_MIXED = ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED; + + /** + * A named preference that controls whether sentence capitalization should + * be ignored during spell-checking. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_SENTENCE = ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE; + + /** + * A named preference that controls whether upper case words should be + * skipped during spell-checking. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_UPPER = ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER; + + /** + * A named preference that controls whether urls should be ignored during + * spell-checking. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_IGNORE_URLS = ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS; + + /** + * A named preference that controls the locale used for spell-checking. + *

+ * Value is of type String. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_LOCALE = ISpellCheckPreferenceKeys.SPELLING_LOCALE; + + /** + * A named preference that controls the number of proposals offered during + * spell-checking. + *

+ * Value is of type Integer. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_PROPOSAL_THRESHOLD = ISpellCheckPreferenceKeys.SPELLING_PROPOSAL_THRESHOLD; + + /** + * A named preference that specifies the workspace user dictionary. + *

+ * Value is of type Integer. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_USER_DICTIONARY = ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY; + + /** + * A named preference that specifies whether spelling dictionaries are + * available to content assist. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String SPELLING_ENABLE_CONTENTASSIST = ISpellCheckPreferenceKeys.SPELLING_ENABLE_CONTENTASSIST; + + /** + * A named preference that controls whether code snippets are formatted in + * Javadoc comments. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATSOURCE = "comment_format_source_code"; //$NON-NLS-1$ + + /** + * A named preference that controls whether description of Javadoc + * parameters are indented. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION = "comment_indent_parameter_description"; //$NON-NLS-1$ + + /** + * A named preference that controls whether the header comment of a Java + * source file is formatted. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATHEADER = "comment_format_header"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Javadoc root tags are indented. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_INDENTROOTTAGS = "comment_indent_root_tags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether Javadoc comments are formatted + * by the content formatter. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMAT = "comment_format_comments"; //$NON-NLS-1$ + + /** + * A named preference that controls whether a new line is inserted after + * Javadoc root tag parameters. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER = "comment_new_line_for_parameter"; //$NON-NLS-1$ + + /** + * A named preference that controls whether an empty line is inserted before + * the Javadoc root tag block. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS = "comment_separate_root_tags"; //$NON-NLS-1$ + + /** + * A named preference that controls whether blank lines are cleared during + * formatting + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_CLEARBLANKLINES = "comment_clear_blank_lines"; //$NON-NLS-1$ + + /** + * A named preference that controls the line length of comments. + *

+ * Value is of type Integer. The value must be at least 4 + * for reasonable formatting. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_LINELENGTH = "comment_line_length"; //$NON-NLS-1$ + + /** + * A named preference that controls whether html tags are formatted. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public final static String FORMATTER_COMMENT_FORMATHTML = "comment_format_html"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist gets auto + * activated. + *

+ * Value is of type Boolean. + *

+ */ + public final static String CODEASSIST_AUTOACTIVATION = "content_assist_autoactivation"; //$NON-NLS-1$ + + /** + * A name preference that holds the auto activation delay time in milli + * seconds. + *

+ * Value is of type Int. + *

+ */ + public final static String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay"; //$NON-NLS-1$ + + /** + * A named preference that controls if code assist contains only visible + * proposals. + *

+ * Value is of type Boolean. if + * true code assist only contains visible members. If + * false all members are included. + *

+ */ + public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS = "content_assist_show_visible_proposals"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist inserts a + * proposal automatically if only one proposal is available. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String CODEASSIST_AUTOINSERT = "content_assist_autoinsert"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist adds import + * statements. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String CODEASSIST_ADDIMPORT = "content_assist_add_import"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java code assist only inserts + * completions. If set to false the proposals can also _replace_ code. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String CODEASSIST_INSERT_COMPLETION = "content_assist_insert_completion"; //$NON-NLS-1$ + + /** + * A named preference that controls whether code assist proposals filtering + * is case sensitive or not. + *

+ * Value is of type Boolean. + *

+ */ + public final static String CODEASSIST_CASE_SENSITIVITY = "content_assist_case_sensitivity"; //$NON-NLS-1$ + + /** + * A named preference that defines if code assist proposals are sorted in + * alphabetical order. + *

+ * Value is of type Boolean. If true that are + * sorted in alphabetical order. If false that are unsorted. + *

+ */ + public final static String CODEASSIST_ORDER_PROPOSALS = "content_assist_order_proposals"; //$NON-NLS-1$ + + /** + * A named preference that controls if argument names are filled in when a + * method is selected from as list of code assist proposal. + *

+ * Value is of type Boolean. + *

+ */ + public final static String CODEASSIST_FILL_ARGUMENT_NAMES = "content_assist_fill_method_arguments"; //$NON-NLS-1$ + + /** + * A named preference that controls if method arguments are guessed when a + * method is selected from as list of code assist proposal. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS = "content_assist_guess_method_arguments"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in PHP code. + *

+ * Value is of type Sring. All characters that trigger auto + * code assist in PHP code. + *

+ */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA = "content_assist_autoactivation_triggers_php"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in PHPDoc. + *

+ * Value is of type Sring. All characters that trigger auto + * code assist in PHPDoc. + *

+ */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC = "content_assist_autoactivation_triggers_phpdoc"; //$NON-NLS-1$ + + /** + * A named preference that holds the characters that auto activate code + * assist in HTML. + *

+ * Value is of type Sring. All characters that trigger auto + * code assist in HTML. + *

+ */ + public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML = "content_assist_autoactivation_triggers_html"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used in the code + * assist selection dialog. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used for parameter + * hints. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PARAMETERS_BACKGROUND = "content_assist_parameters_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + */ + public final static String CODEASSIST_PARAMETERS_FOREGROUND = "content_assist_parameters_foreground"; //$NON-NLS-1$ + + /** + * A named preference that holds the background color used in the code + * assist selection dialog to mark replaced code. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String CODEASSIST_REPLACEMENT_BACKGROUND = "content_assist_completion_replacement_background"; //$NON-NLS-1$ + + /** + * A named preference that holds the foreground color used in the code + * assist selection dialog to mark replaced code. + *

+ * Value is of type String. A RGB color value encoded as a + * string using class PreferenceConverter + *

+ * + * @see org.eclipse.jface.resource.StringConverter + * @see org.eclipse.jface.preference.PreferenceConverter + * @since 2.1 + */ + public final static String CODEASSIST_REPLACEMENT_FOREGROUND = "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ + + /** + * A named preference that controls the behaviour of the refactoring wizard + * for showing the error page. + *

+ * Value is of type String. Valid values are: + * REFACTOR_FATAL_SEVERITY, + * REFACTOR_ERROR_SEVERITY,REFACTOR_WARNING_SEVERITY + * REFACTOR_INFO_SEVERITY, + * REFACTOR_OK_SEVERITY. + *

+ * + * @see #REFACTOR_FATAL_SEVERITY + * @see #REFACTOR_ERROR_SEVERITY + * @see #REFACTOR_WARNING_SEVERITY + * @see #REFACTOR_INFO_SEVERITY + * @see #REFACTOR_OK_SEVERITY + */ + public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD = "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_FATAL_SEVERITY = "4"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_ERROR_SEVERITY = "3"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_WARNING_SEVERITY = "2"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_INFO_SEVERITY = "1"; //$NON-NLS-1$ + + /** + * A string value used by the named preference + * REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD. + * + * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD + */ + public static final String REFACTOR_OK_SEVERITY = "0"; //$NON-NLS-1$ + + /** + * A named preference thet controls whether all dirty editors are + * automatically saved before a refactoring is executed. + *

+ * Value is of type Boolean. + *

+ */ + public static final String REFACTOR_SAVE_ALL_EDITORS = "Refactoring.savealleditors"; //$NON-NLS-1$ + + /** + * A named preference that controls if the Java Browsing views are linked to + * the active editor. + *

+ * Value is of type Boolean. + *

+ * + * @see #LINK_PACKAGES_TO_EDITOR + */ + public static final String BROWSING_LINK_VIEW_TO_EDITOR = "net.sourceforge.phpdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ + + /** + * A named preference that controls the layout of the Java Browsing views + * vertically. Boolean value. + *

+ * Value is of type Boolean. If + * true the views are stacked vertical. + * If false they are stacked horizontal. + *

+ */ + public static final String BROWSING_STACK_VERTICALLY = "net.sourceforge.phpdt.ui.browsing.stackVertically"; //$NON-NLS-1$ + + /** + * A named preference that controls if templates are formatted when applied. + *

+ * Value is of type Boolean. + *

+ * + * @since 2.1 + */ + public static final String TEMPLATES_USE_CODEFORMATTER = "net.sourceforge.phpdt.ui.template.format"; //$NON-NLS-1$ + + /** + * A named preference that controls whether annotation roll over is used or + * not. + *

+ * Value is of type Boolean. If + * true the annotation ruler column + * uses a roll over to display multiple annotations + *

+ * + * @since 3.0 + */ + public static final String EDITOR_ANNOTATION_ROLL_OVER = "editor_annotation_roll_over"; //$NON-NLS-1$ + + /** + * A named preference that controls the key modifier mask for browser like + * links. The value is only used if the value of + * EDITOR_BROWSER_LIKE_LINKS cannot be resolved to valid SWT + * modifier bits. + *

+ * Value is of type String. + *

+ * + * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER + * @since 2.1.1 + */ + public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ + + /** + * A named preference that defines the key for the hover modifier state + * masks. The value is only used if the value of + * EDITOR_TEXT_HOVER_MODIFIERS cannot be resolved to valid + * SWT modifier bits. + * + * @see JavaUI + * @see #EDITOR_TEXT_HOVER_MODIFIERS + * @since 2.1.1 + */ + public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$ + + /** + * A named preference that controls whether folding is enabled in the Java + * editor. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_ENABLED = "editor_folding_enabled"; //$NON-NLS-1$ + + /** + * A named preference that stores the configured folding provider. + *

+ * Value is of type String. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_PROVIDER = "editor_folding_provider"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for Javadoc folding for the + * default folding provider. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_JAVADOC = "editor_folding_default_javadoc"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for inner type folding for the + * default folding provider. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_INNERTYPES = "editor_folding_default_innertypes"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for method folding for the + * default folding provider. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + public static final String EDITOR_FOLDING_METHODS = "editor_folding_default_methods"; //$NON-NLS-1$ + + /** + * A named preference that stores the value for imports folding for the + * default folding provider. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.0 + */ + // public static final String EDITOR_FOLDING_IMPORTS = + // "editor_folding_default_imports"; //$NON-NLS-1$ + /** + * A named preference that stores the value for header comment folding for + * the default folding provider. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.1 + */ + public static final String EDITOR_FOLDING_HEADERS = "editor_folding_default_headers"; //$NON-NLS-1$ + + public static void initializeDefaultValues(IPreferenceStore store) { + store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); + + // JavaBasePreferencePage + store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, true); + store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, + false); + store + .setDefault(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR, + true); + store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, + PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); + store.setDefault(PreferenceConstants.DOUBLE_CLICK, + PreferenceConstants.DOUBLE_CLICK_EXPANDS); + store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, + PreferenceConstants.UPDATE_WHILE_EDITING); + + // AppearancePreferencePage + store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, + false); + store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, + false); + store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); + store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, + true); + store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); + store.setDefault( + PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, + ""); //$NON-NLS-1$ + store + .setDefault( + PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, + true); + + // ImportOrganizePreferencePage + // store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, + // "php;phpx;org;com"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); + store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); + + // ClasspathVariablesPreferencePage + // CodeFormatterPreferencePage + // CompilerPreferencePage + // no initialization needed + + // RefactoringPreferencePage + store.setDefault( + PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, + PreferenceConstants.REFACTOR_ERROR_SEVERITY); + store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); + store.setDefault("RefactoringUI", "dialog"); + + // TemplatePreferencePage + store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); + + // CodeGenerationPreferencePage + store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, + false); + store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, + false); + store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, + "fg, f, _$, _, m_"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ + + store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); + store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); + store.setDefault(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, "e"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); + store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, + false); + store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); + + // MembersOrderPreferencePage + store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, + "T,SF,SI,SM,I,F,C,M"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.APPEARANCE_VISIBILITY_SORT_ORDER, + "B,V,R,D"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.APPEARANCE_ENABLE_VISIBILITY_SORT_ORDER, + false); + // must add here to guarantee that it is the first in the listener list + store.addPropertyChangeListener(PHPeclipsePlugin.getDefault() + .getMemberOrderPreferenceCache()); + + store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB( + 192, 192, 192)); + + store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, + 235, 224)); + + store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); + store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, + 180, 185)); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176, + 180)); + + // store.setDefault(PreferenceConstants.EDITOR_PROBLEM_INDICATION, + // true); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, new RGB(255, 0, + // 128)); + // store.setDefault(PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER, + // true); + // + // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION, + // true); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, new RGB(244, + // 200, 45)); + // store.setDefault(PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER, + // true); + // + // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION, false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, new RGB(0, 128, + // 255)); + // store.setDefault(PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, new RGB(34, + // 164, 99)); + // store.setDefault(PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, new + // RGB(192, 192, 192)); + // store.setDefault(PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, + // false); + // + // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION, + // false); + // PreferenceConverter.setDefault(store, + // PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, new RGB(0, 0, + // 0)); + // store.setDefault(PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER, + // false); + + store + .setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, + true); + store.setDefault( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); + + store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, + true); + + store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); + + // WorkbenchChainedTextFontFieldEditor.startPropagate(store, + // JFaceResources.TEXT_FONT); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, + 200, 100)); + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); + + store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, + true); + + store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, + true); + + store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); + store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB( + 63, 127, 95)); + store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB( + 63, 127, 95)); + store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_TAG_COLOR, new RGB(255, 0, 128)); + store.setDefault(PreferenceConstants.EDITOR_PHP_TAG_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, + 85)); + store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR, new RGB(127, + 127, 159)); + store.setDefault(PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_VARIABLE_COLOR, new RGB(127, + 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_COLOR, new RGB( + 127, 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_PHP_VARIABLE_DOLLAR_BOLD, + false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_CONSTANT_COLOR, new RGB(127, 0, + 85)); + store.setDefault(PreferenceConstants.EDITOR_PHP_CONSTANT_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_PHP_TYPE_COLOR, new RGB(127, 0, 85)); + store.setDefault(PreferenceConstants.EDITOR_PHP_TYPE_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_STRING_COLOR_DQ, + PHPColorProvider.STRING_DQ); + store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_DQ, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_STRING_COLOR_SQ, + PHPColorProvider.STRING_SQ); + store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD_SQ, true); + + PreferenceConverter + .setDefault(store, + PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB( + 0, 0, 0)); + store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, + 159, 191)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, + 159)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, + 191)); + store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); + + PreferenceConverter.setDefault(store, + PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, + 95, 191)); + store + .setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, + false); + + store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); + store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, + 500); + + store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB( + 254, 241, 233)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, + 0, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB( + 254, 241, 233)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB( + 0, 0, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB( + 255, 255, 0)); + PreferenceConverter.setDefault(store, + PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB( + 255, 0, 0)); + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, + "$>"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, + "@"); //$NON-NLS-1$ + store.setDefault( + PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_HTML, + "<&#"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, + true); + store + .setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, + false); + store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); + store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); + store + .setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, + true); + store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, + false); + store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, + true); + store.setDefault(PreferenceConstants.CODEASSIST_PREFIX_COMPLETION, + false); + + store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); + store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); + store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); + store.setDefault(PreferenceConstants.EDITOR_WRAP_WORDS, false); + store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_DQ, true); + store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_DQ, false); + store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS_SQ, true); + store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS_SQ, false); + store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); + store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); + store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, + false); + + store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, true); + store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, true); + + // store.setDefault(PreferenceConstants.EDITOR_DEFAULT_HOVER, + // JavaPlugin.ID_BESTMATCH_HOVER); + store.setDefault(PreferenceConstants.EDITOR_NONE_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + // store.setDefault(PreferenceConstants.EDITOR_CTRL_HOVER, + // JavaPlugin.ID_SOURCE_HOVER); + store.setDefault(PreferenceConstants.EDITOR_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, + PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID); + + int modifier = SWT.CTRL; + if (Platform.getOS().equals(Platform.OS_MACOSX)) + modifier = SWT.COMMAND; + String ctrl = Action.findModifierString(modifier); + store + .setDefault( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, + "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$ + store + .setDefault( + PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, + "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + modifier); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, + true); + + store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); + store.setDefault( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, + ctrl); + store + .setDefault( + PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, + modifier); + + // mark occurrences + store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, true); + store.setDefault(PreferenceConstants.EDITOR_STICKY_OCCURRENCES, true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS, + // true); + // store.setDefault(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS, true); + + // spell checking + store.setDefault(PreferenceConstants.SPELLING_CHECK_SPELLING, false); + store.setDefault(PreferenceConstants.SPELLING_LOCALE, SpellCheckEngine + .getDefaultLocale().toString()); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_DIGITS, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_MIXED, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_SENTENCE, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_UPPER, true); + store.setDefault(PreferenceConstants.SPELLING_IGNORE_URLS, true); + store.setDefault(PreferenceConstants.SPELLING_USER_DICTIONARY, ""); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.SPELLING_PROPOSAL_THRESHOLD, 20); + store.setDefault(PreferenceConstants.SPELLING_ENABLE_CONTENTASSIST, + false); + + // folding + store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, + "net.sourceforge.phpdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$ + store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false); + // store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, false); + store.setDefault(PreferenceConstants.EDITOR_FOLDING_HEADERS, true); + + store.setDefault(PreferenceConstants.EDITOR_SMART_BACKSPACE, true); + store.setDefault(PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE, false); + // do more complicated stuff + // NewJavaProjectPreferencePage.initDefaults(store); + } + + /** + * Returns the JDT-UI preference store. + * + * @return the JDT-UI preference store + */ + public static IPreferenceStore getPreferenceStore() { + return PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + // /** + // * Encodes a JRE library to be used in the named preference + // NEWPROJECT_JRELIBRARY_LIST. + // * + // * @param description a string value describing the JRE library. The + // description is used + // * to indentify the JDR library in the UI + // * @param entries an array of classpath entries to be encoded + // * + // * @return the encoded string. + // */ + // public static String encodeJRELibrary(String description, + // IClasspathEntry[] entries) { + // return NewJavaProjectPreferencePage.encodeJRELibrary(description, + // entries); + // } + // + // /** + // * Decodes an encoded JRE library and returns its description string. + // * + // * @return the description of an encoded JRE library + // * + // * @see #encodeJRELibrary(String, IClasspathEntry[]) + // */ + // public static String decodeJRELibraryDescription(String encodedLibrary) { + // return + // NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); + // } + // + // /** + // * Decodes an encoded JRE library and returns its classpath entries. + // * + // * @return the array of classpath entries of an encoded JRE library. + // * + // * @see #encodeJRELibrary(String, IClasspathEntry[]) + // */ + // public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String + // encodedLibrary) { + // return + // NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); + // } + // + // /** + // * Returns the current configuration for the JRE to be used as default in + // new Java projects. + // * This is a convenience method to access the named preference + // NEWPROJECT_JRELIBRARY_LIST + // * with the index defined by + // NEWPROJECT_JRELIBRARY_INDEX. + // * + // * @return the current default set of classpath entries + // * + // * @see #NEWPROJECT_JRELIBRARY_LIST + // * @see #NEWPROJECT_JRELIBRARY_INDEX + // */ + // public static IClasspathEntry[] getDefaultJRELibrary() { + // return NewJavaProjectPreferencePage.getDefaultJRELibrary(); + // } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java new file mode 100644 index 0000000..2af4d84 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java @@ -0,0 +1,425 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import java.util.Iterator; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.viewsupport.IProblemChangedListener; +import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; +import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +//incastrix +//import org.eclipse.jface.util.ListenerList; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.viewers.IBaseLabelProvider; +import org.eclipse.jface.viewers.IDecoration; +import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ILightweightLabelDecorator; +import org.eclipse.jface.viewers.LabelProviderChangedEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.MarkerAnnotation; + +/** + * LabelDecorator that decorates an element's image with error and warning + * overlays that represent the severity of markers attached to the element's + * underlying resource. To see a problem decoration for a marker, the marker + * needs to be a subtype of IMarker.PROBLEM. + *

+ * Note: Only images for elements in Java projects are currently updated on + * marker changes. + *

+ * + * @since 2.0 + */ +public class ProblemsLabelDecorator implements ILabelDecorator, + ILightweightLabelDecorator { + + /** + * This is a special LabelProviderChangedEvent carring + * additional information whether the event orgins from a maker change. + *

+ * ProblemsLabelChangedEvents are only generated by + * ProblemsLabelDecorators. + *

+ */ + public static class ProblemsLabelChangedEvent extends + LabelProviderChangedEvent { + + /** + * + */ + private static final long serialVersionUID = -7557704732816971319L; + private boolean fMarkerChange; + + /** + * Note: This constructor is for internal use only. Clients should not + * call this constructor. + */ + public ProblemsLabelChangedEvent(IBaseLabelProvider source, + IResource[] changedResource, boolean isMarkerChange) { + super(source, changedResource); + fMarkerChange = isMarkerChange; + } + + /** + * Returns whether this event origins from marker changes. If + * false an annotation model change is the origin. In + * this case viewers not displaying working copies can ignore these + * events. + * + * @return if this event origins from a marker change. + */ + public boolean isMarkerChange() { + return fMarkerChange; + } + + } + + private static final int ERRORTICK_WARNING = JavaElementImageDescriptor.WARNING; + + private static final int ERRORTICK_ERROR = JavaElementImageDescriptor.ERROR; + + private ImageDescriptorRegistry fRegistry; + + private boolean fUseNewRegistry = false; + + private IProblemChangedListener fProblemChangedListener; + + private ListenerList fListeners; + + /** + * Creates a new ProblemsLabelDecorator. + */ +// public ProblemsLabelDecorator() { +// this(null); +// fUseNewRegistry = true; +// } + + /* + * Creates decorator with a shared image registry. + * + * @param registry The registry to use or null to use the + * Java plugin's image registry. + */ + /** + * Note: This constructor is for internal use only. Clients should not call + * this constructor. + */ + public ProblemsLabelDecorator(ImageDescriptorRegistry registry) { + fRegistry = registry; + fProblemChangedListener = null; + } + + private ImageDescriptorRegistry getRegistry() { + if (fRegistry == null) { + fRegistry = fUseNewRegistry ? new ImageDescriptorRegistry() + : PHPeclipsePlugin.getImageDescriptorRegistry(); + } + return fRegistry; + } + + /* + * (non-Javadoc) + * + * @see ILabelDecorator#decorateText(String, Object) + */ + public String decorateText(String text, Object element) { + return text; + } + + /* + * (non-Javadoc) + * + * @see ILabelDecorator#decorateImage(Image, Object) + */ + public Image decorateImage(Image image, Object obj) { + int adornmentFlags = computeAdornmentFlags(obj); + if (adornmentFlags != 0) { + ImageDescriptor baseImage = new ImageImageDescriptor(image); + Rectangle bounds = image.getBounds(); + return getRegistry().get( + new JavaElementImageDescriptor(baseImage, adornmentFlags, + new Point(bounds.width, bounds.height))); + } + return image; + } + + /** + * Note: This method is for internal use only. Clients should not call this + * method. + */ + protected int computeAdornmentFlags(Object obj) { + try { + if (obj instanceof IJavaElement) { + IJavaElement element = (IJavaElement) obj; + int type = element.getElementType(); + switch (type) { + case IJavaElement.JAVA_PROJECT: + case IJavaElement.PACKAGE_FRAGMENT_ROOT: + return getErrorTicksFromMarkers(element.getResource(), + IResource.DEPTH_INFINITE, null); + case IJavaElement.PACKAGE_FRAGMENT: + case IJavaElement.CLASS_FILE: + return getErrorTicksFromMarkers(element.getResource(), + IResource.DEPTH_ONE, null); + case IJavaElement.COMPILATION_UNIT: + case IJavaElement.PACKAGE_DECLARATION: + case IJavaElement.IMPORT_DECLARATION: + case IJavaElement.IMPORT_CONTAINER: + case IJavaElement.TYPE: + case IJavaElement.INITIALIZER: + case IJavaElement.METHOD: + case IJavaElement.FIELD: + ICompilationUnit cu = (ICompilationUnit) element + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null) { + ISourceReference ref = (type == IJavaElement.COMPILATION_UNIT) ? null + : (ISourceReference) element; + // The assumption is that only source elements in + // compilation unit can have markers + if (cu.isWorkingCopy()) { + // working copy: look at annotation model + return getErrorTicksFromWorkingCopy( + (ICompilationUnit) cu.getOriginalElement(), + ref); + } + return getErrorTicksFromMarkers(cu.getResource(), + IResource.DEPTH_ONE, ref); + } + break; + default: + } + } else if (obj instanceof IResource) { + return getErrorTicksFromMarkers((IResource) obj, + IResource.DEPTH_INFINITE, null); + } + } catch (CoreException e) { + if (e instanceof JavaModelException) { + if (((JavaModelException) e).isDoesNotExist()) { + return 0; + } + } + PHPeclipsePlugin.log(e); + } + return 0; + } + + private int getErrorTicksFromMarkers(IResource res, int depth, + ISourceReference sourceElement) throws CoreException { + if (res == null || !res.isAccessible()) { + return 0; + } + int info = 0; + + IMarker[] markers = res.findMarkers(IMarker.PROBLEM, true, depth); + if (markers != null) { + for (int i = 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { + IMarker curr = markers[i]; + if (sourceElement == null + || isMarkerInRange(curr, sourceElement)) { + int priority = curr.getAttribute(IMarker.SEVERITY, -1); + if (priority == IMarker.SEVERITY_WARNING) { + info = ERRORTICK_WARNING; + } else if (priority == IMarker.SEVERITY_ERROR) { + info = ERRORTICK_ERROR; + } + } + } + } + return info; + } + + private boolean isMarkerInRange(IMarker marker, + ISourceReference sourceElement) throws CoreException { + if (marker.isSubtypeOf(IMarker.TEXT)) { + int pos = marker.getAttribute(IMarker.CHAR_START, -1); + return isInside(pos, sourceElement); + } + return false; + } + + private int getErrorTicksFromWorkingCopy(ICompilationUnit original, + ISourceReference sourceElement) throws CoreException { + int info = 0; + FileEditorInput editorInput = new FileEditorInput((IFile) original + .getResource()); + IAnnotationModel model = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider().getAnnotationModel( + editorInput); + if (model != null) { + Iterator iter = model.getAnnotationIterator(); + while ((info != ERRORTICK_ERROR) && iter.hasNext()) { + Annotation curr = (Annotation) iter.next(); + IMarker marker = isAnnotationInRange(model, curr, sourceElement); + if (marker != null) { + int priority = marker.getAttribute(IMarker.SEVERITY, -1); + if (priority == IMarker.SEVERITY_WARNING) { + info = ERRORTICK_WARNING; + } else if (priority == IMarker.SEVERITY_ERROR) { + info = ERRORTICK_ERROR; + } + } + } + } + return info; + } + + private IMarker isAnnotationInRange(IAnnotationModel model, + Annotation annot, ISourceReference sourceElement) + throws CoreException { + if (annot instanceof MarkerAnnotation) { + IMarker marker = ((MarkerAnnotation) annot).getMarker(); + if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { + Position pos = model.getPosition(annot); + if (sourceElement == null + || isInside(pos.getOffset(), sourceElement)) { + return marker; + } + } + } + return null; + } + + /** + * Tests if a position is inside the source range of an element. + * + * @param pos + * Position to be tested. + * @param sourceElement + * Source element (must be a IJavaElement) + * @return boolean Return true if position is located inside + * the source element. + * @throws CoreException + * Exception thrown if element range could not be accessed. + * + * @since 2.1 + */ + protected boolean isInside(int pos, ISourceReference sourceElement) + throws CoreException { + ISourceRange range = sourceElement.getSourceRange(); + if (range != null) { + int rangeOffset = range.getOffset(); + return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); + } + return false; + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#dispose() + */ + public void dispose() { + if (fProblemChangedListener != null) { + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .removeListener(fProblemChangedListener); + fProblemChangedListener = null; + } + if (fRegistry != null && fUseNewRegistry) { + fRegistry.dispose(); + } + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#isLabelProperty(Object, String) + */ + public boolean isLabelProperty(Object element, String property) { + return true; + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#addListener(ILabelProviderListener) + */ + public void addListener(ILabelProviderListener listener) { + if (fListeners == null) { + fListeners = new ListenerList(); + } + fListeners.add(listener); + if (fProblemChangedListener == null) { + fProblemChangedListener = new IProblemChangedListener() { + public void problemsChanged(IResource[] changedResources, + boolean isMarkerChange) { + fireProblemsChanged(changedResources, isMarkerChange); + } + }; + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .addListener(fProblemChangedListener); + } + } + + /* + * (non-Javadoc) + * + * @see IBaseLabelProvider#removeListener(ILabelProviderListener) + */ + public void removeListener(ILabelProviderListener listener) { + if (fListeners != null) { + fListeners.remove(listener); + if (fListeners.isEmpty() && fProblemChangedListener != null) { + PHPeclipsePlugin.getDefault().getProblemMarkerManager() + .removeListener(fProblemChangedListener); + fProblemChangedListener = null; + } + } + } + + private void fireProblemsChanged(IResource[] changedResources, + boolean isMarkerChange) { + if (fListeners != null && !fListeners.isEmpty()) { + LabelProviderChangedEvent event = new ProblemsLabelChangedEvent( + this, changedResources, isMarkerChange); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + ((ILabelProviderListener) listeners[i]) + .labelProviderChanged(event); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, + * org.eclipse.jface.viewers.IDecoration) + */ + public void decorate(Object element, IDecoration decoration) { + int adornmentFlags = computeAdornmentFlags(element); + if (adornmentFlags == ERRORTICK_ERROR) { + decoration.addOverlay(PHPUiImages.DESC_OVR_ERROR); + } else if (adornmentFlags == ERRORTICK_WARNING) { + decoration.addOverlay(PHPUiImages.DESC_OVR_WARNING); + } + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java new file mode 100644 index 0000000..b766eda --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/CustomFiltersActionGroup.java @@ -0,0 +1,812 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui.actions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.Stack; +import java.util.StringTokenizer; +import java.util.TreeSet; + +//import net.sourceforge.phpdt.core.IJavaModel; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.filters.CustomFiltersDialog; +import net.sourceforge.phpdt.internal.ui.filters.FilterDescriptor; +import net.sourceforge.phpdt.internal.ui.filters.FilterMessages; +import net.sourceforge.phpdt.internal.ui.filters.NamePatternFilter; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.ContributionItem; +import org.eclipse.jface.action.GroupMarker; +import org.eclipse.jface.action.IContributionItem; +import org.eclipse.jface.action.IMenuListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +//import org.eclipse.jface.viewers.IContentProvider; +//import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.StructuredViewer; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.IMemento; +//import org.eclipse.ui.IViewPart; +import org.eclipse.ui.actions.ActionGroup; + +/** + * Action group to add the filter action to a view part's tool bar menu. + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * @since 2.0 + */ +public class CustomFiltersActionGroup extends ActionGroup { + + class ShowFilterDialogAction extends Action { + ShowFilterDialogAction() { + setText(FilterMessages + .getString("OpenCustomFiltersDialogAction.text")); //$NON-NLS-1$ + setImageDescriptor(PHPUiImages.DESC_ELCL_FILTER); + setDisabledImageDescriptor(PHPUiImages.DESC_DLCL_FILTER); + } + + public void run() { + openDialog(); + } + } + + /** + * Menu contribution item which shows and lets check and uncheck filters. + * + * @since 3.0 + */ + class FilterActionMenuContributionItem extends ContributionItem { + + private int fItemNumber; + + private boolean fState; + + private String fFilterId; + + private String fFilterName; + + private CustomFiltersActionGroup fActionGroup; + + /** + * Constructor for FilterActionMenuContributionItem. + * + * @param actionGroup + * the action group + * @param filterId + * the id of the filter + * @param filterName + * the name of the filter + * @param state + * the initial state of the filter + * @param itemNumber + * the menu item index + */ + public FilterActionMenuContributionItem( + CustomFiltersActionGroup actionGroup, String filterId, + String filterName, boolean state, int itemNumber) { + super(filterId); + Assert.isNotNull(actionGroup); + Assert.isNotNull(filterId); + Assert.isNotNull(filterName); + fActionGroup = actionGroup; + fFilterId = filterId; + fFilterName = filterName; + fState = state; + fItemNumber = itemNumber; + } + + /* + * Overrides method from ContributionItem. + */ + public void fill(Menu menu, int index) { + MenuItem mi = new MenuItem(menu, SWT.CHECK, index); + mi.setText("&" + fItemNumber + " " + fFilterName); //$NON-NLS-1$ //$NON-NLS-2$ + /* + * XXX: Don't set the image - would look bad because other menu + * items don't provide image XXX: Get working set specific image + * name from XML - would need to cache icons + */ + // mi.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVA_WORKING_SET)); + mi.setSelection(fState); + mi.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + fState = !fState; + fActionGroup.setFilter(fFilterId, fState); + } + }); + } + + /* + * @see org.eclipse.jface.action.IContributionItem#isDynamic() + */ + public boolean isDynamic() { + return true; + } + } + + private static final String TAG_CUSTOM_FILTERS = "customFilters"; //$NON-NLS-1$ + + private static final String TAG_USER_DEFINED_PATTERNS_ENABLED = "userDefinedPatternsEnabled"; //$NON-NLS-1$ + + private static final String TAG_USER_DEFINED_PATTERNS = "userDefinedPatterns"; //$NON-NLS-1$ + + private static final String TAG_XML_DEFINED_FILTERS = "xmlDefinedFilters"; //$NON-NLS-1$ + + private static final String TAG_LRU_FILTERS = "lastRecentlyUsedFilters"; //$NON-NLS-1$ + + private static final String TAG_CHILD = "child"; //$NON-NLS-1$ + + private static final String TAG_PATTERN = "pattern"; //$NON-NLS-1$ + + private static final String TAG_FILTER_ID = "filterId"; //$NON-NLS-1$ + + private static final String TAG_IS_ENABLED = "isEnabled"; //$NON-NLS-1$ + + private static final String SEPARATOR = ","; //$NON-NLS-1$ + + private static final int MAX_FILTER_MENU_ENTRIES = 3; + + private static final String RECENT_FILTERS_GROUP_NAME = "recentFiltersGroup"; //$NON-NLS-1$ + + private StructuredViewer fViewer; + + private NamePatternFilter fPatternFilter; + + private Map fInstalledBuiltInFilters; + + private Map fEnabledFilterIds; + + private boolean fUserDefinedPatternsEnabled; + + private String[] fUserDefinedPatterns; + + /** + * Recently changed filter Ids stack with oldest on top (i.e. at the end). + * + * @since 3.0 + */ + private Stack fLRUFilterIdsStack; + + /** + * Handle to menu manager to dynamically update the last recently used + * filters. + * + * @since 3.0 + */ + private IMenuManager fMenuManager; + + /** + * The menu listener which dynamically updates the last recently used + * filters. + * + * @since 3.0 + */ + private IMenuListener fMenuListener; + + /** + * Filter Ids used in the last view menu invocation. + * + * @since 3.0 + */ + private String[] fFilterIdsUsedInLastViewMenu; + + private HashMap fFilterDescriptorMap; + + private String fTargetId; + + /** + * Creates a new CustomFiltersActionGroup. + * + * @param part + * the view part that owns this action group + * @param viewer + * the viewer to be filtered + */ +// public CustomFiltersActionGroup(IViewPart part, StructuredViewer viewer) { +// this(part.getViewSite().getId(), viewer); +// } + + /** + * Creates a new CustomFiltersActionGroup. + * + * @param ownerId + * the id of this action group's owner + * @param viewer + * the viewer to be filtered + */ + public CustomFiltersActionGroup(String ownerId, StructuredViewer viewer) { + Assert.isNotNull(ownerId); + Assert.isNotNull(viewer); + fTargetId = ownerId; + fViewer = viewer; + + fLRUFilterIdsStack = new Stack(); + + initializeWithPluginContributions(); + initializeWithViewDefaults(); + + installFilters(); + } + + /* + * Method declared on ActionGroup. + */ + public void fillActionBars(IActionBars actionBars) { + fillToolBar(actionBars.getToolBarManager()); + fillViewMenu(actionBars.getMenuManager()); + } + +// public String[] removeFiltersFor(Object parent, Object element, +// IContentProvider contentProvider) { +// String[] enabledFilters = getEnabledFilterIds(); +// Set newFilters = new HashSet(); +// for (int i = 0; i < enabledFilters.length; i++) { +// String filterName = enabledFilters[i]; +// ViewerFilter filter = (ViewerFilter) fInstalledBuiltInFilters +// .get(filterName); +// if (filter == null) +// newFilters.add(filterName); +// else if (isSelected(parent, element, contentProvider, filter)) +// newFilters.add(filterName); +// } +// if (newFilters.size() == enabledFilters.length) +// return new String[0]; +// return (String[]) newFilters.toArray(new String[newFilters.size()]); +// } + + public void setFilters(String[] newFilters) { + setEnabledFilterIds(newFilters); + updateViewerFilters(true); + } + +// private boolean isSelected(Object parent, Object element, +// IContentProvider contentProvider, ViewerFilter filter) { +// if (contentProvider instanceof ITreeContentProvider) { +// // the element and all its parents have to be selected +// ITreeContentProvider provider = (ITreeContentProvider) contentProvider; +// while (element != null && !(element instanceof IJavaModel)) { +// if (!filter.select(fViewer, parent, element)) +// return false; +// element = provider.getParent(element); +// } +// return true; +// } +// return filter.select(fViewer, parent, element); +// } + + /** + * Sets the enable state of the given filter. + * + * @param filterId + * the id of the filter + * @param state + * the filter state + */ + private void setFilter(String filterId, boolean state) { + // Renew filter id in LRU stack + fLRUFilterIdsStack.remove(filterId); + fLRUFilterIdsStack.add(0, filterId); + + fEnabledFilterIds.put(filterId, new Boolean(state)); + storeViewDefaults(); + + updateViewerFilters(true); + } + + private String[] getEnabledFilterIds() { + Set enabledFilterIds = new HashSet(fEnabledFilterIds.size()); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); + if (isEnabled) + enabledFilterIds.add(id); + } + return (String[]) enabledFilterIds.toArray(new String[enabledFilterIds + .size()]); + } + + private void setEnabledFilterIds(String[] enabledIds) { + Iterator iter = fEnabledFilterIds.keySet().iterator(); + while (iter.hasNext()) { + String id = (String) iter.next(); + fEnabledFilterIds.put(id, Boolean.FALSE); + } + for (int i = 0; i < enabledIds.length; i++) + fEnabledFilterIds.put(enabledIds[i], Boolean.TRUE); + } + + private void setUserDefinedPatterns(String[] patterns) { + fUserDefinedPatterns = patterns; + cleanUpPatternDuplicates(); + } + + /** + * Sets the recently changed filters. + * + * @param changeHistory + * the change history + * @since 3.0 + */ + private void setRecentlyChangedFilters(Stack changeHistory) { + Stack oldestFirstStack = new Stack(); + + int length = Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES); + for (int i = 0; i < length; i++) + oldestFirstStack.push(((FilterDescriptor) changeHistory.pop()) + .getId()); + + length = Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES + - oldestFirstStack.size()); + int NEWEST = 0; + for (int i = 0; i < length; i++) { + Object filter = fLRUFilterIdsStack.remove(NEWEST); + if (!oldestFirstStack.contains(filter)) + oldestFirstStack.push(filter); + } + fLRUFilterIdsStack = oldestFirstStack; + } + + private boolean areUserDefinedPatternsEnabled() { + return fUserDefinedPatternsEnabled; + } + + private void setUserDefinedPatternsEnabled(boolean state) { + fUserDefinedPatternsEnabled = state; + } + + private void fillToolBar(IToolBarManager tooBar) { + } + + /** + * Fills the given view menu with the entries managed by the group. + * + * @param viewMenu + * the menu to fill + */ + public void fillViewMenu(IMenuManager viewMenu) { + /* + * Don't change the separator group name. Using this name ensures that + * other filters get contributed to the same group. + */ + viewMenu.add(new Separator("filters")); //$NON-NLS-1$ + viewMenu.add(new GroupMarker(RECENT_FILTERS_GROUP_NAME)); + viewMenu.add(new ShowFilterDialogAction()); + + fMenuManager = viewMenu; + fMenuListener = new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + removePreviousLRUFilterActions(manager); + addLRUFilterActions(manager); + } + }; + fMenuManager.addMenuListener(fMenuListener); + } + + private void removePreviousLRUFilterActions(IMenuManager mm) { + if (fFilterIdsUsedInLastViewMenu == null) + return; + + for (int i = 0; i < fFilterIdsUsedInLastViewMenu.length; i++) + mm.remove(fFilterIdsUsedInLastViewMenu[i]); + } + + private void addLRUFilterActions(IMenuManager mm) { + if (fLRUFilterIdsStack.isEmpty()) { + fFilterIdsUsedInLastViewMenu = null; + return; + } + + SortedSet sortedFilters = new TreeSet(fLRUFilterIdsStack); + String[] recentlyChangedFilterIds = (String[]) sortedFilters + .toArray(new String[sortedFilters.size()]); + + fFilterIdsUsedInLastViewMenu = new String[recentlyChangedFilterIds.length]; + for (int i = 0; i < recentlyChangedFilterIds.length; i++) { + String id = recentlyChangedFilterIds[i]; + fFilterIdsUsedInLastViewMenu[i] = id; + boolean state = fEnabledFilterIds.containsKey(id) + && ((Boolean) fEnabledFilterIds.get(id)).booleanValue(); + FilterDescriptor filterDesc = (FilterDescriptor) fFilterDescriptorMap + .get(id); + if (filterDesc != null) { + IContributionItem item = new FilterActionMenuContributionItem( + this, id, filterDesc.getName(), state, i + 1); + mm.insertBefore(RECENT_FILTERS_GROUP_NAME, item); + } + } + } + + /* + * Method declared on ActionGroup. + */ + public void dispose() { + if (fMenuManager != null) + fMenuManager.removeMenuListener(fMenuListener); + super.dispose(); + } + + private void initializeWithPluginContributions() { + fUserDefinedPatterns = new String[0]; + fUserDefinedPatternsEnabled = false; + + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + fFilterDescriptorMap = new HashMap(filterDescs.length); + fEnabledFilterIds = new HashMap(filterDescs.length); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); + Boolean isEnabled = new Boolean(filterDescs[i].isEnabled()); + if (fEnabledFilterIds.containsKey(id)) + PHPeclipsePlugin + .logErrorMessage("WARNING: Duplicate id for extension-point \"net.sourceforge.phpdt.ui.javaElementFilters\""); //$NON-NLS-1$ + fEnabledFilterIds.put(id, isEnabled); + fFilterDescriptorMap.put(id, filterDescs[i]); + } + } + + // ---------- viewer filter handling ---------- + + private void installFilters() { + fInstalledBuiltInFilters = new HashMap(fEnabledFilterIds.size()); + fPatternFilter = new NamePatternFilter(); + fPatternFilter.setPatterns(getUserAndBuiltInPatterns()); + fViewer.addFilter(fPatternFilter); + updateBuiltInFilters(); + } + + private void updateViewerFilters(boolean refresh) { + String[] patterns = getUserAndBuiltInPatterns(); + fPatternFilter.setPatterns(patterns); + fViewer.getControl().setRedraw(false); + updateBuiltInFilters(); + if (refresh) + fViewer.refresh(); + fViewer.getControl().setRedraw(true); + } + + private void updateBuiltInFilters() { + Set installedFilters = fInstalledBuiltInFilters.keySet(); + Set filtersToAdd = new HashSet(fEnabledFilterIds.size()); + Set filtersToRemove = new HashSet(fEnabledFilterIds.size()); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); + if (isEnabled && !installedFilters.contains(id)) + filtersToAdd.add(id); + else if (!isEnabled && installedFilters.contains(id)) + filtersToRemove.add(id); + } + + // Install the filters + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); + // just to double check - id should denote a custom filter anyway + boolean isCustomFilter = filterDescs[i].isCustomFilter(); + if (isCustomFilter) { + if (filtersToAdd.contains(id)) { + ViewerFilter filter = filterDescs[i].createViewerFilter(); + if (filter != null) { + fViewer.addFilter(filter); + fInstalledBuiltInFilters.put(id, filter); + } + } + if (filtersToRemove.contains(id)) { + fViewer + .removeFilter((ViewerFilter) fInstalledBuiltInFilters + .get(id)); + fInstalledBuiltInFilters.remove(id); + } + } + } + } + + private String[] getUserAndBuiltInPatterns() { + List patterns = new ArrayList(fUserDefinedPatterns.length); + if (areUserDefinedPatternsEnabled()) + patterns.addAll(Arrays.asList(fUserDefinedPatterns)); + FilterDescriptor[] filterDescs = FilterDescriptor + .getFilterDescriptors(fTargetId); + for (int i = 0; i < filterDescs.length; i++) { + String id = filterDescs[i].getId(); + boolean isPatternFilter = filterDescs[i].isPatternFilter(); + Object isEnabled = fEnabledFilterIds.get(id); + if (isEnabled != null && isPatternFilter + && ((Boolean) isEnabled).booleanValue()) + patterns.add(filterDescs[i].getPattern()); + } + return (String[]) patterns.toArray(new String[patterns.size()]); + } + + // ---------- view kind/defaults persistency ---------- + + private void initializeWithViewDefaults() { + // get default values for view + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + // XXX: can be removed once bug 22533 is fixed. + if (!store.contains(getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE")))//$NON-NLS-1$ + return; + + // XXX: Uncomment once bug 22533 is fixed. + // if + // (!store.contains(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED))) + // return; + + fUserDefinedPatternsEnabled = store + .getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); + setUserDefinedPatterns(CustomFiltersDialog.convertFromString(store + .getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), + SEPARATOR)); + + Iterator iter = fEnabledFilterIds.keySet().iterator(); + while (iter.hasNext()) { + String id = (String) iter.next(); + Boolean isEnabled = new Boolean(store.getBoolean(id)); + fEnabledFilterIds.put(id, isEnabled); + } + + fLRUFilterIdsStack.clear(); + String lruFilterIds = store.getString(TAG_LRU_FILTERS); + StringTokenizer tokenizer = new StringTokenizer(lruFilterIds, SEPARATOR); + while (tokenizer.hasMoreTokens()) { + String id = tokenizer.nextToken(); + if (fFilterDescriptorMap.containsKey(id) + && !fLRUFilterIdsStack.contains(id)) + fLRUFilterIdsStack.push(id); + } + } + + private void storeViewDefaults() { + // get default values for view + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + // XXX: can be removed once bug 22533 is fixed. + store + .setValue( + getPreferenceKey("TAG_DUMMY_TO_TEST_EXISTENCE"), "storedViewPreferences");//$NON-NLS-1$//$NON-NLS-2$ + + store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), + fUserDefinedPatternsEnabled); + store.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), + CustomFiltersDialog.convertToString(fUserDefinedPatterns, + SEPARATOR)); + + Iterator iter = fEnabledFilterIds.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + boolean isEnabled = ((Boolean) entry.getValue()).booleanValue(); + store.setValue(id, isEnabled); + } + + StringBuffer buf = new StringBuffer(fLRUFilterIdsStack.size() * 20); + iter = fLRUFilterIdsStack.iterator(); + while (iter.hasNext()) { + buf.append((String) iter.next()); + buf.append(SEPARATOR); + } + store.setValue(TAG_LRU_FILTERS, buf.toString()); + } + + private String getPreferenceKey(String tag) { + return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$ + } + + // ---------- view instance persistency ---------- + + /** + * Saves the state of the custom filters in a memento. + * + * @param memento + * the memento into which the state is saved + */ + public void saveState(IMemento memento) { + IMemento customFilters = memento.createChild(TAG_CUSTOM_FILTERS); + customFilters.putString(TAG_USER_DEFINED_PATTERNS_ENABLED, new Boolean( + fUserDefinedPatternsEnabled).toString()); + saveUserDefinedPatterns(customFilters); + saveXmlDefinedFilters(customFilters); + saveLRUFilters(customFilters); + } + + private void saveXmlDefinedFilters(IMemento memento) { + if (fEnabledFilterIds != null && !fEnabledFilterIds.isEmpty()) { + IMemento xmlDefinedFilters = memento + .createChild(TAG_XML_DEFINED_FILTERS); + Iterator iter = fEnabledFilterIds.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String id = (String) entry.getKey(); + Boolean isEnabled = (Boolean) entry.getValue(); + IMemento child = xmlDefinedFilters.createChild(TAG_CHILD); + child.putString(TAG_FILTER_ID, id); + child.putString(TAG_IS_ENABLED, isEnabled.toString()); + } + } + } + + /** + * Stores the last recently used filter Ids into the given memento + * + * @param memento + * the memento into which to store the LRU filter Ids + * @since 3.0 + */ + private void saveLRUFilters(IMemento memento) { + if (fLRUFilterIdsStack != null && !fLRUFilterIdsStack.isEmpty()) { + IMemento lruFilters = memento.createChild(TAG_LRU_FILTERS); + Iterator iter = fLRUFilterIdsStack.iterator(); + while (iter.hasNext()) { + String id = (String) iter.next(); + IMemento child = lruFilters.createChild(TAG_CHILD); + child.putString(TAG_FILTER_ID, id); + } + } + } + + private void saveUserDefinedPatterns(IMemento memento) { + if (fUserDefinedPatterns != null && fUserDefinedPatterns.length > 0) { + IMemento userDefinedPatterns = memento + .createChild(TAG_USER_DEFINED_PATTERNS); + for (int i = 0; i < fUserDefinedPatterns.length; i++) { + IMemento child = userDefinedPatterns.createChild(TAG_CHILD); + child.putString(TAG_PATTERN, fUserDefinedPatterns[i]); + } + } + } + + /** + * Restores the state of the filter actions from a memento. + *

+ * Note: This method does not refresh the viewer. + *

+ * + * @param memento + * the memento from which the state is restored + */ + public void restoreState(IMemento memento) { + if (memento == null) + return; + IMemento customFilters = memento.getChild(TAG_CUSTOM_FILTERS); + if (customFilters == null) + return; + String userDefinedPatternsEnabled = customFilters + .getString(TAG_USER_DEFINED_PATTERNS_ENABLED); + if (userDefinedPatternsEnabled == null) + return; + + fUserDefinedPatternsEnabled = Boolean.valueOf( + userDefinedPatternsEnabled).booleanValue(); + restoreUserDefinedPatterns(customFilters); + restoreXmlDefinedFilters(customFilters); + restoreLRUFilters(customFilters); + + updateViewerFilters(false); + } + + private void restoreUserDefinedPatterns(IMemento memento) { + IMemento userDefinedPatterns = memento + .getChild(TAG_USER_DEFINED_PATTERNS); + if (userDefinedPatterns != null) { + IMemento children[] = userDefinedPatterns.getChildren(TAG_CHILD); + String[] patterns = new String[children.length]; + for (int i = 0; i < children.length; i++) + patterns[i] = children[i].getString(TAG_PATTERN); + + setUserDefinedPatterns(patterns); + } else + setUserDefinedPatterns(new String[0]); + } + + private void restoreXmlDefinedFilters(IMemento memento) { + IMemento xmlDefinedFilters = memento.getChild(TAG_XML_DEFINED_FILTERS); + if (xmlDefinedFilters != null) { + IMemento[] children = xmlDefinedFilters.getChildren(TAG_CHILD); + for (int i = 0; i < children.length; i++) { + String id = children[i].getString(TAG_FILTER_ID); + Boolean isEnabled = new Boolean(children[i] + .getString(TAG_IS_ENABLED)); + fEnabledFilterIds.put(id, isEnabled); + } + } + } + + private void restoreLRUFilters(IMemento memento) { + IMemento lruFilters = memento.getChild(TAG_LRU_FILTERS); + fLRUFilterIdsStack.clear(); + if (lruFilters != null) { + IMemento[] children = lruFilters.getChildren(TAG_CHILD); + for (int i = 0; i < children.length; i++) { + String id = children[i].getString(TAG_FILTER_ID); + if (fFilterDescriptorMap.containsKey(id) + && !fLRUFilterIdsStack.contains(id)) + fLRUFilterIdsStack.push(id); + } + } + } + + private void cleanUpPatternDuplicates() { + if (!areUserDefinedPatternsEnabled()) + return; + List userDefinedPatterns = new ArrayList(Arrays + .asList(fUserDefinedPatterns)); + FilterDescriptor[] filters = FilterDescriptor + .getFilterDescriptors(fTargetId); + + for (int i = 0; i < filters.length; i++) { + if (filters[i].isPatternFilter()) { + String pattern = filters[i].getPattern(); + if (userDefinedPatterns.contains(pattern)) { + fEnabledFilterIds.put(filters[i].getId(), Boolean.TRUE); + boolean hasMore = true; + while (hasMore) + hasMore = userDefinedPatterns.remove(pattern); + } + } + } + fUserDefinedPatterns = (String[]) userDefinedPatterns + .toArray(new String[userDefinedPatterns.size()]); + setUserDefinedPatternsEnabled(fUserDefinedPatternsEnabled + && fUserDefinedPatterns.length > 0); + } + + // ---------- dialog related code ---------- + + private void openDialog() { + CustomFiltersDialog dialog = new CustomFiltersDialog(fViewer + .getControl().getShell(), fTargetId, + areUserDefinedPatternsEnabled(), fUserDefinedPatterns, + getEnabledFilterIds()); + + if (dialog.open() == Window.OK) { + setEnabledFilterIds(dialog.getEnabledFilterIds()); + setUserDefinedPatternsEnabled(dialog + .areUserDefinedPatternsEnabled()); + setUserDefinedPatterns(dialog.getUserDefinedPatterns()); + setRecentlyChangedFilters(dialog.getFilterDescriptorChangeHistory()); + + storeViewDefaults(); + + updateViewerFilters(true); + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GenerateActionGroup.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/GotoMatchingBracketAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java new file mode 100644 index 0000000..8801dae --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java @@ -0,0 +1,327 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui.actions; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.actions.ActionMessages; +import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilter; +import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilterAction; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +//import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.viewers.StructuredViewer; +import org.eclipse.swt.custom.BusyIndicator; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.IMemento; +import org.eclipse.ui.actions.ActionGroup; + +/** + * Action Group that contributes filter buttons for a view parts showing methods + * and fields. Contributed filters are: hide fields, hide static members and + * hide non-public members. + *

+ * The action group installs a filter on a structured viewer. The filter is + * connected to the actions installed in the view part's toolbar menu and is + * updated when the state of the buttons changes. + * + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * @since 2.0 + */ +public class MemberFilterActionGroup extends ActionGroup { + + public static final int FILTER_NONPUBLIC = MemberFilter.FILTER_NONPUBLIC; + + public static final int FILTER_STATIC = MemberFilter.FILTER_STATIC; + + public static final int FILTER_FIELDS = MemberFilter.FILTER_FIELDS; + + private static final String TAG_HIDEFIELDS = "hidefields"; //$NON-NLS-1$ + + private static final String TAG_HIDESTATIC = "hidestatic"; //$NON-NLS-1$ + + private static final String TAG_HIDENONPUBLIC = "hidenonpublic"; //$NON-NLS-1$ + + private MemberFilterAction[] fFilterActions; + + private MemberFilter fFilter; + + private StructuredViewer fViewer; + + private String fViewerId; + + private boolean fInViewMenu; + + /** + * Creates a new MemberFilterActionGroup. + * + * @param viewer + * the viewer to be filtered + * @param viewerId + * a unique id of the viewer. Used as a key to to store the last + * used filter settings in the preference store + */ + public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) { + this(viewer, viewerId, false); + } + + /** + * Creates a new MemberFilterActionGroup. + * + * @param viewer + * the viewer to be filtered + * @param viewerId + * a unique id of the viewer. Used as a key to to store the last + * used filter settings in the preference store + * @param inViewMenu + * if true the actions are added to the view menu. + * If false they are added to the toobar. + * + * @since 2.1 + */ + public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, + boolean inViewMenu) { + fViewer = viewer; + fViewerId = viewerId; + fInViewMenu = inViewMenu; + + // get initial values + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + boolean doHideFields = store + .getBoolean(getPreferenceKey(FILTER_FIELDS)); + boolean doHideStatic = store + .getBoolean(getPreferenceKey(FILTER_STATIC)); + boolean doHidePublic = store + .getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); + + fFilter = new MemberFilter(); + if (doHideFields) + fFilter.addFilter(FILTER_FIELDS); + if (doHideStatic) + fFilter.addFilter(FILTER_STATIC); + if (doHidePublic) + fFilter.addFilter(FILTER_NONPUBLIC); + + // fields + String title = ActionMessages + .getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ + String helpContext = IJavaHelpContextIds.FILTER_FIELDS_ACTION; + MemberFilterAction hideFields = new MemberFilterAction(this, title, + FILTER_FIELDS, helpContext, doHideFields); + hideFields.setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ + hideFields.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ + + // static + title = ActionMessages + .getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ + helpContext = IJavaHelpContextIds.FILTER_STATIC_ACTION; + MemberFilterAction hideStatic = new MemberFilterAction(this, title, + FILTER_STATIC, helpContext, doHideStatic); + hideStatic.setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ + hideStatic.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ + + // non-public + title = ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ + helpContext = IJavaHelpContextIds.FILTER_PUBLIC_ACTION; + MemberFilterAction hideNonPublic = new MemberFilterAction(this, title, + FILTER_NONPUBLIC, helpContext, doHidePublic); + hideNonPublic + .setDescription(ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ + hideNonPublic.setToolTipText(ActionMessages + .getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ + + // order corresponds to order in toolbar + fFilterActions = new MemberFilterAction[] { hideFields, hideStatic, + hideNonPublic }; + + fViewer.addFilter(fFilter); + } + + private String getPreferenceKey(int filterProperty) { + return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$ + } + + /** + * Sets the member filters. + * + * @param filterProperty + * the filter to be manipulated. Valid values are + * FILTER_FIELDS, FILTER_PUBLIC, + * and FILTER_PRIVATE as defined by this action + * group + * @param set + * if true the given filter is installed. If + * false the given filter is removed . + */ + public void setMemberFilter(int filterProperty, boolean set) { + setMemberFilters(new int[] { filterProperty }, new boolean[] { set }, + true); + } + + private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, + boolean refresh) { + if (propertyKeys.length == 0) + return; + Assert.isTrue(propertyKeys.length == propertyValues.length); + + for (int i = 0; i < propertyKeys.length; i++) { + int filterProperty = propertyKeys[i]; + boolean set = propertyValues[i]; + if (set) { + fFilter.addFilter(filterProperty); + } else { + fFilter.removeFilter(filterProperty); + } + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + + for (int j = 0; j < fFilterActions.length; j++) { + int currProperty = fFilterActions[j].getFilterProperty(); + if (currProperty == filterProperty) { + fFilterActions[j].setChecked(set); + } + store.setValue(getPreferenceKey(currProperty), + hasMemberFilter(currProperty)); + } + } + if (refresh) { + fViewer.getControl().setRedraw(false); + BusyIndicator.showWhile(fViewer.getControl().getDisplay(), + new Runnable() { + public void run() { + fViewer.refresh(); + } + }); + fViewer.getControl().setRedraw(true); + } + } + + /** + * Returns true if the given filter is installed. + * + * @param filterProperty + * the filter to be tested. Valid values are + * FILTER_FIELDS, FILTER_PUBLIC, + * and FILTER_PRIVATE as defined by this action + * group + */ + public boolean hasMemberFilter(int filterProperty) { + return fFilter.hasFilter(filterProperty); + } + + /** + * Saves the state of the filter actions in a memento. + * + * @param memento + * the memento to which the state is saved + */ + public void saveState(IMemento memento) { + memento.putString(TAG_HIDEFIELDS, String + .valueOf(hasMemberFilter(FILTER_FIELDS))); + memento.putString(TAG_HIDESTATIC, String + .valueOf(hasMemberFilter(FILTER_STATIC))); + memento.putString(TAG_HIDENONPUBLIC, String + .valueOf(hasMemberFilter(FILTER_NONPUBLIC))); + } + + /** + * Restores the state of the filter actions from a memento. + *

+ * Note: This method does not refresh the viewer. + *

+ * + * @param memento + * the memento from which the state is restored + */ + public void restoreState(IMemento memento) { + setMemberFilters(new int[] { FILTER_FIELDS, FILTER_STATIC, + FILTER_NONPUBLIC }, new boolean[] { + Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)) + .booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDESTATIC)) + .booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)) + .booleanValue() }, false); + } + + /* + * (non-Javadoc) + * + * @see ActionGroup#fillActionBars(IActionBars) + */ + public void fillActionBars(IActionBars actionBars) { + contributeToToolBar(actionBars.getToolBarManager()); + }; + + /** + * Adds the filter actions to the given tool bar + * + * @param tbm + * the tool bar to which the actions are added + */ + public void contributeToToolBar(IToolBarManager tbm) { + if (fInViewMenu) + return; + tbm.add(fFilterActions[0]); // fields + tbm.add(fFilterActions[1]); // static + tbm.add(fFilterActions[2]); // public + } + + /** + * Adds the filter actions to the given menu manager. + * + * @param menu + * the menu manager to which the actions are added + * @since 2.1 + */ +// public void contributeToViewMenu(IMenuManager menu) { +// if (!fInViewMenu) +// return; +// final String filters = "filters"; //$NON-NLS-1$ +// if (menu.find(filters) != null) { +// menu.prependToGroup(filters, fFilterActions[0]); // fields +// menu.prependToGroup(filters, fFilterActions[1]); // static +// menu.prependToGroup(filters, fFilterActions[2]); // public +// } else { +// menu.add(fFilterActions[0]); // fields +// menu.add(fFilterActions[1]); // static +// menu.add(fFilterActions[2]); // public +// } +// } + + /* + * (non-Javadoc) + * + * @see ActionGroup#dispose() + */ + public void dispose() { + super.dispose(); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenEditorActionGroup.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java new file mode 100644 index 0000000..1583139 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/OpenPHPPerspectiveAction.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui.actions; + +import net.sourceforge.phpdt.internal.ui.actions.ActionMessages; +import net.sourceforge.phpdt.internal.ui.util.ExceptionHandler; +import net.sourceforge.phpdt.ui.JavaUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.jface.action.Action; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.WorkbenchException; + +/** + * Action to programmatically open a Java perspective. + * + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * @since 2.0 + */ +public class OpenPHPPerspectiveAction extends Action { + + /** + * Create a new OpenPHPPerspectiveAction. + */ + public OpenPHPPerspectiveAction() { + // WorkbenchHelp.setHelp(this, + // IJavaHelpContextIds.OPEN_JAVA_PERSPECTIVE_ACTION); + } + + public void run() { + IWorkbench workbench = PHPeclipsePlugin.getDefault().getWorkbench(); + IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); + IWorkbenchPage page = window.getActivePage(); + IAdaptable input; + if (page != null) + input = page.getInput(); + else + input = ResourcesPlugin.getWorkspace().getRoot(); + try { + workbench.showPerspective(JavaUI.ID_PERSPECTIVE, window, + input); + } catch (WorkbenchException e) { + ExceptionHandler + .handle( + e, + window.getShell(), + ActionMessages + .getString("OpenPHPPerspectiveAction.dialog.title"), //$NON-NLS-1$ + ActionMessages + .getString("OpenPHPPerspectiveAction.error.open_failed")); //$NON-NLS-1$ + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPEditorActionDefinitionIds.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/PHPdtActionConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/SelectionDispatchAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IColorManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IColorManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IColorManagerExtension.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/IJavaColorConstants.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java new file mode 100644 index 0000000..3616ccc --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java @@ -0,0 +1,736 @@ +package net.sourceforge.phpdt.ui.text; + +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ + +import net.sourceforge.phpdt.internal.ui.text.FastJavaPartitionScanner; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaColorManager; +import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCodeScanner; +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.phpeditor.php.HTMLPartitionScanner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPCodeScanner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPDocumentPartitioner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPPartitionScanner; +import net.sourceforge.phpeclipse.phpeditor.php.SmartyCodeScanner; +import net.sourceforge.phpeclipse.phpeditor.php.SmartyDocCodeScanner; +import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; +import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; + +import org.eclipse.core.runtime.Preferences; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension3; +import org.eclipse.jface.text.IDocumentPartitioner; +//import org.eclipse.jface.text.rules.DefaultPartitioner; +import org.eclipse.jface.text.rules.FastPartitioner; +//import org.eclipse.jface.text.rules.RuleBasedScanner; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; + +// +// import org.phpeclipse.phpdt.internal.ui.text.FastJavaPartitionScanner; +// import org.phpeclipse.phpdt.internal.ui.text.JavaColorManager; +// import org.phpeclipse.phpdt.internal.ui.text.JavaPartitionScanner; +// import org.phpeclipse.phpdt.internal.ui.text.SingleTokenJavaScanner; +// import org.phpeclipse.phpdt.internal.ui.text.php.JavaCodeScanner; +// import org.phpeclipse.phpdt.internal.ui.text.phpdoc.JavaDocScanner; + +/** + * Tools required to configure a Java text viewer. The color manager and all + * scanner exist only one time, i.e. the same instances are returned to all + * clients. Thus, clients share those tools. + *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ */ +public class JavaTextTools implements IPHPPartitions { + // private static final String[] TOKENS = { + // JSPScriptScanner.JSP_DEFAULT, + // JSPScriptScanner.JSP_BRACKET }; + private final static String[] LEGAL_CONTENT_TYPES = new String[] { + PHP_PHPDOC_COMMENT, PHP_MULTILINE_COMMENT, PHP_SINGLELINE_COMMENT, + PHP_STRING_DQ, PHP_STRING_SQ, PHP_STRING_HEREDOC }; + + // private static XMLPartitionScanner HTML_PARTITION_SCANNER = null; + + // private static FastJavaPartitionScanner PHP_PARTITION_SCANNER = null; + + private static HTMLPartitionScanner SMARTY_PARTITION_SCANNER = null; + + // private static XMLPartitionScanner XML_PARTITION_SCANNER = null; + + // private final static String[] TYPES= new String[] { + // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, + // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; + // private final static String[] TYPES = new String[] { + // IPHPPartitions.PHP_PARTITIONING, + // IPHPPartitions.PHP_PHPDOC_COMMENT, + // // IPHPPartitions.HTML, + // // IPHPPartitions.HTML_MULTILINE_COMMENT, + // IPHPPartitions.JAVASCRIPT, + // IPHPPartitions.CSS, + // IPHPPartitions.SMARTY, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT }; + + /** + * This tools' preference listener. + */ + private class PreferenceListener implements IPropertyChangeListener, + Preferences.IPropertyChangeListener { + public void propertyChange(PropertyChangeEvent event) { + adaptToPreferenceChange(event); + } + + public void propertyChange(Preferences.PropertyChangeEvent event) { + adaptToPreferenceChange(new PropertyChangeEvent(event.getSource(), + event.getProperty(), event.getOldValue(), event + .getNewValue())); + } + }; + + // /** The color manager */ + private JavaColorManager colorManager; + + /** The PHP source code scanner */ + private PHPCodeScanner fCodeScanner; + + /** The PHP multiline comment scanner */ + private SingleTokenPHPScanner fMultilineCommentScanner; + + /** The Java singleline comment scanner */ + private SingleTokenPHPScanner fSinglelineCommentScanner; + + /** The PHP double quoted string scanner */ + // private SingleTokenPHPScanner fStringDQScanner; + /** The PHP single quoted string scanner */ + // private SingleTokenPHPScanner fStringSQScanner; + /** The PHPDoc scanner */ + private PHPDocCodeScanner fPHPDocScanner; + + /** The HTML scanner */ + // private HTMLCodeScanner fHTMLScanner; + /** The Smarty scanner */ + private SmartyCodeScanner fSmartyScanner; + + /** The SmartyDoc scanner */ + private SmartyDocCodeScanner fSmartyDocScanner; + + /** The Java partitions scanner. */ + private FastJavaPartitionScanner fPartitionScanner; + + /** The preference store */ + private IPreferenceStore fPreferenceStore; + + /** The XML Language text tools */ + private XMLTextTools xmlTextTools; + + /** + * The core preference store. + * + * @since 2.1 + */ + private Preferences fCorePreferenceStore; + + /** The preference change listener */ + private PreferenceListener fPreferenceListener = new PreferenceListener(); + + /** The JSP partitions scanner */ + private PHPPartitionScanner jspPartitionScanner = null; + + /** The JSP script subpartitions scanner */ + // private JSPScriptScanner jspScriptScanner; + /** The PHP plain text scanner */ + // private RuleBasedScanner jspTextScanner; + /** The PHP brackets scanner */ + // private RuleBasedScanner jspBracketScanner; + /** + * Creates a new Java text tools collection. + * + * @param store + * the preference store to initialize the text tools. The text + * tool instance installs a listener on the passed preference + * store to adapt itself to changes in the preference store. In + * general PreferenceConstants. + * getPreferenceStore() + * should be used to initialize the text tools. + * @param coreStore + * optional preference store to initialize the text tools. The + * text tool instance installs a listener on the passed + * preference store to adapt itself to changes in the preference + * store. + * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() + * @since 2.1 + */ + public JavaTextTools(IPreferenceStore store, Preferences coreStore) { + this(store, coreStore, true); + } + + /** + * Creates a new Java text tools collection. + * + * @param store + * the preference store to initialize the text tools. The text + * tool instance installs a listener on the passed preference + * store to adapt itself to changes in the preference store. In + * general PreferenceConstants. + * getPreferenceStore() + * shoould be used to initialize the text tools. + * @param coreStore + * optional preference store to initialize the text tools. The + * text tool instance installs a listener on the passed + * preference store to adapt itself to changes in the preference + * store. + * @param autoDisposeOnDisplayDispose + * if true the color manager automatically + * disposes all managed colors when the current display gets + * disposed and all calls to + * {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()}are + * ignored. + * @see net.sourceforge.phpdt.ui.PreferenceConstants#getPreferenceStore() + * @since 2.1 + */ + public JavaTextTools(IPreferenceStore store, Preferences coreStore, + boolean autoDisposeOnDisplayDispose) { + // super(store, TOKENS, ); + // REVISIT: preference store + xmlTextTools = new XMLTextTools(XMLPlugin.getDefault() + .getPreferenceStore()); + + colorManager = new JavaColorManager(autoDisposeOnDisplayDispose); + fPreferenceStore = store; + fPreferenceStore.addPropertyChangeListener(fPreferenceListener); + + fCorePreferenceStore = coreStore; + if (fCorePreferenceStore != null) + fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener); + + fCodeScanner = new PHPCodeScanner((JavaColorManager) colorManager, + store); + fMultilineCommentScanner = new SingleTokenPHPScanner( + (JavaColorManager) colorManager, store, + IPreferenceConstants.PHP_MULTILINE_COMMENT); + fSinglelineCommentScanner = new SingleTokenPHPScanner( + (JavaColorManager) colorManager, store, + IPreferenceConstants.PHP_SINGLELINE_COMMENT); + // fStringDQScanner = new SingleTokenPHPScanner((JavaColorManager) + // colorManager, store, IPreferenceConstants.PHP_STRING); + // fStringSQScanner = new SingleTokenPHPScanner((JavaColorManager) + // colorManager, store, IPreferenceConstants.PHP_STRING); + + fPHPDocScanner = new PHPDocCodeScanner((JavaColorManager) colorManager, + store); + // fHTMLScanner = new HTMLCodeScanner((JavaColorManager)fColorManager, + // store); + fSmartyScanner = new SmartyCodeScanner((JavaColorManager) colorManager, + store); + fSmartyDocScanner = new SmartyDocCodeScanner( + (JavaColorManager) colorManager, store); + + fPartitionScanner = new FastJavaPartitionScanner(); + + // jspScriptScanner = new JSPScriptScanner(); + // fPartitionScanner = new FastJavaPartitionScanner(); + // fPartitionScanner = new PHPPartitionScanner(); + + // jspBracketScanner = new RuleBasedScanner(); + // jspBracketScanner.setDefaultReturnToken(new + // Token(JSPScriptScanner.JSP_BRACKET)); + // jspTextScanner = new RuleBasedScanner(); + // jspTextScanner.setDefaultReturnToken(new + // Token(JSPScriptScanner.JSP_DEFAULT)); + } + + /** + * + */ + public XMLTextTools getXMLTextTools() { + return xmlTextTools; + } + + /** + * Disposes all the individual tools of this tools collection. + */ + public void dispose() { + + fCodeScanner = null; + fMultilineCommentScanner = null; + fSinglelineCommentScanner = null; + // fStringDQScanner = null; + // fStringSQScanner = null; + fPHPDocScanner = null; + // fPartitionScanner = null; + + if (colorManager != null) { + colorManager.dispose(); + colorManager = null; + } + + if (fPreferenceStore != null) { + fPreferenceStore.removePropertyChangeListener(fPreferenceListener); + fPreferenceStore = null; + + if (fCorePreferenceStore != null) { + fCorePreferenceStore + .removePropertyChangeListener(fPreferenceListener); + fCorePreferenceStore = null; + } + + fPreferenceListener = null; + } + } + + /** + * Returns the color manager which is used to manage any Java-specific + * colors needed for such things like syntax highlighting. + * + * @return the color manager to be used for Java text viewers + */ + public JavaColorManager getColorManager() { + return (JavaColorManager) colorManager; + } + + /** + * Returns a scanner which is configured to scan Java source code. + * + * @return a Java source code scanner + */ +// public RuleBasedScanner getCodeScanner() { +// return fCodeScanner; +// } + + /** + * Returns a scanner which is configured to scan Java multiline comments. + * + * @return a Java multiline comment scanner + * + * @since 2.0 + */ +// public RuleBasedScanner getMultilineCommentScanner() { +// return fMultilineCommentScanner; +// } + + /** + * Returns a scanner which is configured to scan HTML code. + * + * @return a HTML scanner + * + * @since 2.0 + */ + // public RuleBasedScanner getHTMLScanner() { + // return fHTMLScanner; + // } + /** + * Returns a scanner which is configured to scan Smarty code. + * + * @return a Smarty scanner + * + * @since 2.0 + */ +// public RuleBasedScanner getSmartyScanner() { +// return fSmartyScanner; +// } + + /** + * Returns a scanner which is configured to scan Smarty code. + * + * @return a Smarty scanner + * + * @since 2.0 + */ +// public RuleBasedScanner getSmartyDocScanner() { +// return fSmartyDocScanner; +// } + + /** + * Returns a scanner which is configured to scan Java singleline comments. + * + * @return a Java singleline comment scanner + * + * @since 2.0 + */ +// public RuleBasedScanner getSinglelineCommentScanner() { +// return fSinglelineCommentScanner; +// } + + /** + * Returns a scanner which is configured to scan Java strings. + * + * @return a Java string scanner + * + * @since 2.0 + */ + // public RuleBasedScanner getStringScanner() { + // return fStringDQScanner; + // } + /** + * Returns a scanner which is configured to scan JavaDoc compliant comments. + * Notes that the start sequence "/**" and the corresponding end sequence + * are part of the JavaDoc comment. + * + * @return a JavaDoc scanner + */ +// public RuleBasedScanner getJavaDocScanner() { +// return fPHPDocScanner; +// } + + /** + * Returns a scanner which is configured to scan Java-specific partitions, + * which are multi-line comments, JavaDoc comments, and regular Java source + * code. + * + * @return a Java partition scanner + */ + // public IPartitionTokenScanner getPartitionScanner() { + // return fPartitionScanner; + // } + /** + * Factory method for creating a PHP-specific document partitioner using + * this object's partitions scanner. This method is a convenience method. + * + * @return a newly created Java document partitioner + */ + public IDocumentPartitioner createDocumentPartitioner() { + return createDocumentPartitioner(".php"); + } + + /** + * Factory method for creating a PHP-specific document partitioner using + * this object's partitions scanner. This method is a convenience method. + * + * @return a newly created Java document partitioner + */ + public IDocumentPartitioner createDocumentPartitioner(String extension) { + + // String[] types = + // new String[] { + // FastJavaPartitionScanner.JAVA_DOC, + // FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT, + // FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT, + // FastJavaPartitionScanner.JAVA_STRING }; + // + // return new DefaultPartitioner(getPartitionScanner(), types); + IDocumentPartitioner partitioner = null; + // System.out.println(extension); + if (extension.equalsIgnoreCase(".html") + || extension.equalsIgnoreCase(".htm")) { + // html + partitioner = createHTMLPartitioner(); + partitioner = createJSPPartitioner(); + } else if (extension.equalsIgnoreCase(".xml")) { + // xml + partitioner = createXMLPartitioner(); + // } else if (extension.equalsIgnoreCase(".js")) { + // // javascript + // partitioner = createJavaScriptPartitioner(); + // } else if (extension.equalsIgnoreCase(".css")) { + // // cascading style sheets + // partitioner = createCSSPartitioner(); + } else if (extension.equalsIgnoreCase(".tpl")) { + // smarty ? + partitioner = createSmartyPartitioner(); + // } else if (extension.equalsIgnoreCase(".inc")) { + // // php include files ? + // partitioner = createIncludePartitioner(); + } + + if (partitioner == null) { + partitioner = createJSPPartitioner(); + } + + return partitioner; + } + + /** + * Sets up the Java document partitioner for the given document for the + * given partitioning. + * + * @param document + * the document to be set up + * @param partitioning + * the document partitioning + * @param element + * TODO + * + * @since 3.0 + */ + // public void setupJavaDocumentPartitioner(IDocument document, String + // partitioning, Object element) { + // IDocumentPartitioner partitioner = createDocumentPartitioner(".php"); + // + // // if (document instanceof IDocumentExtension3) { + // // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // // extension3.setDocumentPartitioner(partitioning, partitioner); + // // } else { + // document.setDocumentPartitioner(partitioner); + // // } + // partitioner.connect(document); + // } + public void setupHTMLDocumentPartitioner(IDocument document, + String partitioning, Object element) { + IDocumentPartitioner partitioner = createDocumentPartitioner(".html"); + + // if (document instanceof IDocumentExtension3) { + // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // extension3.setDocumentPartitioner(partitioning, partitioner); + // } else { + document.setDocumentPartitioner(partitioner); + // } + partitioner.connect(document); + } + + public void setupSmartyDocumentPartitioner(IDocument document, + String partitioning, Object element) { + IDocumentPartitioner partitioner = createDocumentPartitioner(".tpl"); + + // if (document instanceof IDocumentExtension3) { + // IDocumentExtension3 extension3= (IDocumentExtension3) document; + // extension3.setDocumentPartitioner(partitioning, partitioner); + // } else { + document.setDocumentPartitioner(partitioner); + // } + partitioner.connect(document); + } + + /** + * Returns the names of the document position categories used by the + * document partitioners created by this object to manage their partition + * information. If the partitioners don't use document position categories, + * the returned result is null. + * + * @return the partition managing position categories or null + * if there is none + */ +// public String[] getPartitionManagingPositionCategories() { +// return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; +// } + + /** + * Determines whether the preference change encoded by the given event + * changes the behavior of one its contained components. + * + * @param event + * the event to be investigated + * @return true if event causes a behavioral change + * @since 2.0 + * @deprecated As of 3.0, replaced by + * {@link net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration#affectsTextPresentation(PropertyChangeEvent)} + */ + // public boolean affectsBehavior(PropertyChangeEvent event) { + // return fCodeScanner.affectsBehavior(event) + // || fMultilineCommentScanner.affectsBehavior(event) + // || fSinglelineCommentScanner.affectsBehavior(event) + // || fStringDQScanner.affectsBehavior(event) + // || fPHPDocScanner.affectsBehavior(event); + // } + /** + * Adapts the behavior of the contained components to the change encoded in + * the given event. + * + * @param event + * the event to which to adapt + * @since 2.0 + */ + protected void adaptToPreferenceChange(PropertyChangeEvent event) { + if (fCodeScanner.affectsBehavior(event)) + fCodeScanner.adaptToPreferenceChange(event); + if (fMultilineCommentScanner.affectsBehavior(event)) + fMultilineCommentScanner.adaptToPreferenceChange(event); + if (fSinglelineCommentScanner.affectsBehavior(event)) + fSinglelineCommentScanner.adaptToPreferenceChange(event); + // if (fStringDQScanner.affectsBehavior(event)) + // fStringDQScanner.adaptToPreferenceChange(event); + if (fPHPDocScanner.affectsBehavior(event)) + fPHPDocScanner.adaptToPreferenceChange(event); + // if (fHTMLScanner.affectsBehavior(event)) + // fHTMLScanner.adaptToPreferenceChange(event); + if (fSmartyScanner.affectsBehavior(event)) + fSmartyScanner.adaptToPreferenceChange(event); + if (fSmartyDocScanner.affectsBehavior(event)) + fSmartyDocScanner.adaptToPreferenceChange(event); + // if (XMLPlugin.getDefault().getXMLTextTools().affectsBehavior(event)) + // { + // XMLPlugin.getDefault().getXMLTextTools().adaptToPreferenceChange(event); + // } + } + + /** + * Return a partitioner for .html files. + */ + public IDocumentPartitioner createHTMLPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + return xmlTextTools.createXMLPartitioner(); + } + + // private static IDocumentPartitioner createIncludePartitioner() { + // // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // return new DefaultPartitioner(getPHPPartitionScanner(), + // FastJavaPartitionScanner.PHP_PARTITION_TYPES); + // + // } + + // private static IDocumentPartitioner createJavaScriptPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + + /** + * Return a partitioner for .php files. + */ + public IDocumentPartitioner createPHPPartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + return new /*DefaultPartitioner*/FastPartitioner(getPHPPartitionScanner(), + LEGAL_CONTENT_TYPES); + } + + private IDocumentPartitioner createJSPPartitioner() { + return new PHPDocumentPartitioner(getJSPPartitionScanner()); + // return new JSPDocumentPartitioner(getJSPPartitionScanner(), + // jspScriptScanner); + } + + /** + * + */ + // public IPartitionTokenScanner getJSPScriptScanner() { + // return jspScriptScanner; + // } + private IDocumentPartitioner createSmartyPartitioner() { + return new /*DefaultPartitioner*/FastPartitioner(getSmartyPartitionScanner(), + XMLTextTools.TYPES); + } + + private IDocumentPartitioner createXMLPartitioner() { + // return new DefaultPartitioner(getXMLPartitionScanner(), + // XMLTextTools.TYPES); + return xmlTextTools.createXMLPartitioner(); + } + + // private IDocumentPartitioner createCSSPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), + // XMLTextTools.TYPES); + // } + + /** + * Return a scanner for creating html partitions. + */ + // private static XMLPartitionScanner getHTMLPartitionScanner() { + // // if (HTML_PARTITION_SCANNER == null) + // // HTML_PARTITION_SCANNER = new + // HTMLPartitionScanner(IPHPPartitions.HTML_FILE); + // // return HTML_PARTITION_SCANNER;^ + // if (HTML_PARTITION_SCANNER == null) + // HTML_PARTITION_SCANNER = new XMLPartitionScanner(false); + // return HTML_PARTITION_SCANNER; + // } + /** + * Return a scanner for creating php partitions. + */ + private FastJavaPartitionScanner getPHPPartitionScanner() { + // if (PHP_PARTITION_SCANNER == null) + // PHP_PARTITION_SCANNER = new FastJavaPartitionScanner(); //new + // PHPPartitionScanner(IPHPPartitions.PHP_FILE); + // return PHP_PARTITION_SCANNER; + return fPartitionScanner; + } + + /** + * Returns a scanner which is configured to scan plain text in JSP. + * + * @return a JSP text scanner + */ + // public RuleBasedScanner getJSPTextScanner() { + // return jspTextScanner; + // } + /** + * Returns a scanner which is configured to scan plain text in JSP. + * + * @return a JSP text scanner + */ + // public RuleBasedScanner getJSPBracketScanner() { + // return jspBracketScanner; + // } + /** + * Return a scanner for creating smarty partitions. + */ + private static HTMLPartitionScanner getSmartyPartitionScanner() { + if (SMARTY_PARTITION_SCANNER == null) + SMARTY_PARTITION_SCANNER = new HTMLPartitionScanner( + IPHPPartitions.SMARTY_FILE); + return SMARTY_PARTITION_SCANNER; + } + + /** + * Return a scanner for creating xml partitions. + */ + // private static XMLPartitionScanner getXMLPartitionScanner() { + // // if (XML_PARTITION_SCANNER == null) + // // XML_PARTITION_SCANNER = new + // HTMLPartitionScanner(IPHPPartitions.XML_FILE); + // // return XML_PARTITION_SCANNER; + // if (XML_PARTITION_SCANNER == null) + // XML_PARTITION_SCANNER = new XMLPartitionScanner(false); + // return XML_PARTITION_SCANNER; + // } + private PHPPartitionScanner getJSPPartitionScanner() { + if (jspPartitionScanner == null) + jspPartitionScanner = new PHPPartitionScanner(); + return jspPartitionScanner; + } + + /** + * Sets up the Java document partitioner for the given document for the + * default partitioning. + * + * @param document + * the document to be set up + * @since 3.0 + */ + public void setupJavaDocumentPartitioner(IDocument document) { + setupJavaDocumentPartitioner(document, + IDocumentExtension3.DEFAULT_PARTITIONING); + } + + /** + * Sets up the Java document partitioner for the given document for the + * given partitioning. + * + * @param document + * the document to be set up + * @param partitioning + * the document partitioning + * @since 3.0 + */ + public void setupJavaDocumentPartitioner(IDocument document, + String partitioning) { + IDocumentPartitioner partitioner = createDocumentPartitioner(); + if (document instanceof IDocumentExtension3) { + IDocumentExtension3 extension3 = (IDocumentExtension3) document; + extension3.setDocumentPartitioner(partitioning, partitioner); + } else { + document.setDocumentPartitioner(partitioner); + } + partitioner.connect(document); + } + + /** + * Returns this text tool's preference store. + * + * @return the preference store + * @since 3.0 + */ + protected IPreferenceStore getPreferenceStore() { + return fPreferenceStore; + } + + /** + * Returns this text tool's core preference store. + * + * @return the core preference store + * @since 3.0 + */ +// protected Preferences getCorePreferenceStore() { +// return fCorePreferenceStore; +// } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java new file mode 100644 index 0000000..6a47790 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPSourceViewerConfiguration.java @@ -0,0 +1,1149 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ +package net.sourceforge.phpdt.ui.text; + +import java.util.Vector; + +import net.sourceforge.phpdt.core.JavaCore; +//import net.sourceforge.phpdt.internal.debug.ui.PHPDebugUiMessages; +import net.sourceforge.phpdt.internal.ui.text.AbstractJavaScanner; +import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference; +import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaAnnotationHover; +import net.sourceforge.phpdt.internal.ui.text.JavaCompositeReconcilingStrategy; +import net.sourceforge.phpdt.internal.ui.text.JavaElementProvider; +import net.sourceforge.phpdt.internal.ui.text.JavaOutlineInformationControl; +import net.sourceforge.phpdt.internal.ui.text.JavaPresentationReconciler; +import net.sourceforge.phpdt.internal.ui.text.JavaReconciler; +import net.sourceforge.phpdt.internal.ui.text.java.JavaFormattingStrategy; +import net.sourceforge.phpdt.internal.ui.text.java.JavaStringAutoIndentStrategyDQ; +import net.sourceforge.phpdt.internal.ui.text.java.JavaStringAutoIndentStrategySQ; +import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; +import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy; +import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaInformationProvider; +import net.sourceforge.phpdt.internal.ui.text.phpdoc.JavaDocAutoIndentStrategy; +import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCodeScanner; +import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCompletionProcessor; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.HTMLCompletionProcessor; +import net.sourceforge.phpeclipse.phpeditor.php.PHPAutoIndentStrategy; +import net.sourceforge.phpeclipse.phpeditor.php.PHPCodeScanner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPCompletionProcessor; +import net.sourceforge.phpeclipse.phpeditor.php.PHPDocumentPartitioner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPDoubleClickSelector; +import net.sourceforge.phpeclipse.phpeditor.php.PHPPartitionScanner; +//import net.sourceforge.phpeclipse.xml.ui.XMLPlugin; +import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLConfiguration; +import net.sourceforge.phpeclipse.xml.ui.internal.text.XMLPartitionScanner; +import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; + +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.DefaultIndentLineAutoEditStrategy; +import org.eclipse.jface.text.DefaultInformationControl; +import org.eclipse.jface.text.IAutoEditStrategy; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IInformationControl; +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.ITextDoubleClickStrategy; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextViewerExtension2; +import org.eclipse.jface.text.TextAttribute; +import org.eclipse.jface.text.contentassist.ContentAssistant; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContentAssistant; +import org.eclipse.jface.text.formatter.ContentFormatter; +import org.eclipse.jface.text.formatter.IContentFormatter; +import org.eclipse.jface.text.formatter.IFormattingStrategy; +import org.eclipse.jface.text.information.IInformationPresenter; +import org.eclipse.jface.text.information.IInformationProvider; +import org.eclipse.jface.text.information.InformationPresenter; +import org.eclipse.jface.text.presentation.IPresentationDamager; +import org.eclipse.jface.text.presentation.IPresentationReconciler; +import org.eclipse.jface.text.presentation.IPresentationRepairer; +import org.eclipse.jface.text.presentation.PresentationReconciler; +import org.eclipse.jface.text.reconciler.IReconciler; +import org.eclipse.jface.text.rules.BufferedRuleBasedScanner; +import org.eclipse.jface.text.rules.DefaultDamagerRepairer; +import org.eclipse.jface.text.rules.DefaultPartitioner; +import org.eclipse.jface.text.rules.RuleBasedScanner; +import org.eclipse.jface.text.rules.Token; +import org.eclipse.jface.text.source.IAnnotationHover; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.SourceViewerConfiguration; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Configuration for an SourceViewer which shows PHP code. + */ +public class PHPSourceViewerConfiguration extends SourceViewerConfiguration { + /** + * Preference key used to look up display tab width. + * + * @since 2.0 + */ + public final static String PREFERENCE_TAB_WIDTH = PreferenceConstants.EDITOR_TAB_WIDTH; + + /** + * Preference key for inserting spaces rather than tabs. + * + * @since 2.0 + */ + public final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; + + // public static final String HTML_DEFAULT = + // IPHPPartitionScannerConstants.HTML; + // IDocument.DEFAULT_CONTENT_TYPE; + // private JavaTextTools fJavaTextTools; + + private ITextEditor fTextEditor; + + /** + * The document partitioning. + * + * @since 3.0 + */ + private String fDocumentPartitioning; + + private ContentFormatter fFormatter; + + /** + * Single token scanner. + */ + static class SingleTokenScanner extends BufferedRuleBasedScanner { + public SingleTokenScanner(TextAttribute attribute) { + setDefaultReturnToken(new Token(attribute)); + } + }; + + /** + * The document partitioning. + * + * @since 3.0 + */ + // private String fDocumentPartitioning; + /** + * The Java source code scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fCodeScanner; + + /** + * The Java multi-line comment scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fMultilineCommentScanner; + + /** + * The Java single-line comment scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fSinglelineCommentScanner; + + /** + * The PHP double quoted string scanner + */ + private AbstractJavaScanner fStringDQScanner; + + /** + * The PHP single quoted string scanner + */ + private AbstractJavaScanner fStringSQScanner; + + /** + * The Javadoc scanner + * + * @since 3.0 + */ + private AbstractJavaScanner fJavaDocScanner; + + /** + * The preference store, can be read-only + * + * @since 3.0 + */ + private IPreferenceStore fPreferenceStore; + + /** + * The color manager + * + * @since 3.0 + */ + private IColorManager fColorManager; + + private XMLTextTools fXMLTextTools; + + private XMLConfiguration xmlConfiguration; + + /** + * Creates a new Java source viewer configuration for viewers in the given + * editor using the given preference store, the color manager and the + * specified document partitioning. + *

+ * Creates a Java source viewer configuration in the new setup without text + * tools. Clients are allowed to call + * {@link JavaSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}and + * disallowed to call + * {@link JavaSourceViewerConfiguration#getPreferenceStore()}on the + * resulting Java source viewer configuration. + *

+ * + * @param colorManager + * the color manager + * @param preferenceStore + * the preference store, can be read-only + * @param editor + * the editor in which the configured viewer(s) will reside + * @param partitioning + * the document partitioning for this configuration + * @since 3.0 + */ + public PHPSourceViewerConfiguration(IColorManager colorManager, + IPreferenceStore preferenceStore, ITextEditor editor, + String partitioning) { + fColorManager = colorManager; + fPreferenceStore = preferenceStore; + fTextEditor = editor; + fDocumentPartitioning = partitioning; + // fJavaTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + fXMLTextTools = new XMLTextTools(getPreferenceStore()); + //XMLPlugin.getDefault().getXMLTextTools(); + xmlConfiguration = new XMLConfiguration(fXMLTextTools); + fColorManager = colorManager; + fPreferenceStore = preferenceStore; + fTextEditor = editor; + fDocumentPartitioning = partitioning; + + initializeScanners(); + } + + /** + * Creates a new Java source viewer configuration for viewers in the given + * editor using the given Java tools. + * + * @param tools + * the Java text tools to be used + * @param editor + * the editor in which the configured viewer(s) will reside + * @see JavaTextTools + * @deprecated As of 3.0, replaced by + * {@link JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, IPreferenceStore, ITextEditor, String)} + */ + // public PHPSourceViewerConfiguration(JavaTextTools tools, PHPEditor + // editor, String partitioning) { + // fJavaTextTools = tools; + // fColorManager = tools.getColorManager(); + // fPreferenceStore = createPreferenceStore(); + // fDocumentPartitioning = partitioning; + // fCodeScanner = (AbstractJavaScanner) fJavaTextTools.getCodeScanner(); + // fMultilineCommentScanner = (AbstractJavaScanner) + // fJavaTextTools.getMultilineCommentScanner(); + // fSinglelineCommentScanner = (AbstractJavaScanner) + // fJavaTextTools.getSinglelineCommentScanner(); + // fStringDQScanner = (AbstractJavaScanner) + // fJavaTextTools.getStringScanner(); + // fJavaDocScanner = (AbstractJavaScanner) + // fJavaTextTools.getJavaDocScanner(); + // fTextEditor = editor; + // fXMLTextTools = XMLPlugin.getDefault().getXMLTextTools(); + // xmlConfiguration = new XMLConfiguration(fXMLTextTools); + // } + /** + * Returns the color manager for this configuration. + * + * @return the color manager + */ + protected IColorManager getColorManager() { + return fColorManager; + } + + /** + * Initializes the scanners. + * + * @since 3.0 + */ + private void initializeScanners() { + // Assert.isTrue(isNewSetup()); + fCodeScanner = new PHPCodeScanner(getColorManager(), fPreferenceStore); + fMultilineCommentScanner = new SingleTokenPHPScanner(getColorManager(), + fPreferenceStore, IPreferenceConstants.PHP_MULTILINE_COMMENT); + fSinglelineCommentScanner = new SingleTokenPHPScanner( + getColorManager(), fPreferenceStore, + IPreferenceConstants.PHP_SINGLELINE_COMMENT); + // fStringDQScanner = new SingleTokenPHPScanner(getColorManager(), + // fPreferenceStore, IPreferenceConstants.PHP_STRING_DQ); + fStringDQScanner = new PHPStringDQCodeScanner(getColorManager(), + fPreferenceStore); + fStringSQScanner = new SingleTokenPHPScanner(getColorManager(), + fPreferenceStore, IPreferenceConstants.PHP_STRING_SQ); + fJavaDocScanner = new PHPDocCodeScanner(getColorManager(), + fPreferenceStore); + } + + /** + * Determines whether the preference change encoded by the given event + * changes the behavior of one of its contained components. + * + * @param event + * the event to be investigated + * @return true if event causes a behavioral change + * @since 3.0 + */ + public boolean affectsTextPresentation(PropertyChangeEvent event) { + return fCodeScanner.affectsBehavior(event) + || fMultilineCommentScanner.affectsBehavior(event) + || fSinglelineCommentScanner.affectsBehavior(event) + || fStringDQScanner.affectsBehavior(event) + || fStringSQScanner.affectsBehavior(event) + || fJavaDocScanner.affectsBehavior(event); + } + + /** + * Adapts the behavior of the contained components to the change encoded in + * the given event. + *

+ * Clients are not allowed to call this method if the old setup with text + * tools is in use. + *

+ * + * @param event + * the event to which to adapt + * @see JavaSourceViewerConfiguration#JavaSourceViewerConfiguration(IColorManager, + * IPreferenceStore, ITextEditor, String) + * @since 3.0 + */ + public void handlePropertyChangeEvent(PropertyChangeEvent event) { + // Assert.isTrue(isNewSetup()); + if (fCodeScanner.affectsBehavior(event)) + fCodeScanner.adaptToPreferenceChange(event); + if (fMultilineCommentScanner.affectsBehavior(event)) + fMultilineCommentScanner.adaptToPreferenceChange(event); + if (fSinglelineCommentScanner.affectsBehavior(event)) + fSinglelineCommentScanner.adaptToPreferenceChange(event); + if (fStringDQScanner.affectsBehavior(event)) + fStringDQScanner.adaptToPreferenceChange(event); + if (fStringSQScanner.affectsBehavior(event)) + fStringSQScanner.adaptToPreferenceChange(event); + if (fJavaDocScanner.affectsBehavior(event)) + fJavaDocScanner.adaptToPreferenceChange(event); + } + + /* + * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) + */ + public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { + // if (fFormatter == null) { + // fFormatter = new ContentFormatter(); + // fFormattingStrategy = new HTMLFormattingStrategy(this, + // sourceViewer); + // fFormatter.setFormattingStrategy(fFormattingStrategy, HTML_DEFAULT); + // fFormatter.enablePartitionAwareFormatting(false); + // fFormatter.setPartitionManagingPositionCategories(getConfiguredContentTypes(null)); + // } + // return fFormatter; + if (fFormatter == null) { + // ContentFormatter + fFormatter = new ContentFormatter(); + IFormattingStrategy strategy = new JavaFormattingStrategy( + sourceViewer); + fFormatter.setFormattingStrategy(strategy, + IDocument.DEFAULT_CONTENT_TYPE); + fFormatter.enablePartitionAwareFormatting(false); + fFormatter + .setPartitionManagingPositionCategories(getPartitionManagingPositionCategories()); + } + return fFormatter; + } + + /** + * Returns the names of the document position categories used by the + * document partitioners created by this object to manage their partition + * information. If the partitioners don't use document position categories, + * the returned result is null. + * + * @return the partition managing position categories or null + * if there is none + */ + public String[] getPartitionManagingPositionCategories() { + return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; + } + + // /** + // * Returns the names of the document position categories used by the + // document + // * partitioners created by this object to manage their partition + // information. + // * If the partitioners don't use document position categories, the + // returned + // * result is null. + // * + // * @return the partition managing position categories or + // null + // * if there is none + // */ + // private String[] getPartitionManagingPositionCategories() { + // return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY }; + // } + public ITextEditor getEditor() { + return fTextEditor; + } + + /** + * Returns the preference store used by this configuration to initialize the + * individual bits and pieces. + * + * @return the preference store used to initialize this configuration + * + * @since 2.0 + */ + protected IPreferenceStore getPreferenceStore() { + return PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + // /* (non-Javadoc) + // * Method declared on SourceViewerConfiguration + // */ + // public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + // return new PHPAnnotationHover(); + // } + /* + * @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer) + */ + public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { + return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER); + } + + /* + * @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer) + * @since 3.0 + */ + public IAnnotationHover getOverviewRulerAnnotationHover( + ISourceViewer sourceViewer) { + return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER); + } + + public IAutoEditStrategy[] getAutoEditStrategies( + ISourceViewer sourceViewer, String contentType) { + IAutoEditStrategy strategy = new DefaultIndentLineAutoEditStrategy(); + if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(contentType) + || IPHPPartitions.PHP_MULTILINE_COMMENT.equals(contentType)) + strategy = new JavaDocAutoIndentStrategy( + getConfiguredDocumentPartitioning(sourceViewer)); + else if (IPHPPartitions.PHP_STRING_DQ.equals(contentType)) + strategy = new JavaStringAutoIndentStrategyDQ( + getConfiguredDocumentPartitioning(sourceViewer)); + else if (IPHPPartitions.PHP_STRING_SQ.equals(contentType)) + strategy = new JavaStringAutoIndentStrategySQ( + getConfiguredDocumentPartitioning(sourceViewer)); + else + strategy = (PHPDocumentPartitioner.PHP_TEMPLATE_DATA + .equals(contentType) + || PHPDocumentPartitioner.PHP_SCRIPT_CODE + .equals(contentType) + || IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) + || IPHPPartitions.PHP_PARTITIONING.equals(contentType) + || PHPPartitionScanner.PHP_SCRIPTING_AREA + .equals(contentType) ? new PHPAutoIndentStrategy() + : new DefaultIndentLineAutoEditStrategy()); + IAutoEditStrategy[] result = new IAutoEditStrategy[1]; + result[0] = strategy; + return result; + } + + /** + * Returns the PHP source code scanner for this configuration. + * + * @return the PHP source code scanner + */ + protected RuleBasedScanner getCodeScanner() { + return fCodeScanner; // fJavaTextTools.getCodeScanner(); + } + + /** + * Returns the Java multi-line comment scanner for this configuration. + * + * @return the Java multi-line comment scanner + * @since 2.0 + */ + protected RuleBasedScanner getMultilineCommentScanner() { + return fMultilineCommentScanner; + } + + /** + * Returns the Java single-line comment scanner for this configuration. + * + * @return the Java single-line comment scanner + * @since 2.0 + */ + protected RuleBasedScanner getSinglelineCommentScanner() { + return fSinglelineCommentScanner; + } + + /** + * Returns the PHP double quoted string scanner for this configuration. + * + * @return the PHP double quoted string scanner + */ + protected RuleBasedScanner getStringDQScanner() { + return fStringDQScanner; + } + + /** + * Returns the PHP single quoted string scanner for this configuration. + * + * @return the PHP single quoted string scanner + */ + protected RuleBasedScanner getStringSQScanner() { + return fStringSQScanner; + } + + /** + * Returns the HTML source code scanner for this configuration. + * + * @return the HTML source code scanner + */ + // protected RuleBasedScanner getHTMLScanner() { + // return fJavaTextTools.getHTMLScanner(); + // } + /** + * Returns the Smarty source code scanner for this configuration. + * + * @return the Smarty source code scanner + */ + // protected RuleBasedScanner getSmartyScanner() { + // return fJavaTextTools.getSmartyScanner(); + // } + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ + public IReconciler getReconciler(ISourceViewer sourceViewer) { + + final ITextEditor editor = getEditor(); + if (editor != null && editor.isEditable()) { + + JavaCompositeReconcilingStrategy strategy = new JavaCompositeReconcilingStrategy( + editor, getConfiguredDocumentPartitioning(sourceViewer)); + JavaReconciler reconciler = new JavaReconciler(editor, strategy, + false); + reconciler.setIsIncrementalReconciler(false); + reconciler.setProgressMonitor(new NullProgressMonitor()); + reconciler.setDelay(500); + + return reconciler; + } + return null; + } + + /* + * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, + * String) + * @since 2.1 + */ + public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, + String contentType) { + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .getDefault().getJavaEditorTextHoverDescriptors(); + int stateMasks[] = new int[hoverDescs.length]; + int stateMasksLength = 0; + for (int i = 0; i < hoverDescs.length; i++) { + if (hoverDescs[i].isEnabled()) { + int j = 0; + int stateMask = hoverDescs[i].getStateMask(); + while (j < stateMasksLength) { + if (stateMasks[j] == stateMask) + break; + j++; + } + if (j == stateMasksLength) + stateMasks[stateMasksLength++] = stateMask; + } + } + if (stateMasksLength == hoverDescs.length) + return stateMasks; + int[] shortenedStateMasks = new int[stateMasksLength]; + System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, + stateMasksLength); + return shortenedStateMasks; + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) + * @since 2.1 + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType, int stateMask) { + JavaEditorTextHoverDescriptor[] hoverDescs = PHPeclipsePlugin + .getDefault().getJavaEditorTextHoverDescriptors(); + int i = 0; + while (i < hoverDescs.length) { + if (hoverDescs[i].isEnabled() + && hoverDescs[i].getStateMask() == stateMask) + return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor()); + i++; + } + return null; + // if (fEditor != null) { + // IEditorInput editorInput = fEditor.getEditorInput(); + // if (editorInput instanceof IFileEditorInput) { + // try { + // IFile f = ((IFileEditorInput) editorInput).getFile(); + // return new PHPTextHover(f.getProject()); + // } catch (NullPointerException e) { + // // this exception occurs, if getTextHover is called by + // // preference pages ! + // } + // } + // } + // return new PHPTextHover(null); + } + + /* + * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) + */ + public ITextHover getTextHover(ISourceViewer sourceViewer, + String contentType) { + return getTextHover(sourceViewer, contentType, + ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); + } + + /** + * Returns the SmartyDoc source code scanner for this configuration. + * + * @return the SmartyDoc source code scanner + */ + // protected RuleBasedScanner getSmartyDocScanner() { + // return fJavaTextTools.getSmartyDocScanner(); + // } + /** + * Returns the PHPDoc source code scanner for this configuration. + * + * @return the PHPDoc source code scanner + */ + protected RuleBasedScanner getPHPDocScanner() { + return fJavaDocScanner; // fJavaTextTools.getJavaDocScanner(); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { + return new String[] { IDocument.DEFAULT_CONTENT_TYPE, + PHPPartitionScanner.PHP_SCRIPTING_AREA, + + IPHPPartitions.HTML, IPHPPartitions.HTML_MULTILINE_COMMENT, + IPHPPartitions.PHP_PARTITIONING, + IPHPPartitions.PHP_SINGLELINE_COMMENT, + IPHPPartitions.PHP_MULTILINE_COMMENT, + IPHPPartitions.PHP_PHPDOC_COMMENT, + IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, + IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, + IPHPPartitions.CSS_MULTILINE_COMMENT, + IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, + IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, + + XMLPartitionScanner.XML_PI, XMLPartitionScanner.XML_COMMENT, + XMLPartitionScanner.XML_DECL, XMLPartitionScanner.XML_TAG, + XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, + + XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, + + PHPDocumentPartitioner.PHP_TEMPLATE_DATA, + PHPDocumentPartitioner.PHP_SCRIPT_CODE }; + } + + public String[] getConfiguredHTMLContentTypes() { + return new String[] { XMLPartitionScanner.XML_PI, + XMLPartitionScanner.XML_COMMENT, XMLPartitionScanner.XML_DECL, + XMLPartitionScanner.XML_TAG, XMLPartitionScanner.XML_ATTRIBUTE, + XMLPartitionScanner.XML_CDATA, + + XMLPartitionScanner.DTD_INTERNAL, + XMLPartitionScanner.DTD_INTERNAL_PI, + XMLPartitionScanner.DTD_INTERNAL_COMMENT, + XMLPartitionScanner.DTD_INTERNAL_DECL, }; + } + + public String[] getConfiguredPHPContentTypes() { + return new String[] { IDocument.DEFAULT_CONTENT_TYPE, + IPHPPartitions.PHP_PARTITIONING, + IPHPPartitions.PHP_SINGLELINE_COMMENT, + IPHPPartitions.PHP_MULTILINE_COMMENT, + IPHPPartitions.PHP_PHPDOC_COMMENT, + IPHPPartitions.PHP_STRING_DQ, IPHPPartitions.PHP_STRING_SQ, + IPHPPartitions.PHP_STRING_HEREDOC, IPHPPartitions.CSS, + IPHPPartitions.CSS_MULTILINE_COMMENT, + IPHPPartitions.JAVASCRIPT, IPHPPartitions.JS_MULTILINE_COMMENT, + IPHPPartitions.SMARTY, IPHPPartitions.SMARTY_MULTILINE_COMMENT, }; + } + + /* + * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer) + * @since 3.0 + */ + public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { + if (fDocumentPartitioning != null) + return fDocumentPartitioning; + return super.getConfiguredDocumentPartitioning(sourceViewer); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { + ContentAssistant assistant = new ContentAssistant(); + IContentAssistProcessor processor = new HTMLCompletionProcessor( + getEditor()); + assistant + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + assistant.setContentAssistProcessor(processor, IPHPPartitions.HTML); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.HTML_MULTILINE_COMMENT); + + assistant.setContentAssistProcessor(processor, IPHPPartitions.CSS); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.CSS_MULTILINE_COMMENT); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.JAVASCRIPT); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.JS_MULTILINE_COMMENT); + // TODO define special smarty partition content assist + assistant.setContentAssistProcessor(processor, IPHPPartitions.SMARTY); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.SMARTY_MULTILINE_COMMENT); + + assistant.setContentAssistProcessor(processor, + PHPDocumentPartitioner.PHP_TEMPLATE_DATA); + String[] htmlTypes = getConfiguredHTMLContentTypes(); + for (int i = 0; i < htmlTypes.length; i++) { + assistant.setContentAssistProcessor(processor, htmlTypes[i]); + } + processor = new PHPCompletionProcessor(getEditor()); + + assistant.setContentAssistProcessor(processor, + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_PARTITIONING); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_DQ); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_SQ); + assistant.setContentAssistProcessor(processor, + IPHPPartitions.PHP_STRING_HEREDOC); + + assistant.setContentAssistProcessor(new PHPDocCompletionProcessor( + getEditor()), IPHPPartitions.PHP_PHPDOC_COMMENT); + // assistant.enableAutoActivation(true); + // assistant.setAutoActivationDelay(500); + // assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); + // ContentAssistPreference.configure(assistant, getPreferenceStore()); + // assistant.setContextInformationPopupOrientation( + // ContentAssistant.CONTEXT_INFO_ABOVE); + // assistant.setContextInformationPopupBackground( + // PHPEditorEnvironment.getPHPColorProvider().getColor( + // new RGB(150, 150, 0))); + ContentAssistPreference.configure(assistant, getPreferenceStore()); + assistant + .setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); + assistant + .setInformationControlCreator(getInformationControlCreator(sourceViewer)); + return assistant; + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + // public String getDefaultPrefix(ISourceViewer sourceViewer, String + // contentType) { + // return (PHPPartitionScanner.PHP.equals(contentType) ? "//" : null); + // //$NON-NLS-1$ + // // return (IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) ? "//" : + // null); //$NON-NLS-1$ + // } + /* + * @see SourceViewerConfiguration#getDefaultPrefix(ISourceViewer, String) + * @since 2.0 + */ + public String[] getDefaultPrefixes(ISourceViewer sourceViewer, + String contentType) { + return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public ITextDoubleClickStrategy getDoubleClickStrategy( + ISourceViewer sourceViewer, String contentType) { + return new PHPDoubleClickSelector(); + } + + /* + * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) + */ + public String[] getIndentPrefixes(ISourceViewer sourceViewer, + String contentType) { + Vector vector = new Vector(); + // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces + final IPreferenceStore preferences = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + int tabWidth = preferences.getInt(JavaCore.FORMATTER_TAB_SIZE); + boolean useSpaces = getPreferenceStore().getBoolean(SPACES_FOR_TABS); + for (int i = 0; i <= tabWidth; i++) { + StringBuffer prefix = new StringBuffer(); + if (useSpaces) { + for (int j = 0; j + i < tabWidth; j++) + prefix.append(' '); + if (i != 0) + prefix.append('\t'); + } else { + for (int j = 0; j < i; j++) + prefix.append(' '); + if (i != tabWidth) + prefix.append('\t'); + } + vector.add(prefix.toString()); + } + vector.add(""); //$NON-NLS-1$ + return (String[]) vector.toArray(new String[vector.size()]); + } + + /** + * @return true iff the new setup without text tools is in + * use. + * + * @since 3.0 + */ + // private boolean isNewSetup() { + // return fJavaTextTools == null; + // } + /** + * Creates and returns a preference store which combines the preference + * stores from the text tools and which is read-only. + * + * @return the read-only preference store + * @since 3.0 + */ + // private IPreferenceStore createPreferenceStore() { + // Assert.isTrue(!isNewSetup()); + // IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + // if (fJavaTextTools.getCorePreferenceStore() == null) + // return new ChainedPreferenceStore(new IPreferenceStore[] { + // fJavaTextTools.getPreferenceStore(), generalTextStore }); + // + // return new ChainedPreferenceStore(new IPreferenceStore[] { + // fJavaTextTools.getPreferenceStore(), + // new PreferencesAdapter(fJavaTextTools.getCorePreferenceStore()), + // generalTextStore }); + // } + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public IPresentationReconciler getPresentationReconciler( + ISourceViewer sourceViewer) { + // PHPColorProvider provider = + // PHPEditorEnvironment.getPHPColorProvider(); + // JavaColorManager provider = + // PHPEditorEnvironment.getPHPColorProvider(); + PresentationReconciler phpReconciler = new JavaPresentationReconciler(); + phpReconciler + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + + // DefaultDamagerRepairer dr = new + // DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + // reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.HTML); + // reconciler.setRepairer(dr, IPHPPartitions.HTML); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.CSS); + // reconciler.setRepairer(dr, IPHPPartitions.CSS); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.CSS_MULTILINE_COMMENT); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.JAVASCRIPT); + // reconciler.setRepairer(dr, IPHPPartitions.JAVASCRIPT); + // dr = new DefaultDamagerRepairer(getHTMLScanner()); + // reconciler.setDamager(dr, IPHPPartitions.JS_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.JS_MULTILINE_COMMENT); + // DefaultDamagerRepairer phpDR = new + // DefaultDamagerRepairer(getSmartyScanner()); + // phpReconciler.setDamager(phpDR, IPHPPartitions.SMARTY); + // phpReconciler.setRepairer(phpDR, IPHPPartitions.SMARTY); + // phpDR = new DefaultDamagerRepairer(getSmartyDocScanner()); + // phpReconciler.setDamager(phpDR, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT); + // phpReconciler.setRepairer(phpDR, + // IPHPPartitions.SMARTY_MULTILINE_COMMENT); + // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new + // TextAttribute(fJavaTextTools.getColorManager().getColor( + // PHPColorProvider.MULTI_LINE_COMMENT)))); + // reconciler.setDamager(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); + // reconciler.setRepairer(dr, IPHPPartitions.HTML_MULTILINE_COMMENT); + + DefaultDamagerRepairer phpDR = new DefaultDamagerRepairer( + getCodeScanner()); + phpReconciler.setDamager(phpDR, IDocument.DEFAULT_CONTENT_TYPE); + phpReconciler.setRepairer(phpDR, IDocument.DEFAULT_CONTENT_TYPE); + + phpDR = new DefaultDamagerRepairer(getCodeScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PARTITIONING); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PARTITIONING); + + phpDR = new DefaultDamagerRepairer(getPHPDocScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_PHPDOC_COMMENT); + + phpDR = new DefaultDamagerRepairer(getStringDQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_DQ); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_DQ); + phpDR = new DefaultDamagerRepairer(getStringSQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_SQ); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_SQ); + phpDR = new DefaultDamagerRepairer(getStringDQScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_STRING_HEREDOC); + phpDR = new DefaultDamagerRepairer(getSinglelineCommentScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_SINGLELINE_COMMENT); + phpDR = new DefaultDamagerRepairer(getMultilineCommentScanner()); + phpReconciler.setDamager(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); + phpReconciler.setRepairer(phpDR, IPHPPartitions.PHP_MULTILINE_COMMENT); + + PresentationReconciler reconciler = new PresentationReconciler(); + reconciler + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + // + // JavaTextTools jspTextTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + DefaultDamagerRepairer dr = new DefaultDamagerRepairer( + getPHPDocScanner());// jspTextTools.getJSPTextScanner()); + reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); + reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); + + // dr = new DefaultDamagerRepairer(new SingleTokenScanner(new + // TextAttribute(fJavaTextTools.getColorManager().getColor( + // PHPColorProvider.PHPDOC_TAG))));//jspTextTools.getJSPBracketScanner()); + // reconciler.setDamager(dr, JSPScriptScanner.JSP_BRACKET); + // reconciler.setRepairer(dr, JSPScriptScanner.JSP_BRACKET); + + // xml partitions + configureEmbeddedPresentationReconciler(reconciler, xmlConfiguration + .getPresentationReconciler(sourceViewer), xmlConfiguration + .getConfiguredContentTypes(sourceViewer), + PHPDocumentPartitioner.PHP_TEMPLATE_DATA); + + // java partitions + configureEmbeddedPresentationReconciler(reconciler, phpReconciler, + getConfiguredPHPContentTypes(), + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + + return reconciler; + } + + private void configureEmbeddedPresentationReconciler( + PresentationReconciler reconciler, + IPresentationReconciler embedded, String[] types, String defaultType) { + for (int i = 0; i < types.length; i++) { + String type = types[i]; + + IPresentationDamager damager = embedded.getDamager(type); + IPresentationRepairer repairer = embedded.getRepairer(type); + + if (type == IDocument.DEFAULT_CONTENT_TYPE) { + type = defaultType; + } + + reconciler.setDamager(damager, type); + reconciler.setRepairer(repairer, type); + } + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + public int getTabWidth(ISourceViewer sourceViewer) { + return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH); + } + + /* + * (non-Javadoc) Method declared on SourceViewerConfiguration + */ + // public ITextHover getTextHover(ISourceViewer sourceViewer, String + // contentType) { + // if (fEditor != null) { + // IEditorInput editorInput = fEditor.getEditorInput(); + // if (editorInput instanceof IFileEditorInput) { + // try { + // IFile f = ((IFileEditorInput) editorInput).getFile(); + // return new PHPTextHover(f.getProject()); + // } catch (NullPointerException e) { + // // this exception occurs, if getTextHover is called by preference pages + // ! + // } + // } + // } + // return new PHPTextHover(null); + // } + /* + * @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer) + * @since 2.0 + */ + public IInformationControlCreator getInformationControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { +//incastrix + // return new DefaultInformationControl(parent, SWT.NONE, +// new HTMLTextPresenter(true)); + return new DefaultInformationControl(parent, + new HTMLTextPresenter(true)); + // return new HoverBrowserControl(parent); + } + }; + } + + /* + * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) + * @since 2.0 + */ + public IInformationPresenter getInformationPresenter( + ISourceViewer sourceViewer) { + InformationPresenter presenter = new InformationPresenter( + getInformationPresenterControlCreator(sourceViewer)); + presenter + .setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); + IInformationProvider provider = new JavaInformationProvider(getEditor()); + presenter.setInformationProvider(provider, + IDocument.DEFAULT_CONTENT_TYPE); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PHPDOC_COMMENT); + // presenter.setInformationProvider(provider, + // IPHPPartitions.JAVA_CHARACTER); + presenter.setSizeConstraints(60, 10, true, true); + return presenter; + } + + /* + * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) + * @since 2.0 + */ + // public IInformationPresenter getInformationPresenter(ISourceViewer + // sourceViewer) { + // InformationPresenter presenter= new + // InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); + // IInformationProvider provider= new JavaInformationProvider(getEditor()); + // presenter.setInformationProvider(provider, + // IDocument.DEFAULT_CONTENT_TYPE); + // presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); + // presenter.setSizeConstraints(60, 10, true, true); + // return presenter; + // } + /** + * Returns the information presenter control creator. The creator is a + * factory creating the presenter controls for the given source viewer. This + * implementation always returns a creator for + * DefaultInformationControl instances. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @return an information control creator + * @since 2.1 + */ + private IInformationControlCreator getInformationPresenterControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + int shellStyle = SWT.RESIZE; + int style = SWT.V_SCROLL | SWT.H_SCROLL; + return new DefaultInformationControl(parent, shellStyle, style, + new HTMLTextPresenter(false)); + // return new HoverBrowserControl(parent); + } + }; + } + + /** + * Returns the outline presenter control creator. The creator is a factory + * creating outline presenter controls for the given source viewer. This + * implementation always returns a creator for + * JavaOutlineInformationControl instances. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @return an information control creator + * @since 2.1 + */ + private IInformationControlCreator getOutlinePresenterControlCreator( + ISourceViewer sourceViewer) { + return new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + int shellStyle = SWT.RESIZE; + int treeStyle = SWT.V_SCROLL | SWT.H_SCROLL; + return new JavaOutlineInformationControl(parent, shellStyle, + treeStyle); + } + }; + } + + /** + * Returns the outline presenter which will determine and shown information + * requested for the current cursor position. + * + * @param sourceViewer + * the source viewer to be configured by this configuration + * @param doCodeResolve + * a boolean which specifies whether code resolve should be used + * to compute the Java element + * @return an information presenter + * @since 2.1 + */ + public IInformationPresenter getOutlinePresenter( + ISourceViewer sourceViewer, boolean doCodeResolve) { + InformationPresenter presenter = new InformationPresenter( + getOutlinePresenterControlCreator(sourceViewer)); + presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); + IInformationProvider provider = new JavaElementProvider(getEditor(), + doCodeResolve); + presenter.setInformationProvider(provider, + IDocument.DEFAULT_CONTENT_TYPE); + presenter.setInformationProvider(provider, + PHPDocumentPartitioner.PHP_SCRIPT_CODE); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PARTITIONING); + presenter.setInformationProvider(provider, + IPHPPartitions.PHP_PHPDOC_COMMENT); + presenter.setInformationProvider(provider, + IPHPPartitions.SMARTY_MULTILINE_COMMENT); + presenter.setInformationProvider(provider, IPHPPartitions.HTML); + presenter.setInformationProvider(provider, + IPHPPartitions.HTML_MULTILINE_COMMENT); + presenter.setSizeConstraints(40, 20, true, false); + return presenter; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/PHPStringDQCodeScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/SingleTokenPHPScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingPreferenceBlock.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/IJavaFoldingStructureProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/package.html similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/folding/package.html rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/folding/package.html diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/java/hover/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/package.html similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/text/java/hover/package.html rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/package.html diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewClassWizardPage.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java new file mode 100644 index 0000000..21b28fe --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewContainerWizardPage.java @@ -0,0 +1,475 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui.wizards; + +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IPackageFragmentRoot; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +// incastrix +//import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo; +import net.sourceforge.phpeclipse.ui.StatusInfo; +import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider; +import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.views.contentoutline.ContentOutline; + +/** + * Wizard page that acts as a base class for wizard pages that create new Java + * elements. The class provides a input field for source folders (called + * container in this class) and API to validate the enter source folder name. + * + * @since 2.0 + */ +public abstract class NewContainerWizardPage extends NewElementWizardPage { + + /** Id of the container field */ + protected static final String CONTAINER = "NewContainerWizardPage.container"; //$NON-NLS-1$ + + /** The status of the last validation. */ + protected IStatus fContainerStatus; + + private StringButtonDialogField fContainerDialogField; + + /* + * package fragment root corresponding to the input type (can be null) + */ + private IPackageFragmentRoot fCurrRoot; + + private IWorkspaceRoot fWorkspaceRoot; + + /** + * Create a new NewContainerWizardPage + * + * @param name + * the wizard page's name + */ + public NewContainerWizardPage(String name) { + super(name); + fWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + ContainerFieldAdapter adapter = new ContainerFieldAdapter(); + + fContainerDialogField = new StringButtonDialogField(adapter); + fContainerDialogField.setDialogFieldListener(adapter); + fContainerDialogField.setLabelText(NewWizardMessages + .getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ + fContainerDialogField.setButtonLabel(NewWizardMessages + .getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ + + fContainerStatus = new StatusInfo(); + fCurrRoot = null; + } + + /** + * Initializes the source folder field with a valid package fragement root. + * The package fragement root is computed from the given Java element. + * + * @param elem + * the Java element used to compute the initial package fragment + * root used as the source folder + */ +// protected void initContainerPage(IJavaElement elem) { +// //IPackageFragmentRoot initRoot = null; +// // if (elem != null) { +// // initRoot= JavaModelUtil.getPackageFragmentRoot(elem); +// // if (initRoot == null || initRoot.isArchive()) { +// // IJavaProject jproject= elem.getJavaProject(); +// // if (jproject != null) { +// // try { +// // initRoot= null; +// // if (jproject.exists()) { +// // IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); +// // for (int i= 0; i < roots.length; i++) { +// // if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { +// // initRoot= roots[i]; +// // break; +// // } +// // } +// // } +// // } catch (JavaModelException e) { +// // PHPeclipsePlugin.log(e); +// // } +// // if (initRoot == null) { +// // initRoot= jproject.getPackageFragmentRoot(jproject.getResource()); +// // } +// // } +// // } +// // } +// // setPackageFragmentRoot(initRoot, true); +// } + + /** + * Utility method to inspect a selection to find a Java element. + * + * @param selection + * the selection to be inspected + * @return a Java element to be used as the initial selection, or + * null, if no Java element exists in the given + * selection + */ + protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { + IJavaElement jelem = null; + if (selection != null && !selection.isEmpty()) { + Object selectedElement = selection.getFirstElement(); + if (selectedElement instanceof IAdaptable) { + IAdaptable adaptable = (IAdaptable) selectedElement; + + jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class); + if (jelem == null) { + IResource resource = (IResource) adaptable + .getAdapter(IResource.class); + if (resource != null + && resource.getType() != IResource.ROOT) { + while (jelem == null + && resource.getType() != IResource.PROJECT) { + resource = resource.getParent(); + jelem = (IJavaElement) resource + .getAdapter(IJavaElement.class); + } + if (jelem == null) { + jelem = JavaCore.create(resource); // java project + } + } + } + } + } + if (jelem == null) { + IWorkbenchPart part = PHPeclipsePlugin.getActivePage() + .getActivePart(); + if (part instanceof ContentOutline) { + part = PHPeclipsePlugin.getActivePage().getActiveEditor(); + } + + if (part instanceof IViewPartInputProvider) { + Object elem = ((IViewPartInputProvider) part) + .getViewPartInput(); + if (elem instanceof IJavaElement) { + jelem = (IJavaElement) elem; + } + } + } + + if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) { + try { + IJavaProject[] projects = JavaCore.create(getWorkspaceRoot()) + .getJavaProjects(); + if (projects.length == 1) { + jelem = projects[0]; + } + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); + } + } + return jelem; + } + + /** + * Returns the recommended maximum width for text fields (in pixels). This + * method requires that createContent has been called before this method is + * call. Subclasses may override to change the maximum width for text + * fields. + * + * @return the recommended maximum width for text fields. + */ + protected int getMaxFieldWidth() { + return convertWidthInCharsToPixels(40); + } + + /** + * Creates the necessary controls (label, text field and browse button) to + * edit the source folder location. The method expects that the parent + * composite uses a GridLayout as its layout manager and that + * the grid layout has at least 3 columns. + * + * @param parent + * the parent composite + * @param nColumns + * the number of columns to span. This number must be greater or + * equal three + */ + protected void createContainerControls(Composite parent, int nColumns) { + fContainerDialogField.doFillIntoGrid(parent, nColumns); + LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), + getMaxFieldWidth()); + } + + /** + * Sets the focus to the source folder's text field. + */ +// protected void setFocusOnContainer() { +// fContainerDialogField.setFocus(); +// } + + // -------- ContainerFieldAdapter -------- + + private class ContainerFieldAdapter implements IStringButtonAdapter, + IDialogFieldListener { + + // -------- IStringButtonAdapter + public void changeControlPressed(DialogField field) { + //containerChangeControlPressed(field); + } + + // -------- IDialogFieldListener + public void dialogFieldChanged(DialogField field) { + containerDialogFieldChanged(field); + } + } + +// private void containerChangeControlPressed(DialogField field) { +// // take the current jproject as init element of the dialog +// // IPackageFragmentRoot root= getPackageFragmentRoot(); +// // root= chooseSourceContainer(root); +// // if (root != null) { +// // setPackageFragmentRoot(root, true); +// // } +// } + + private void containerDialogFieldChanged(DialogField field) { + if (field == fContainerDialogField) { + fContainerStatus = containerChanged(); + } + // tell all others + //handleFieldChanged(CONTAINER); + } + + // ----------- validation ---------- + + /** + * This method is a hook which gets called after the source folder's text + * input field has changed. This default implementation updates the model + * and returns an error status. The underlying model is only valid if the + * returned status is OK. + * + * @return the model's error status + */ + protected IStatus containerChanged() { + StatusInfo status = new StatusInfo(); + + fCurrRoot = null; + String str = getPackageFragmentRootText(); + if (str.length() == 0) { + status + .setError(NewWizardMessages + .getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ + return status; + } + IPath path = new Path(str); + IResource res = fWorkspaceRoot.findMember(path); + if (res != null) { + int resType = res.getType(); + if (resType == IResource.PROJECT || resType == IResource.FOLDER) { + IProject proj = res.getProject(); + if (!proj.isOpen()) { + status + .setError(NewWizardMessages + .getFormattedString( + "NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ + return status; + } + //IJavaProject jproject = JavaCore.create(proj); + // fCurrRoot= jproject.getPackageFragmentRoot(res); + // if (res.exists()) { + // try { + // if (!proj.hasNature(JavaCore.NATURE_ID)) { + // if (resType == IResource.PROJECT) { + // status.setError(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); + // //$NON-NLS-1$ + // } else { + // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); + // //$NON-NLS-1$ + // } + // return status; + // } + // } catch (CoreException e) { + // status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); + // //$NON-NLS-1$ + // } + // if (!jproject.isOnClasspath(fCurrRoot)) { + // status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", + // str)); //$NON-NLS-1$ + // } + // if (fCurrRoot.isArchive()) { + // status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", + // str)); //$NON-NLS-1$ + // return status; + // } + // } + return status; + } else { + status.setError(NewWizardMessages.getFormattedString( + "NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ + return status; + } + } else { + status.setError(NewWizardMessages.getFormattedString( + "NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ + return status; + } + } + + // -------- update message ---------------- + + /** + * Hook method that gets called when a field on this page has changed. For + * this page the method gets called when the source folder field changes. + *

+ * Every sub type is responsible to call this method when a field on its + * page has changed. Subtypes override (extend) the method to add + * verification when a own field has a dependency to an other field. For + * example the class name input must be verified again when the package + * field changes (check for duplicated class names). + * + * @param fieldName + * The name of the field that has changed (field id). For the + * source folder the field id is CONTAINER + */ +// protected void handleFieldChanged(String fieldName) { +// } + + // ---- get ---------------- + + /** + * Returns the workspace root. + * + * @return the workspace root + */ + protected IWorkspaceRoot getWorkspaceRoot() { + return fWorkspaceRoot; + } + + /** + * Returns the IPackageFragmentRoot that corresponds to the + * current value of the source folder field. + * + * @return the IPackageFragmentRoot or null if the current + * source folder value is not a valid package fragment root + * + */ + public IPackageFragmentRoot getPackageFragmentRoot() { + return fCurrRoot; + } + + /** + * Returns the current text of source folder text field. + * + * @return the text of the source folder text field + */ + public String getPackageFragmentRootText() { + return fContainerDialogField.getText(); + } + + /** + * Sets the current source folder (model and text field) to the given + * package fragment root. + * + * @param canBeModified + * if false the source folder field can not be + * changed by the user. If true the field is + * editable + */ + // public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean + // canBeModified) { + // fCurrRoot= root; + // String str= (root == null) ? "" : + // root.getPath().makeRelative().toString(); //$NON-NLS-1$ + // fContainerDialogField.setText(str); + // fContainerDialogField.setEnabled(canBeModified); + // } + // ------------- choose source container dialog + // private IPackageFragmentRoot chooseSourceContainer(IJavaElement + // initElement) { + // Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, + // IJavaProject.class }; + // TypedElementSelectionValidator validator= new + // TypedElementSelectionValidator(acceptedClasses, false) { + // public boolean isSelectedValid(Object element) { + // try { + // if (element instanceof IJavaProject) { + // IJavaProject jproject= (IJavaProject)element; + // IPath path= jproject.getProject().getFullPath(); + // return (jproject.findPackageFragmentRoot(path) != null); + // } else if (element instanceof IPackageFragmentRoot) { + // return (((IPackageFragmentRoot)element).getKind() == + // IPackageFragmentRoot.K_SOURCE); + // } + // return true; + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation + // } + // return false; + // } + // }; + // + // acceptedClasses= new Class[] { IJavaModel.class, + // IPackageFragmentRoot.class, IJavaProject.class }; + // ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { + // public boolean select(Viewer viewer, Object parent, Object element) { + // if (element instanceof IPackageFragmentRoot) { + // try { + // return (((IPackageFragmentRoot)element).getKind() == + // IPackageFragmentRoot.K_SOURCE); + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e.getStatus()); // just log, no ui in validation + // return false; + // } + // } + // return super.select(viewer, parent, element); + // } + // }; + // + // StandardJavaElementContentProvider provider= new + // StandardJavaElementContentProvider(); + // ILabelProvider labelProvider= new + // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); + // ElementTreeSelectionDialog dialog= new + // ElementTreeSelectionDialog(getShell(), labelProvider, provider); + // dialog.setValidator(validator); + // dialog.setSorter(new JavaElementSorter()); + // dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); + // //$NON-NLS-1$ + // dialog.addFilter(filter); + // dialog.setInput(JavaCore.create(fWorkspaceRoot)); + // dialog.setInitialSelection(initElement); + // + // if (dialog.open() == ElementTreeSelectionDialog.OK) { + // Object element= dialog.getFirstResult(); + // if (element instanceof IJavaProject) { + // IJavaProject jproject= (IJavaProject)element; + // return jproject.getPackageFragmentRoot(jproject.getProject()); + // } else if (element instanceof IPackageFragmentRoot) { + // return (IPackageFragmentRoot)element; + // } + // return null; + // } + // return null; + // } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewElementWizardPage.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java new file mode 100644 index 0000000..45b6763 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java @@ -0,0 +1,1958 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui.wizards; + +import java.util.ArrayList; +import java.util.List; + +import net.sourceforge.phpdt.core.Flags; +import net.sourceforge.phpdt.core.IBuffer; +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IPackageFragment; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.core.compiler.IScanner; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +//incastrix +//import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo; +import net.sourceforge.phpeclipse.ui.StatusInfo; +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +//import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +//import net.sourceforge.phpdt.internal.corext.template.php.Templates; +//import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.util.SWTUtil; +import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IListAdapter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.Separator; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringDialogField; +//import net.sourceforge.phpdt.ui.CodeGeneration; +//import net.sourceforge.phpdt.ui.PreferenceConstants; +//import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.SubProgressMonitor; +//import org.eclipse.jface.preference.IPreferenceStore; +//import org.eclipse.jface.text.BadLocationException; +//import org.eclipse.jface.text.templates.Template; +//import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.viewers.LabelProvider; +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; + +/** + * The class NewTypeWizardPage contains controls and validation + * routines for a 'New Type WizardPage'. Implementors decide which components to + * add and to enable. Implementors can also customize the validation code. + * NewTypeWizardPage is intended to serve as base class of all + * wizards that create types like applets, servlets, classes, interfaces, etc. + *

+ * See NewClassWizardPage or NewInterfaceWizardPage + * for an example usage of NewTypeWizardPage. + *

+ * + * @see net.sourceforge.phpdt.ui.wizards.NewClassWizardPage + * @see net.sourceforge.phpdt.ui.wizards.NewInterfaceWizardPage + * + * @since 2.0 + */ +public abstract class NewTypeWizardPage extends NewContainerWizardPage { + + /** + * Class used in stub creation routines to add needed imports to a + * compilation unit. + */ + // public static class ImportsManager { + // + // private IImportsStructure fImportsStructure; + // + // /* package */ ImportsManager(IImportsStructure structure) { + // fImportsStructure= structure; + // } + // + // /* package */ IImportsStructure getImportsStructure() { + // return fImportsStructure; + // } + // + // /** + // * Adds a new import declaration that is sorted in the existing imports. + // * If an import already exists or the import would conflict with another + // import + // * of an other type with the same simple name the import is not added. + // * + // * @param qualifiedTypeName The fully qualified name of the type to import + // * (dot separated) + // * @return Returns the simple type name that can be used in the code or + // the + // * fully qualified type name if an import conflict prevented the import + // */ + // public String addImport(String qualifiedTypeName) { + // return fImportsStructure.addImport(qualifiedTypeName); + // } + // } + /** + * Public access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_PUBLIC = Flags.AccPublic; + + /** + * Private access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_PRIVATE = Flags.AccPrivate; + + /** + * Protected access flag. See The Java Virtual Machine Specification for + * more details. + */ + public int F_PROTECTED = Flags.AccProtected; + + /** + * Static access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_STATIC = Flags.AccStatic; + + /** + * Final access flag. See The Java Virtual Machine Specification for more + * details. + */ + public int F_FINAL = Flags.AccFinal; + + /** + * Abstract property flag. See The Java Virtual Machine Specification for + * more details. + */ + // public int F_ABSTRACT = Flags.AccAbstract; + private final static String PAGE_NAME = "NewTypeWizardPage"; //$NON-NLS-1$ + + /** Field ID of the package input field */ + protected final static String PACKAGE = PAGE_NAME + ".package"; //$NON-NLS-1$ + + /** Field ID of the eclosing type input field */ + protected final static String ENCLOSING = PAGE_NAME + ".enclosing"; //$NON-NLS-1$ + + /** Field ID of the enclosing type checkbox */ + protected final static String ENCLOSINGSELECTION = ENCLOSING + ".selection"; //$NON-NLS-1$ + + /** Field ID of the type name input field */ + protected final static String TYPENAME = PAGE_NAME + ".typename"; //$NON-NLS-1$ + + /** Field ID of the super type input field */ + protected final static String SUPER = PAGE_NAME + ".superclass"; //$NON-NLS-1$ + + /** Field ID of the super interfaces input field */ + protected final static String INTERFACES = PAGE_NAME + ".interfaces"; //$NON-NLS-1$ + + /** Field ID of the modifier checkboxes */ + protected final static String MODIFIERS = PAGE_NAME + ".modifiers"; //$NON-NLS-1$ + + /** Field ID of the method stubs checkboxes */ + protected final static String METHODS = PAGE_NAME + ".methods"; //$NON-NLS-1$ + + private class InterfacesListLabelProvider extends LabelProvider { + + private Image fInterfaceImage; + + public InterfacesListLabelProvider() { + super(); + fInterfaceImage = PHPUiImages.get(PHPUiImages.IMG_OBJS_INTERFACE); + } + + public Image getImage(Object element) { + return fInterfaceImage; + } + } + + private StringButtonStatusDialogField fPackageDialogField; + + private SelectionButtonDialogField fEnclosingTypeSelection; + + private StringButtonDialogField fEnclosingTypeDialogField; + + private boolean fCanModifyPackage; + + private boolean fCanModifyEnclosingType; + + private IPackageFragment fCurrPackage; + + // private IType fCurrEnclosingType; + private StringDialogField fTypeNameDialogField; + + private StringButtonDialogField fSuperClassDialogField; + + private ListDialogField fSuperInterfacesDialogField; + + // private IType fSuperClass; + + private SelectionButtonDialogFieldGroup fAccMdfButtons; + + private SelectionButtonDialogFieldGroup fOtherMdfButtons; + + private IType fCreatedType; + + protected IStatus fEnclosingTypeStatus; + + protected IStatus fPackageStatus; + + protected IStatus fTypeNameStatus; + + // protected IStatus fSuperClassStatus; + protected IStatus fModifierStatus; + + // protected IStatus fSuperInterfacesStatus; + + private boolean fIsClass; + + private int fStaticMdfIndex; + + private final int PUBLIC_INDEX = 0, DEFAULT_INDEX = 1, PRIVATE_INDEX = 2, + PROTECTED_INDEX = 3; + + private final int ABSTRACT_INDEX = 0, FINAL_INDEX = 1; + + /** + * Creates a new NewTypeWizardPage + * + * @param isClass + * true if a new class is to be created; otherwise + * an interface is to be created + * @param pageName + * the wizard page's name + */ + public NewTypeWizardPage(boolean isClass, String pageName) { + super(pageName); + fCreatedType = null; + + fIsClass = isClass; + + TypeFieldsAdapter adapter = new TypeFieldsAdapter(); + + fPackageDialogField = new StringButtonStatusDialogField(adapter); + fPackageDialogField.setDialogFieldListener(adapter); + fPackageDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ + fPackageDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ + fPackageDialogField.setStatusWidthHint(NewWizardMessages + .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ + + fEnclosingTypeSelection = new SelectionButtonDialogField(SWT.CHECK); + fEnclosingTypeSelection.setDialogFieldListener(adapter); + fEnclosingTypeSelection.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ + + fEnclosingTypeDialogField = new StringButtonDialogField(adapter); + fEnclosingTypeDialogField.setDialogFieldListener(adapter); + fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ + + fTypeNameDialogField = new StringDialogField(); + fTypeNameDialogField.setDialogFieldListener(adapter); + fTypeNameDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ + + fSuperClassDialogField = new StringButtonDialogField(adapter); + fSuperClassDialogField.setDialogFieldListener(adapter); + fSuperClassDialogField.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ + fSuperClassDialogField.setButtonLabel(NewWizardMessages + .getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ + + String[] addButtons = new String[] { + /* 0 */ + NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ + /* 1 */ + null, + /* 2 */ + NewWizardMessages + .getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ + }; + fSuperInterfacesDialogField = new ListDialogField(adapter, addButtons, + new InterfacesListLabelProvider()); + fSuperInterfacesDialogField.setDialogFieldListener(adapter); + String interfaceLabel = fIsClass ? NewWizardMessages + .getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ + fSuperInterfacesDialogField.setLabelText(interfaceLabel); + fSuperInterfacesDialogField.setRemoveButtonIndex(2); + + String[] buttonNames1 = new String[] { + /* 0 == PUBLIC_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ + /* 1 == DEFAULT_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ + /* 2 == PRIVATE_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ + /* 3 == PROTECTED_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ + }; + fAccMdfButtons = new SelectionButtonDialogFieldGroup(SWT.RADIO, + buttonNames1, 4); + fAccMdfButtons.setDialogFieldListener(adapter); + fAccMdfButtons.setLabelText(NewWizardMessages + .getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ + fAccMdfButtons.setSelection(0, true); + + String[] buttonNames2; + if (fIsClass) { + buttonNames2 = new String[] { + /* 0 == ABSTRACT_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ + /* 1 == FINAL_INDEX */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ + /* 2 */ + NewWizardMessages + .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ + }; + fStaticMdfIndex = 2; // index of the static checkbox is 2 + } else { + buttonNames2 = new String[] { NewWizardMessages + .getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ + }; + fStaticMdfIndex = 0; // index of the static checkbox is 0 + } + + fOtherMdfButtons = new SelectionButtonDialogFieldGroup(SWT.CHECK, + buttonNames2, 4); + fOtherMdfButtons.setDialogFieldListener(adapter); + + fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); + fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); + fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); + + fPackageStatus = new StatusInfo(); + fEnclosingTypeStatus = new StatusInfo(); + + fCanModifyPackage = true; + fCanModifyEnclosingType = true; + updateEnableState(); + + fTypeNameStatus = new StatusInfo(); + // fSuperClassStatus= new StatusInfo(); + // fSuperInterfacesStatus= new StatusInfo(); + fModifierStatus = new StatusInfo(); + } + + /** + * Initializes all fields provided by the page with a given selection. + * + * @param elem + * the selection used to intialize this page or + * null + * if no selection was available + */ + protected void initTypePage(IJavaElement elem) { + String initSuperclass = "java.lang.Object"; //$NON-NLS-1$ + ArrayList initSuperinterfaces = new ArrayList(5); + + IPackageFragment pack = null; + IType enclosingType = null; + + if (elem != null) { + // evaluate the enclosing type + pack = (IPackageFragment) elem + .getAncestor(IJavaElement.PACKAGE_FRAGMENT); + IType typeInCU = (IType) elem.getAncestor(IJavaElement.TYPE); + if (typeInCU != null) { + if (typeInCU.getCompilationUnit() != null) { + enclosingType = typeInCU; + } + } else { + ICompilationUnit cu = (ICompilationUnit) elem + .getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null) { + // enclosingType= cu.findPrimaryType(); + } + } + + // try { + // IType type= null; + // if (elem.getElementType() == IJavaElement.TYPE) { + // type= (IType)elem; + // if (type.exists()) { + // String superName= JavaModelUtil.getFullyQualifiedName(type); + // if (type.isInterface()) { + // initSuperinterfaces.add(superName); + // } else { + // initSuperclass= superName; + // } + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // ignore this exception now + // } + } + + setPackageFragment(pack, true); + // setEnclosingType(enclosingType, true); + setEnclosingTypeSelection(false, true); + + setTypeName("", true); //$NON-NLS-1$ + setSuperClass(initSuperclass, true); + setSuperInterfaces(initSuperinterfaces, true); + } + + // -------- UI Creation --------- + + /** + * Creates a separator line. Expects a GridLayout with at + * least 1 column. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSeparator(Composite composite, int nColumns) { + (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid( + composite, nColumns, convertHeightInCharsToPixels(1)); + } + + /** + * Creates the controls for the package name field. Expects a + * GridLayout with at least 4 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createPackageControls(Composite composite, int nColumns) { + fPackageDialogField.doFillIntoGrid(composite, nColumns); + LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), + getMaxFieldWidth()); + LayoutUtil.setHorizontalGrabbing(fPackageDialogField + .getTextControl(null)); + } + + /** + * Creates the controls for the enclosing type name field. Expects a + * GridLayout with at least 4 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createEnclosingTypeControls(Composite composite, int nColumns) { + // #6891 + Composite tabGroup = new Composite(composite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginWidth = 0; + layout.marginHeight = 0; + tabGroup.setLayout(layout); + + fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); + + Control c = fEnclosingTypeDialogField.getTextControl(composite); + GridData gd = new GridData(GridData.FILL_HORIZONTAL); + gd.widthHint = getMaxFieldWidth(); + gd.horizontalSpan = 2; + c.setLayoutData(gd); + + Button button = fEnclosingTypeDialogField.getChangeControl(composite); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.heightHint = SWTUtil.getButtonHeightHint(button); + gd.widthHint = SWTUtil.getButtonWidthHint(button); + button.setLayoutData(gd); + } + + /** + * Creates the controls for the type name field. Expects a + * GridLayout with at least 2 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createTypeNameControls(Composite composite, int nColumns) { + fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); + DialogField.createEmptySpace(composite); + + LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), + getMaxFieldWidth()); + } + + /** + * Creates the controls for the modifiers radio/ceckbox buttons. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createModifierControls(Composite composite, int nColumns) { + LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), + 1); + + Control control = fAccMdfButtons.getSelectionButtonsGroup(composite); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = nColumns - 2; + control.setLayoutData(gd); + + DialogField.createEmptySpace(composite); + + DialogField.createEmptySpace(composite); + + control = fOtherMdfButtons.getSelectionButtonsGroup(composite); + gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + gd.horizontalSpan = nColumns - 2; + control.setLayoutData(gd); + + DialogField.createEmptySpace(composite); + } + + /** + * Creates the controls for the superclass name field. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSuperClassControls(Composite composite, int nColumns) { + fSuperClassDialogField.doFillIntoGrid(composite, nColumns); + LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), + getMaxFieldWidth()); + } + + /** + * Creates the controls for the superclass name field. Expects a + * GridLayout with at least 3 columns. + * + * @param composite + * the parent composite + * @param nColumns + * number of columns to span + */ + protected void createSuperInterfacesControls(Composite composite, + int nColumns) { + fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); + GridData gd = (GridData) fSuperInterfacesDialogField.getListControl( + null).getLayoutData(); + if (fIsClass) { + gd.heightHint = convertHeightInCharsToPixels(3); + } else { + gd.heightHint = convertHeightInCharsToPixels(6); + } + gd.grabExcessVerticalSpace = false; + gd.widthHint = getMaxFieldWidth(); + } + + /** + * Sets the focus on the type name input field. + */ + protected void setFocus() { + fTypeNameDialogField.setFocus(); + } + + // -------- TypeFieldsAdapter -------- + + private class TypeFieldsAdapter implements IStringButtonAdapter, + IDialogFieldListener, IListAdapter { + + // -------- IStringButtonAdapter + public void changeControlPressed(DialogField field) { + // typePageChangeControlPressed(field); + } + + // -------- IListAdapter + public void customButtonPressed(ListDialogField field, int index) { + // typePageCustomButtonPressed(field, index); + } + + public void selectionChanged(ListDialogField field) { + } + + // -------- IDialogFieldListener + public void dialogFieldChanged(DialogField field) { + typePageDialogFieldChanged(field); + } + + public void doubleClicked(ListDialogField field) { + } + } + + // private void typePageChangeControlPressed(DialogField field) { + // if (field == fPackageDialogField) { + // IPackageFragment pack= choosePackage(); + // if (pack != null) { + // fPackageDialogField.setText(pack.getElementName()); + // } + // } else if (field == fEnclosingTypeDialogField) { + // IType type= chooseEnclosingType(); + // if (type != null) { + // fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); + // } + // } else if (field == fSuperClassDialogField) { + // IType type= chooseSuperType(); + // if (type != null) { + // fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); + // } + // } + // } + + // private void typePageCustomButtonPressed(DialogField field, int index) { + // if (field == fSuperInterfacesDialogField) { + // chooseSuperInterfaces(); + // } + // } + + /* + * A field on the type has changed. The fields' status and all dependend + * status are updated. + */ + private void typePageDialogFieldChanged(DialogField field) { + String fieldName = null; + if (field == fPackageDialogField) { + fPackageStatus = packageChanged(); + updatePackageStatusLabel(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = PACKAGE; + } else if (field == fEnclosingTypeDialogField) { + // fEnclosingTypeStatus= enclosingTypeChanged(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = ENCLOSING; + } else if (field == fEnclosingTypeSelection) { + updateEnableState(); + boolean isEnclosedType = isEnclosingTypeSelected(); + if (!isEnclosedType) { + if (fAccMdfButtons.isSelected(PRIVATE_INDEX) + || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { + fAccMdfButtons.setSelection(PRIVATE_INDEX, false); + fAccMdfButtons.setSelection(PROTECTED_INDEX, false); + fAccMdfButtons.setSelection(PUBLIC_INDEX, true); + } + if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { + fOtherMdfButtons.setSelection(fStaticMdfIndex, false); + } + } + fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType + && fIsClass); + fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, + isEnclosedType && fIsClass); + fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, + isEnclosedType); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + fieldName = ENCLOSINGSELECTION; + } else if (field == fTypeNameDialogField) { + fTypeNameStatus = typeNameChanged(); + fieldName = TYPENAME; + } else if (field == fSuperClassDialogField) { + // fSuperClassStatus= superClassChanged(); + fieldName = SUPER; + } else if (field == fSuperInterfacesDialogField) { + // fSuperInterfacesStatus= superInterfacesChanged(); + fieldName = INTERFACES; + } else if (field == fOtherMdfButtons) { + fModifierStatus = modifiersChanged(); + fieldName = MODIFIERS; + } else { + fieldName = METHODS; + } + // tell all others + handleFieldChanged(fieldName); + } + + // -------- update message ---------------- + + /* + * @see net.sourceforge.phpdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) + */ + protected void handleFieldChanged(String fieldName) { + //super.handleFieldChanged(fieldName); + if (fieldName == CONTAINER) { + fPackageStatus = packageChanged(); + // fEnclosingTypeStatus= enclosingTypeChanged(); + fTypeNameStatus = typeNameChanged(); + // fSuperClassStatus= superClassChanged(); + // fSuperInterfacesStatus= superInterfacesChanged(); + } + } + + // ---- set / get ---------------- + + /** + * Returns the text of the package input field. + * + * @return the text of the package input field + */ + public String getPackageText() { + return fPackageDialogField.getText(); + } + + /** + * Returns the text of the enclosing type input field. + * + * @return the text of the enclosing type input field + */ +// public String getEnclosingTypeText() { +// return fEnclosingTypeDialogField.getText(); +// } + + /** + * Returns the package fragment corresponding to the current input. + * + * @return a package fragement or null if the input could not + * be resolved. + */ + public IPackageFragment getPackageFragment() { + if (!isEnclosingTypeSelected()) { + return fCurrPackage; + } else { + // if (fCurrEnclosingType != null) { + // return fCurrEnclosingType.getPackageFragment(); + // } + } + return null; + } + + /** + * Sets the package fragment to the given value. The method updates the + * model and the text of the control. + * + * @param pack + * the package fragement to be set + * @param canBeModified + * if true the package fragment is editable; + * otherwise it is read-only. + */ + public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { + fCurrPackage = pack; + fCanModifyPackage = canBeModified; + String str = (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ + fPackageDialogField.setText(str); + updateEnableState(); + } + + /** + * Returns the enclosing type corresponding to the current input. + * + * @return the enclosing type or null if the enclosing type + * is not selected or the input could not be resolved + */ + public IType getEnclosingType() { + // if (isEnclosingTypeSelected()) { + // return fCurrEnclosingType; + // } + return null; + } + + /** + * Sets the enclosing type. The method updates the underlying model and the + * text of the control. + * + * @param type + * the enclosing type + * @param canBeModified + * if true the enclosing type field is editable; + * otherwise it is read-only. + */ + // public void setEnclosingType(IType type, boolean canBeModified) { + // fCurrEnclosingType= type; + // fCanModifyEnclosingType= canBeModified; + // String str= (type == null) ? "" : + // JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ + // fEnclosingTypeDialogField.setText(str); + // updateEnableState(); + // } + /** + * Returns the selection state of the enclosing type checkbox. + * + * @return the seleciton state of the enclosing type checkbox + */ + public boolean isEnclosingTypeSelected() { + return fEnclosingTypeSelection.isSelected(); + } + + /** + * Sets the enclosing type checkbox's selection state. + * + * @param isSelected + * the checkbox's selection state + * @param canBeModified + * if true the enclosing type checkbox is + * modifiable; otherwise it is read-only. + */ + public void setEnclosingTypeSelection(boolean isSelected, + boolean canBeModified) { + fEnclosingTypeSelection.setSelection(isSelected); + fEnclosingTypeSelection.setEnabled(canBeModified); + updateEnableState(); + } + + /** + * Returns the type name entered into the type input field. + * + * @return the type name + */ + public String getTypeName() { + return fTypeNameDialogField.getText(); + } + + /** + * Sets the type name input field's text to the given value. Method doesn't + * update the model. + * + * @param name + * the new type name + * @param canBeModified + * if true the enclosing type name field is + * editable; otherwise it is read-only. + */ + public void setTypeName(String name, boolean canBeModified) { + fTypeNameDialogField.setText(name); + fTypeNameDialogField.setEnabled(canBeModified); + } + + /** + * Returns the selected modifiers. + * + * @return the selected modifiers + * @see Flags + */ +// public int getModifiers() { +// int mdf = 0; +// if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { +// mdf += F_PUBLIC; +// } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { +// mdf += F_PRIVATE; +// } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { +// mdf += F_PROTECTED; +// } +// // if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex +// // != 0)) { +// // mdf+= F_ABSTRACT; +// // } +// if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { +// mdf += F_FINAL; +// } +// if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { +// mdf += F_STATIC; +// } +// return mdf; +// } + + /** + * Sets the modifiers. + * + * @param modifiers + * F_PUBLIC, F_PRIVATE, + * F_PROTECTED, F_ABSTRACT, F_FINAL + * or F_STATIC or, a valid combination. + * @param canBeModified + * if true the modifier fields are editable; + * otherwise they are read-only + * @see Flags + */ +// public void setModifiers(int modifiers, boolean canBeModified) { +// if (Flags.isPublic(modifiers)) { +// fAccMdfButtons.setSelection(PUBLIC_INDEX, true); +// } else if (Flags.isPrivate(modifiers)) { +// fAccMdfButtons.setSelection(PRIVATE_INDEX, true); +// } else if (Flags.isProtected(modifiers)) { +// fAccMdfButtons.setSelection(PROTECTED_INDEX, true); +// } else { +// fAccMdfButtons.setSelection(DEFAULT_INDEX, true); +// } +// // if (Flags.isAbstract(modifiers)) { +// // fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); +// // } +// if (Flags.isFinal(modifiers)) { +// fOtherMdfButtons.setSelection(FINAL_INDEX, true); +// } +// if (Flags.isStatic(modifiers)) { +// fOtherMdfButtons.setSelection(fStaticMdfIndex, true); +// } +// +// fAccMdfButtons.setEnabled(canBeModified); +// fOtherMdfButtons.setEnabled(canBeModified); +// } + + /** + * Returns the content of the superclass input field. + * + * @return the superclass name + */ +// public String getSuperClass() { +// return fSuperClassDialogField.getText(); +// } + + /** + * Sets the super class name. + * + * @param name + * the new superclass name + * @param canBeModified + * if true the superclass name field is editable; + * otherwise it is read-only. + */ + public void setSuperClass(String name, boolean canBeModified) { + fSuperClassDialogField.setText(name); + fSuperClassDialogField.setEnabled(canBeModified); + } + + /** + * Returns the chosen super interfaces. + * + * @return a list of chosen super interfaces. The list's elements are of + * type String + */ +// public List getSuperInterfaces() { +// return fSuperInterfacesDialogField.getElements(); +// } + + /** + * Sets the super interfaces. + * + * @param interfacesNames + * a list of super interface. The method requires that the list's + * elements are of type String + * @param canBeModified + * if true the super interface field is editable; + * otherwise it is read-only. + */ + public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { + fSuperInterfacesDialogField.setElements(interfacesNames); + fSuperInterfacesDialogField.setEnabled(canBeModified); + } + + // ----------- validation ---------- + + /** + * A hook method that gets called when the package field has changed. The + * method validates the package name and returns the status of the + * validation. The validation also updates the package fragment model. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + protected IStatus packageChanged() { + StatusInfo status = new StatusInfo(); + fPackageDialogField.enableButton(getPackageFragmentRoot() != null); + + // String packName= getPackageText(); + // if (packName.length() > 0) { + // IStatus val= JavaConventions.validatePackageName(packName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", + // val.getMessage())); //$NON-NLS-1$ + // return status; + // } else if (val.getSeverity() == IStatus.WARNING) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", + // val.getMessage())); //$NON-NLS-1$ + // // continue + // } + // } + + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root != null) { + // if (root.getJavaProject().exists() && packName.length() > 0) { + // try { + // IPath rootPath= root.getPath(); + // IPath outputPath= root.getJavaProject().getOutputLocation(); + // if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) + // { + // // if the bin folder is inside of our root, dont allow to name a + // package + // // like the bin folder + // IPath packagePath= rootPath.append(packName.replace('.', '/')); + // if (outputPath.isPrefixOf(packagePath)) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); + // //$NON-NLS-1$ + // return status; + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // let pass + // } + // } + // + // fCurrPackage= root.getPackageFragment(packName); + // } else { + // status.setError(""); //$NON-NLS-1$ + // } + return status; + } + + /* + * Updates the 'default' label next to the package field. + */ + private void updatePackageStatusLabel() { + String packName = getPackageText(); + + if (packName.length() == 0) { + fPackageDialogField.setStatus(NewWizardMessages + .getString("NewTypeWizardPage.default")); //$NON-NLS-1$ + } else { + fPackageDialogField.setStatus(""); //$NON-NLS-1$ + } + } + + /* + * Updates the enable state of buttons related to the enclosing type + * selection checkbox. + */ + private void updateEnableState() { + boolean enclosing = isEnclosingTypeSelected(); + fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); + fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType + && enclosing); + } + + /** + * Hook method that gets called when the enclosing type name has changed. + * The method validates the enclosing type and returns the status of the + * validation. It also updates the enclosing type model. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + // protected IStatus enclosingTypeChanged() { + // StatusInfo status= new StatusInfo(); + // fCurrEnclosingType= null; + // + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // + // fEnclosingTypeDialogField.enableButton(root != null); + // if (root == null) { + // status.setError(""); //$NON-NLS-1$ + // return status; + // } + // + // String enclName= getEnclosingTypeText(); + // if (enclName.length() == 0) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); + // //$NON-NLS-1$ + // return status; + // } + // try { + // IType type= findType(root.getJavaProject(), enclName); + // if (type == null) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); + // //$NON-NLS-1$ + // return status; + // } + // + // if (type.getCompilationUnit() == null) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); + // //$NON-NLS-1$ + // return status; + // } + // if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); + // //$NON-NLS-1$ + // return status; + // } + // + // fCurrEnclosingType= type; + // IPackageFragmentRoot enclosingRoot= + // JavaModelUtil.getPackageFragmentRoot(type); + // if (!enclosingRoot.equals(root)) { + // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); + // //$NON-NLS-1$ + // } + // return status; + // } catch (JavaModelException e) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); + // //$NON-NLS-1$ + // PHPeclipsePlugin.log(e); + // return status; + // } + // } + /** + * Hook method that gets called when the type name has changed. The method + * validates the type name and returns the status of the validation. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + protected IStatus typeNameChanged() { + StatusInfo status = new StatusInfo(); + String typeName = getTypeName(); + // must not be empty + if (typeName.length() == 0) { + status.setError(NewWizardMessages + .getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ + return status; + } + if (typeName.indexOf('.') != -1) { + status.setError(NewWizardMessages + .getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ + return status; + } + // IStatus val= JavaConventions.validateJavaTypeName(typeName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", + // val.getMessage())); //$NON-NLS-1$ + // return status; + // } else if (val.getSeverity() == IStatus.WARNING) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", + // val.getMessage())); //$NON-NLS-1$ + // // continue checking + // } + + // must not exist + if (!isEnclosingTypeSelected()) { + IPackageFragment pack = getPackageFragment(); + if (pack != null) { + ICompilationUnit cu = pack.getCompilationUnit(typeName + + ".java"); //$NON-NLS-1$ + if (cu.getResource().exists()) { + status + .setError(NewWizardMessages + .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ + return status; + } + } + } else { + IType type = getEnclosingType(); + if (type != null) { + IType member = type.getType(typeName); + if (member.exists()) { + status + .setError(NewWizardMessages + .getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ + return status; + } + } + } + return status; + } + + /** + * Hook method that gets called when the superclass name has changed. The + * method validates the superclass name and returns the status of the + * validation. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + // protected IStatus superClassChanged() { + // StatusInfo status= new StatusInfo(); + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // fSuperClassDialogField.enableButton(root != null); + // + // fSuperClass= null; + // + // String sclassName= getSuperClass(); + // if (sclassName.length() == 0) { + // // accept the empty field (stands for java.lang.Object) + // return status; + // } + // IStatus val= JavaConventions.validateJavaTypeName(sclassName); + // if (val.getSeverity() == IStatus.ERROR) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); + // //$NON-NLS-1$ + // return status; + // } + // if (root != null) { + // try { + // IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); + // if (type == null) { + // status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); + // //$NON-NLS-1$ + // return status; + // } else { + // if (type.isInterface()) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", + // sclassName)); //$NON-NLS-1$ + // return status; + // } + // int flags= type.getFlags(); + // if (Flags.isFinal(flags)) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", + // sclassName)); //$NON-NLS-1$ + // return status; + // } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", + // sclassName)); //$NON-NLS-1$ + // return status; + // } + // } + // fSuperClass= type; + // } catch (JavaModelException e) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); + // //$NON-NLS-1$ + // PHPeclipsePlugin.log(e); + // } + // } else { + // status.setError(""); //$NON-NLS-1$ + // } + // return status; + // + // } + // private IType resolveSuperTypeName(IJavaProject jproject, String + // sclassName) throws JavaModelException { + // if (!jproject.exists()) { + // return null; + // } + // IType type= null; + // if (isEnclosingTypeSelected()) { + // // search in the context of the enclosing type + // IType enclosingType= getEnclosingType(); + // if (enclosingType != null) { + // String[][] res= enclosingType.resolveType(sclassName); + // if (res != null && res.length > 0) { + // type= jproject.findType(res[0][0], res[0][1]); + // } + // } + // } else { + // IPackageFragment currPack= getPackageFragment(); + // if (type == null && currPack != null) { + // String packName= currPack.getElementName(); + // // search in own package + // if (!currPack.isDefaultPackage()) { + // type= jproject.findType(packName, sclassName); + // } + // // search in java.lang + // if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ + // type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ + // } + // } + // // search fully qualified + // if (type == null) { + // type= jproject.findType(sclassName); + // } + // } + // return type; + // } + // private IType findType(IJavaProject project, String typeName) throws + // JavaModelException { + // if (project.exists()) { + // return project.findType(typeName); + // } + // return null; + // } + /** + * Hook method that gets called when the list of super interface has + * changed. The method validates the superinterfaces and returns the status + * of the validation. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + // protected IStatus superInterfacesChanged() { + // StatusInfo status= new StatusInfo(); + // + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // fSuperInterfacesDialogField.enableButton(0, root != null); + // + // if (root != null) { + // List elements= fSuperInterfacesDialogField.getElements(); + // int nElements= elements.size(); + // for (int i= 0; i < nElements; i++) { + // String intfname= (String)elements.get(i); + // try { + // IType type= findType(root.getJavaProject(), intfname); + // if (type == null) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", + // intfname)); //$NON-NLS-1$ + // return status; + // } else { + // if (type.isClass()) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", + // intfname)); //$NON-NLS-1$ + // return status; + // } + // if (!JavaModelUtil.isVisible(type, getPackageFragment())) { + // status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", + // intfname)); //$NON-NLS-1$ + // return status; + // } + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // // let pass, checking is an extra + // } + // } + // } + // return status; + // } + /** + * Hook method that gets called when the modifiers have changed. The method + * validates the modifiers and returns the status of the validation. + *

+ * Subclasses may extend this method to perform their own validation. + *

+ * + * @return the status of the validation + */ + protected IStatus modifiersChanged() { + StatusInfo status = new StatusInfo(); + //int modifiers = getModifiers(); + + // if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { + // status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); + // //$NON-NLS-1$ + // } + return status; + } + + // selection dialogs + + // private IPackageFragment choosePackage() { + // IPackageFragmentRoot froot= getPackageFragmentRoot(); + // IJavaElement[] packages= null; + // try { + // if (froot != null && froot.exists()) { + // packages= froot.getChildren(); + // } + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // } + // if (packages == null) { + // packages= new IJavaElement[0]; + // } + // + // ElementListSelectionDialog dialog= new + // ElementListSelectionDialog(getShell(), new + // JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); + // dialog.setIgnoreCase(false); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); + // //$NON-NLS-1$ + // dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); + // //$NON-NLS-1$ + // dialog.setElements(packages); + // IPackageFragment pack= getPackageFragment(); + // if (pack != null) { + // dialog.setInitialSelections(new Object[] { pack }); + // } + // + // if (dialog.open() == ElementListSelectionDialog.OK) { + // return (IPackageFragment) dialog.getFirstResult(); + // } + // return null; + // } + + // private IType chooseEnclosingType() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return null; + // } + // + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new + // IJavaElement[] { root }); + // + // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), + // getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); + // //$NON-NLS-1$ + // dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); + // + // if (dialog.open() == TypeSelectionDialog.OK) { + // return (IType) dialog.getFirstResult(); + // } + // return null; + // } + + // private IType chooseSuperType() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return null; + // } + // + // IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; + // IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); + // + // TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), + // getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); + // dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); + // //$NON-NLS-1$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); + // //$NON-NLS-1$ + // dialog.setFilter(getSuperClass()); + // + // if (dialog.open() == TypeSelectionDialog.OK) { + // return (IType) dialog.getFirstResult(); + // } + // return null; + // } + + // private void chooseSuperInterfaces() { + // IPackageFragmentRoot root= getPackageFragmentRoot(); + // if (root == null) { + // return; + // } + // + // IJavaProject project= root.getJavaProject(); + // SuperInterfaceSelectionDialog dialog= new + // SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), + // fSuperInterfacesDialogField, project); + // dialog.setTitle(fIsClass ? + // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") + // : + // NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); + // //$NON-NLS-1$ //$NON-NLS-2$ + // dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); + // //$NON-NLS-1$ + // dialog.open(); + // return; + // } + + // ---- creation ---------------- + + /** + * Creates the new type using the entered field values. + * + * @param monitor + * a progress monitor to report progress. + */ + public void createType(IProgressMonitor monitor) throws CoreException, + InterruptedException { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + monitor.beginTask(NewWizardMessages + .getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ + ICompilationUnit createdWorkingCopy = null; + try { + // IPackageFragmentRoot root = getPackageFragmentRoot(); + // IPackageFragment pack = getPackageFragment(); + // if (pack == null) { + // pack = root.getPackageFragment(""); //$NON-NLS-1$ + // } + // + // if (!pack.exists()) { + // String packName = pack.getElementName(); + // pack = root.createPackageFragment(packName, true, null); + // } + + monitor.worked(1); + + String clName = getTypeName(); + + boolean isInnerClass = isEnclosingTypeSelected(); + + IType createdType; + // ImportsStructure imports; + int indent = 0; + + //IPreferenceStore store = PreferenceConstants.getPreferenceStore(); + // String[] prefOrder = + // JavaPreferencesSettings.getImportOrderPreference(store); + // int threshold = + // JavaPreferencesSettings.getImportNumberThreshold(store); + // + String lineDelimiter = null; + // if (!isInnerClass) { + lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + // + // ICompilationUnit parentCU = pack.createCompilationUnit(clName + + // ".php", "", false, new SubProgressMonitor(monitor, 2)); + // //$NON-NLS-1$ //$NON-NLS-2$ + // createdWorkingCopy = (ICompilationUnit) + // parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), + // null); + // + // imports = new ImportsStructure(createdWorkingCopy, prefOrder, + // threshold, false); + // // add an import that will be removed again. Having this import + // solves 14661 + // imports.addImport(pack.getElementName(), getTypeName()); + // + //String typeContent = constructTypeStub(lineDelimiter);// new + // ImportsManager(imports), + // lineDelimiter); + + // String cuContent = constructCUContent(parentCU, typeContent, + // lineDelimiter); + + // createdWorkingCopy.getBuffer().setContents(cuContent); + // + createdType = createdWorkingCopy.getType(clName); + // } else { + // IType enclosingType = getEnclosingType(); + // + // // if we are working on a enclosed type that is open in an + // editor, + // // then replace the enclosing type with its working copy + // IType workingCopy = (IType) + // EditorUtility.getWorkingCopy(enclosingType); + // if (workingCopy != null) { + // enclosingType = workingCopy; + // } + // + // ICompilationUnit parentCU = enclosingType.getCompilationUnit(); + // imports = new ImportsStructure(parentCU, prefOrder, threshold, + // true); + // + // // add imports that will be removed again. Having the imports + // solves 14661 + // IType[] topLevelTypes = parentCU.getTypes(); + // for (int i = 0; i < topLevelTypes.length; i++) { + // imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); + // } + // + // lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); + // StringBuffer content = new StringBuffer(); + // String comment = getTypeComment(parentCU); + // if (comment != null) { + // content.append(comment); + // content.append(lineDelimiter); + // } + // content.append(constructTypeStub(new ImportsManager(imports), + // lineDelimiter)); + // IJavaElement[] elems = enclosingType.getChildren(); + // IJavaElement sibling = elems.length > 0 ? elems[0] : null; + // + // createdType = enclosingType.createType(content.toString(), + // sibling, false, new SubProgressMonitor(monitor, 1)); + // + // indent = StubUtility.getIndentUsed(enclosingType) + 1; + // } + // + // // add imports for superclass/interfaces, so types can be + // resolved correctly + // imports.create(false, new SubProgressMonitor(monitor, 1)); + // + ICompilationUnit cu = createdType.getCompilationUnit(); + synchronized (cu) { + cu.reconcile(); + } + // createTypeMembers(createdType, new ImportsManager(imports), new + // SubProgressMonitor(monitor, 1)); + // + // // add imports + // imports.create(false, new SubProgressMonitor(monitor, 1)); + + synchronized (cu) { + cu.reconcile(); + } + ISourceRange range = createdType.getSourceRange(); + + IBuffer buf = cu.getBuffer(); + String originalContent = buf.getText(range.getOffset(), range + .getLength()); + String formattedContent = StubUtility.codeFormat(originalContent, + indent, lineDelimiter); + buf.replace(range.getOffset(), range.getLength(), formattedContent); + if (!isInnerClass) { + String fileComment = getFileComment(cu); + if (fileComment != null && fileComment.length() > 0) { + buf.replace(0, 0, fileComment + lineDelimiter); + } + cu.commit(false, new SubProgressMonitor(monitor, 1)); + } else { + monitor.worked(1); + } + fCreatedType = createdType; + } finally { + if (createdWorkingCopy != null) { + createdWorkingCopy.destroy(); + } + monitor.done(); + } + } + + /** + * Uses the New Java file template from the code template page to generate a + * compilation unit with the given type content. + * + * @param cu + * The new created compilation unit + * @param typeContent + * The content of the type, including signature and type body. + * @param lineDelimiter + * The line delimiter to be used. + * @return String Returns the result of evaluating the new file template + * with the given type content. + * @throws CoreException + * @since 2.1 + */ + // protected String constructCUContent(ICompilationUnit cu, String + // typeContent, String lineDelimiter) throws CoreException { + // StringBuffer typeQualifiedName= new StringBuffer(); + // if (isEnclosingTypeSelected()) { + // typeQualifiedName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); + // } + // typeQualifiedName.append(getTypeName()); + // String typeComment= CodeGeneration.getTypeComment(cu, + // typeQualifiedName.toString(), lineDelimiter); + // IPackageFragment pack= (IPackageFragment) cu.getParent(); + // String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, + // typeContent, lineDelimiter); + // if (content != null) { + // CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray()); + // if ((pack.isDefaultPackage() || unit.getPackage() != null) && + // !unit.types().isEmpty()) { + // return content; + // } + // } + // StringBuffer buf= new StringBuffer(); + // if (!pack.isDefaultPackage()) { + // buf.append("package ").append(pack.getElementName()).append(';'); + // //$NON-NLS-1$ + // } + // buf.append(lineDelimiter).append(lineDelimiter); + // if (typeComment != null) { + // buf.append(typeComment).append(lineDelimiter); + // } + // buf.append(typeContent); + // return buf.toString(); + // } + /** + * Returns the created type. The method only returns a valid type after + * createType has been called. + * + * @return the created type + * @see #createType(IProgressMonitor) + */ + public IType getCreatedType() { + return fCreatedType; + } + + // ---- construct cu body---------------- + + // private void writeSuperClass(StringBuffer buf, ImportsManager imports) { + // String typename= getSuperClass(); + // if (fIsClass && typename.length() > 0 && + // !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ + // buf.append(" extends "); //$NON-NLS-1$ + // + // String qualifiedName= fSuperClass != null ? + // JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; + // buf.append(imports.addImport(qualifiedName)); + // } + // } + + // private void writeSuperInterfaces(StringBuffer buf, ImportsManager + // imports) { + // List interfaces= getSuperInterfaces(); + // int last= interfaces.size() - 1; + // if (last >= 0) { + // if (fIsClass) { + // buf.append(" implements "); //$NON-NLS-1$ + // } else { + // buf.append(" extends "); //$NON-NLS-1$ + // } + // for (int i= 0; i <= last; i++) { + // String typename= (String) interfaces.get(i); + // buf.append(imports.addImport(typename)); + // if (i < last) { + // buf.append(','); + // } + // } + // } + // } + + /* + * Called from createType to construct the source for this type + */ +// private String constructTypeStub(String lineDelimiter) { // ImportsManager +// // imports, +// // String +// // lineDelimiter) +// // { +// StringBuffer buf = new StringBuffer(); +// +// int modifiers = getModifiers(); +// buf.append(Flags.toString(modifiers)); +// if (modifiers != 0) { +// buf.append(' '); +// } +// buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ +// buf.append(getTypeName()); +// // writeSuperClass(buf, imports); +// // writeSuperInterfaces(buf, imports); +// buf.append('{'); +// buf.append(lineDelimiter); +// buf.append(lineDelimiter); +// buf.append('}'); +// buf.append(lineDelimiter); +// return buf.toString(); +// } + + /** + * @deprecated Overwrite createTypeMembers(IType, IImportsManager, + * IProgressMonitor) instead + */ + // protected void createTypeMembers(IType newType, IImportsStructure + // imports, IProgressMonitor monitor) throws CoreException { + // //deprecated + // } + /** + * Hook method that gets called from createType to support + * adding of unanticipated methods, fields, and inner types to the created + * type. + *

+ * Implementers can use any methods defined on IType to + * manipulate the new type. + *

+ *

+ * The source code of the new type will be formtted using the platform's + * formatter. Needed imports are added by the wizard at the end of the type + * creation process using the given import manager. + *

+ * + * @param newType + * the new type created via createType + * @param imports + * an import manager which can be used to add new imports + * @param monitor + * a progress monitor to report progress. Must not be + * null + * + * @see #createType(IProgressMonitor) + */ + // protected void createTypeMembers(IType newType, ImportsManager imports, + // IProgressMonitor monitor) throws CoreException { + // // call for compatibility + // createTypeMembers(newType, + // ((ImportsManager)imports).getImportsStructure(), monitor); + // + // // default implementation does nothing + // // example would be + // // String mainMathod= "public void foo(Vector vec) {}" + // // createdType.createMethod(main, null, false, null); + // // imports.addImport("java.lang.Vector"); + // } + /** + * @deprecated Instead of file templates, the new type code template + * specifies the stub for a compilation unit. + */ + protected String getFileComment(ICompilationUnit parentCU) { + return null; + } + + private boolean isValidComment(String template) { + IScanner scanner = ToolFactory.createScanner(true, false, false); // , + // false); + scanner.setSource(template.toCharArray()); + try { + TokenName next = scanner.getNextToken(); + while (next == ITerminalSymbols.TokenName.COMMENT_LINE + || next == ITerminalSymbols.TokenName.COMMENT_PHPDOC + || next == ITerminalSymbols.TokenName.COMMENT_BLOCK) { + next = scanner.getNextToken(); + } + return next == ITerminalSymbols.TokenName.EOF; + } catch (InvalidInputException e) { + } + return false; + } + + /** + * Hook method that gets called from createType to retrieve a + * type comment. This default implementation returns the content of the + * 'typecomment' template. + * + * @return the type comment or null if a type comment is not + * desired + */ +// protected String getTypeComment(ICompilationUnit parentCU) { +// if (PreferenceConstants.getPreferenceStore().getBoolean( +// PreferenceConstants.CODEGEN_ADD_COMMENTS)) { +// try { +// StringBuffer typeName = new StringBuffer(); +// if (isEnclosingTypeSelected()) { +// typeName.append( +// JavaModelUtil +// .getTypeQualifiedName(getEnclosingType())) +// .append('.'); +// } +// typeName.append(getTypeName()); +// String comment = CodeGeneration.getTypeComment(parentCU, +// typeName.toString(), String.valueOf('\n')); +// if (comment != null && isValidComment(comment)) { +// return comment; +// } +// } catch (CoreException e) { +// PHPeclipsePlugin.log(e); +// } +// } +// return null; +// } + + /** + * @deprecated Use getTemplate(String,ICompilationUnit,int) + */ +// protected String getTemplate(String name, ICompilationUnit parentCU) { +// return getTemplate(name, parentCU, 0); +// } + + /** + * Returns the string resulting from evaluation the given template in the + * context of the given compilation unit. This accesses the normal template + * page, not the code templates. To use code templates use + * constructCUContent to construct a compilation unit stub or + * getTypeComment for the comment of the type. + * + * @param name + * the template to be evaluated + * @param parentCU + * the templates evaluation context + * @param pos + * a source offset into the parent compilation unit. The template + * is evalutated at the given source offset + */ +// protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { +// try { +// Template[] templates = Templates.getInstance().getTemplates(name); +// if (templates.length > 0) { +// return JavaContext +// .evaluateTemplate(templates[0], parentCU, pos); +// } +// } catch (CoreException e) { +// PHPeclipsePlugin.log(e); +// } catch (BadLocationException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); +// } catch (TemplateException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); +// } +// return null; +// } + + /** + * @deprecated Use + * createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) + */ + // protected IMethod[] createInheritedMethods(IType type, boolean + // doConstructors, boolean doUnimplementedMethods, IImportsStructure + // imports, IProgressMonitor monitor) throws CoreException { + // return createInheritedMethods(type, doConstructors, + // doUnimplementedMethods, new ImportsManager(imports), monitor); + // } + /** + * Creates the bodies of all unimplemented methods and constructors and adds + * them to the type. Method is typically called by implementers of + * NewTypeWizardPage to add needed method and constructors. + * + * @param type + * the type for which the new methods and constructor are to be + * created + * @param doConstructors + * if true unimplemented constructors are created + * @param doUnimplementedMethods + * if true unimplemented methods are created + * @param imports + * an import manager to add all neded import statements + * @param monitor + * a progress monitor to report progress + */ + // protected IMethod[] createInheritedMethods(IType type, boolean + // doConstructors, boolean doUnimplementedMethods, ImportsManager imports, + // IProgressMonitor monitor) throws CoreException { + // ArrayList newMethods= new ArrayList(); + // ITypeHierarchy hierarchy= null; + // CodeGenerationSettings settings= + // JavaPreferencesSettings.getCodeGenerationSettings(); + // + // if (doConstructors) { + // hierarchy= type.newSupertypeHierarchy(monitor); + // IType superclass= hierarchy.getSuperclass(type); + // if (superclass != null) { + // String[] constructors= StubUtility.evalConstructors(type, superclass, + // settings, imports.getImportsStructure()); + // if (constructors != null) { + // for (int i= 0; i < constructors.length; i++) { + // newMethods.add(constructors[i]); + // } + // } + // + // } + // } + // if (doUnimplementedMethods) { + // if (hierarchy == null) { + // hierarchy= type.newSupertypeHierarchy(monitor); + // } + // String[] unimplemented= StubUtility.evalUnimplementedMethods(type, + // hierarchy, false, settings, null, imports.getImportsStructure()); + // if (unimplemented != null) { + // for (int i= 0; i < unimplemented.length; i++) { + // newMethods.add(unimplemented[i]); + // } + // } + // } + // IMethod[] createdMethods= new IMethod[newMethods.size()]; + // for (int i= 0; i < newMethods.size(); i++) { + // String content= (String) newMethods.get(i) + '\n'; // content will be + // formatted, ok to use \n + // createdMethods[i]= type.createMethod(content, null, false, null); + // } + // return createdMethods; + // } + // ---- creation ---------------- + /** + * Returns the runnable that creates the type using the current settings. + * The returned runnable must be executed in the UI thread. + * + * @return the runnable to create the new type + */ + // public IRunnableWithProgress getRunnable() { + // return new IRunnableWithProgress() { + // public void run(IProgressMonitor monitor) throws + // InvocationTargetException, InterruptedException { + // try { + // if (monitor == null) { + // monitor= new NullProgressMonitor(); + // } + // createType(monitor); + // } catch (CoreException e) { + // throw new InvocationTargetException(e); + // } + // } + // }; + // } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java index ba72251..2624642 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java @@ -8,34 +8,33 @@ **********************************************************************/ package net.sourceforge.phpeclipse; -//import java.io.File; -//import java.io.IOException; -//import java.io.InputStream; -//import java.util.ArrayList; -//import java.util.Collection; -//import java.util.Enumeration; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; import java.util.HashMap; -//import java.util.HashSet; -//import java.util.Iterator; -//import java.util.List; -//import java.util.PropertyResourceBundle; -//import java.util.Set; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.PropertyResourceBundle; +import java.util.Set; -//import net.sourceforge.phpdt.core.IBuffer; +import net.sourceforge.phpdt.core.IBuffer; import net.sourceforge.phpdt.core.IBufferFactory; -//import net.sourceforge.phpdt.core.ICompilationUnit; -//import net.sourceforge.phpdt.core.IJavaElement; -//import net.sourceforge.phpdt.core.JavaCore; -//import net.sourceforge.phpdt.core.WorkingCopyOwner; +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.WorkingCopyOwner; import net.sourceforge.phpdt.internal.core.BatchOperation; -//import net.sourceforge.phpdt.internal.core.JavaModelManager; -//import net.sourceforge.phpdt.internal.core.util.Util; -/*import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpdt.internal.core.JavaModelManager; +import net.sourceforge.phpdt.internal.core.util.Util; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; import net.sourceforge.phpdt.internal.corext.template.php.HTMLContextType; import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; -import net.sourceforge.phpdt.internal.corext.template.php.JavaDocContextType;*/ -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; -/*import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants; +import net.sourceforge.phpdt.internal.corext.template.php.JavaDocContextType; +import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants; import net.sourceforge.phpdt.internal.ui.JavaElementAdapterFactory; import net.sourceforge.phpdt.internal.ui.ResourceAdapterFactory; import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; @@ -48,49 +47,46 @@ import net.sourceforge.phpdt.internal.ui.viewsupport.ProblemMarkerManager; import net.sourceforge.phpdt.ui.IContextMenuConstants; import net.sourceforge.phpdt.ui.IWorkingCopyManager; import net.sourceforge.phpdt.ui.PreferenceConstants; -import net.sourceforge.phpdt.ui.text.JavaTextTools;*/ -/*import net.sourceforge.phpeclipse.builder.ExternalEditorInput; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.builder.ExternalEditorInput; import net.sourceforge.phpeclipse.builder.ExternalStorageDocumentProvider; import net.sourceforge.phpeclipse.builder.FileStorage; -import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;*/ -/*import net.sourceforge.phpeclipse.phpeditor.CustomBufferFactory; -import net.sourceforge.phpeclipse.phpeditor.DocumentAdapter; +import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; +import net.sourceforge.phpeclipse.CustomBufferFactory; +import net.sourceforge.phpeclipse.DocumentAdapter; import net.sourceforge.phpeclipse.phpeditor.ICompilationUnitDocumentProvider; import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider; import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; import net.sourceforge.phpeclipse.phpeditor.WorkingCopyManager; -import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider;*/ +import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; -//import org.eclipse.core.resources.IResource; -//import org.eclipse.core.resources.IResourceChangeEvent; -//import org.eclipse.core.resources.ISavedState; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.ISavedState; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; -//import org.eclipse.core.resources.WorkspaceJob; +import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; -//import org.eclipse.core.runtime.IAdapterManager; -//import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IAdapterManager; +import org.eclipse.core.runtime.IConfigurationElement; 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.Platform; -import org.eclipse.core.runtime.Plugin; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; -//import org.eclipse.core.runtime.jobs.Job; -//import org.eclipse.jface.text.templates.ContextTypeRegistry; -//import org.eclipse.ui.editors.text.templates.ContributionContextTypeRegistry; -//import org.eclipse.jface.action.GroupMarker; -//import org.eclipse.jface.action.IMenuManager; -//import org.eclipse.jface.action.Separator; -//import org.eclipse.jface.preference.IPreferenceStore; -//import org.eclipse.jface.preference.PreferenceConverter; -//import org.eclipse.jface.resource.JFaceResources; -/*import org.eclipse.jface.text.BadLocationException; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.action.GroupMarker; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.templates.ContextTypeRegistry; import org.eclipse.jface.text.templates.persistence.TemplateStore; @@ -116,13 +112,13 @@ import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.ui.texteditor.ConfigurationElementSorter; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;*/ -//import org.osgi.framework.BundleContext; +import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; +import org.osgi.framework.BundleContext; /** * The main plugin class to be used in the desktop. */ -public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements +public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceConstants { /** * The id of the PHP plugin (value "net.sourceforge.phpeclipse"). @@ -132,7 +128,7 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements public static final String EDITOR_ID = PHPeclipsePlugin.PLUGIN_ID + ".PHPUnitEditor"; - //public static final String ID_PERSPECTIVE = "net.sourceforge.phpeclipse.PHPPerspective"; //$NON-NLS-1$ + public static final String ID_PERSPECTIVE = "net.sourceforge.phpeclipse.PHPPerspective"; //$NON-NLS-1$ IWorkspace w; @@ -157,14 +153,14 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ - //private static final String TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_templates"; //$NON-NLS-1$ + private static final String TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_templates"; //$NON-NLS-1$ /** * The key to store customized code templates. * * @since 3.0 */ - //private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ + private static final String CODE_TEMPLATES_KEY = "net.sourceforge.phpdt.ui.text.custom_code_templates"; //$NON-NLS-1$ public static final String PHP_CODING_ACTION_SET_ID = PLUGIN_ID + ".ui.CodingActionSet"; //$NON-NLS-1$ @@ -186,63 +182,63 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ - /*private ContextTypeRegistry fContextTypeRegistry;*/ + private ContextTypeRegistry fContextTypeRegistry; /** * The code template context type registry for the java editor. * * @since 3.0 */ - //private ContextTypeRegistry fCodeTemplateContextTypeRegistry; + private ContextTypeRegistry fCodeTemplateContextTypeRegistry; /** * The template store for the java editor. * * @since 3.0 */ - /*private TemplateStore fTemplateStore;*/ + private TemplateStore fTemplateStore; /** * The coded template store for the java editor. * * @since 3.0 */ - /*private TemplateStore fCodeTemplateStore;*/ + private TemplateStore fCodeTemplateStore; /** Windows 9x */ - //private static final int WINDOWS_9x = 6; + private static final int WINDOWS_9x = 6; /** Windows NT */ - //private static final int WINDOWS_NT = 5; + private static final int WINDOWS_NT = 5; - /*private ImageDescriptorRegistry fImageDescriptorRegistry;*/ + private ImageDescriptorRegistry fImageDescriptorRegistry; private HashMap fIndexManagerMap = new HashMap(); - /*private IWorkingCopyManager fWorkingCopyManager;*/ + private IWorkingCopyManager fWorkingCopyManager; private IBufferFactory fBufferFactory; - /*private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider;*/ + private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider; - /*private JavaTextTools fJavaTextTools;*/ + private JavaTextTools fJavaTextTools; - /*private ProblemMarkerManager fProblemMarkerManager;*/ + private ProblemMarkerManager fProblemMarkerManager; - /*private MembersOrderPreferenceCache fMembersOrderPreferenceCache;*/ + private MembersOrderPreferenceCache fMembersOrderPreferenceCache; - //private IFile fLastEditorFile = null; + private IFile fLastEditorFile = null; -/* private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;*/ + private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors; - /*private JavaElementAdapterFactory fJavaElementAdapterFactory;*/ + private JavaElementAdapterFactory fJavaElementAdapterFactory; // private MarkerAdapterFactory fMarkerAdapterFactory; // private EditorInputAdapterFactory fEditorInputAdapterFactory; - /*private ResourceAdapterFactory fResourceAdapterFactory;*/ + private ResourceAdapterFactory fResourceAdapterFactory; // private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory; - /*private IPropertyChangeListener fFontPropertyChangeListener;*/ + private IPropertyChangeListener fFontPropertyChangeListener; /** * Property change listener on this plugin's preference store. @@ -255,7 +251,7 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ - /*private IPreferenceStore fCombinedPreferenceStore;*/ + private IPreferenceStore fCombinedPreferenceStore; /** * The extension point registry for the @@ -264,7 +260,7 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ - /*private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry;*/ + private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry; /** * Mockup preference store for firing events and registering listeners on @@ -272,7 +268,7 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ - /*private MockupPreferenceStore fMockupPreferenceStore;*/ + private MockupPreferenceStore fMockupPreferenceStore; /** * The constructor. @@ -310,92 +306,92 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @return an array of JavaEditorTextHoverDescriptor * @since 2.1 */ -// public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() { -// if (fJavaEditorTextHoverDescriptors == null) { -// fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor -// .getContributedHovers(); -// ConfigurationElementSorter sorter = new ConfigurationElementSorter() { -// /* -// * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) -// */ -// public IConfigurationElement getConfigurationElement( -// Object object) { -// return ((JavaEditorTextHoverDescriptor) object) -// .getConfigurationElement(); -// } -// }; -// sorter.sort(fJavaEditorTextHoverDescriptors); -// -// // The Problem hover has to be the first and the Annotation hover -// // has to -// // be the last one in the JDT UI's hover list -// int length = fJavaEditorTextHoverDescriptors.length; -// int first = -1; -// int last = length - 1; -// int problemHoverIndex = -1; -// int annotationHoverIndex = -1; -// for (int i = 0; i < length; i++) { -// if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith( -// PLUGIN_ID)) { -// if (problemHoverIndex == -1 || annotationHoverIndex == -1) -// continue; -// else { -// last = i - 1; -// break; -// } -// } -// if (first == -1) -// first = i; -// -// if (fJavaEditorTextHoverDescriptors[i].getId().equals( -// "net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$ -// annotationHoverIndex = i; -// continue; -// } -// if (fJavaEditorTextHoverDescriptors[i].getId().equals( -// "net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$ -// problemHoverIndex = i; -// continue; -// } -// } -// -// JavaEditorTextHoverDescriptor hoverDescriptor = null; -// -// if (first > -1 && problemHoverIndex > -1 -// && problemHoverIndex != first) { -// // move problem hover to beginning -// hoverDescriptor = fJavaEditorTextHoverDescriptors[first]; -// fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex]; -// fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor; -// -// // update annotation hover index if needed -// if (annotationHoverIndex == first) -// annotationHoverIndex = problemHoverIndex; -// } -// -// if (annotationHoverIndex > -1 && annotationHoverIndex != last) { -// // move annotation hover to end -// hoverDescriptor = fJavaEditorTextHoverDescriptors[last]; -// fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex]; -// fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor; -// } -// -// // Move Best Match hover to front -// for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) { -// if (PreferenceConstants.ID_BESTMATCH_HOVER -// .equals(fJavaEditorTextHoverDescriptors[i].getId())) { -// hoverDescriptor = fJavaEditorTextHoverDescriptors[i]; -// for (int j = i; j > 0; j--) -// fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1]; -// fJavaEditorTextHoverDescriptors[0] = hoverDescriptor; -// break; -// } -// -// } -// } -// -// return fJavaEditorTextHoverDescriptors; -// } + public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() { + if (fJavaEditorTextHoverDescriptors == null) { + fJavaEditorTextHoverDescriptors = JavaEditorTextHoverDescriptor + .getContributedHovers(); + ConfigurationElementSorter sorter = new ConfigurationElementSorter() { + /* + * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) + */ + public IConfigurationElement getConfigurationElement( + Object object) { + return ((JavaEditorTextHoverDescriptor) object) + .getConfigurationElement(); + } + }; + sorter.sort(fJavaEditorTextHoverDescriptors); + + // The Problem hover has to be the first and the Annotation hover + // has to + // be the last one in the JDT UI's hover list + int length = fJavaEditorTextHoverDescriptors.length; + int first = -1; + int last = length - 1; + int problemHoverIndex = -1; + int annotationHoverIndex = -1; + for (int i = 0; i < length; i++) { + if (!fJavaEditorTextHoverDescriptors[i].getId().startsWith( + PLUGIN_ID)) { + if (problemHoverIndex == -1 || annotationHoverIndex == -1) + continue; + else { + last = i - 1; + break; + } + } + if (first == -1) + first = i; + + if (fJavaEditorTextHoverDescriptors[i].getId().equals( + "net.sourceforge.phpdt.ui.AnnotationHover")) { //$NON-NLS-1$ + annotationHoverIndex = i; + continue; + } + if (fJavaEditorTextHoverDescriptors[i].getId().equals( + "net.sourceforge.phpdt.ui.ProblemHover")) { //$NON-NLS-1$ + problemHoverIndex = i; + continue; + } + } + + JavaEditorTextHoverDescriptor hoverDescriptor = null; + + if (first > -1 && problemHoverIndex > -1 + && problemHoverIndex != first) { + // move problem hover to beginning + hoverDescriptor = fJavaEditorTextHoverDescriptors[first]; + fJavaEditorTextHoverDescriptors[first] = fJavaEditorTextHoverDescriptors[problemHoverIndex]; + fJavaEditorTextHoverDescriptors[problemHoverIndex] = hoverDescriptor; + + // update annotation hover index if needed + if (annotationHoverIndex == first) + annotationHoverIndex = problemHoverIndex; + } + + if (annotationHoverIndex > -1 && annotationHoverIndex != last) { + // move annotation hover to end + hoverDescriptor = fJavaEditorTextHoverDescriptors[last]; + fJavaEditorTextHoverDescriptors[last] = fJavaEditorTextHoverDescriptors[annotationHoverIndex]; + fJavaEditorTextHoverDescriptors[annotationHoverIndex] = hoverDescriptor; + } + + // Move Best Match hover to front + for (int i = 0; i < fJavaEditorTextHoverDescriptors.length - 1; i++) { + if (PreferenceConstants.ID_BESTMATCH_HOVER + .equals(fJavaEditorTextHoverDescriptors[i].getId())) { + hoverDescriptor = fJavaEditorTextHoverDescriptors[i]; + for (int j = i; j > 0; j--) + fJavaEditorTextHoverDescriptors[j] = fJavaEditorTextHoverDescriptors[j - 1]; + fJavaEditorTextHoverDescriptors[0] = hoverDescriptor; + break; + } + + } + } + + return fJavaEditorTextHoverDescriptors; + } /** * Resets the Java editor text hovers contributed to the workbench. @@ -407,36 +403,36 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @return an array of JavaEditorTextHoverDescriptor * @since 2.1 */ -// public void resetJavaEditorTextHoverDescriptors() { -// fJavaEditorTextHoverDescriptors = null; -// } + public void resetJavaEditorTextHoverDescriptors() { + fJavaEditorTextHoverDescriptors = null; + } /** * Creates the PHP plugin standard groups in a context menu. */ -// public static void createStandardGroups(IMenuManager menu) { -// if (!menu.isEmpty()) -// return; -// menu.add(new Separator(IContextMenuConstants.GROUP_NEW)); -// menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO)); -// menu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); -// menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW)); -// menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); -// menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); -// menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); -// menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); -// menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); -// menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP)); -// menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES)); -// } -// -// public static IWorkbenchPage getActivePage() { -// return getDefault().internalGetActivePage(); -// } -// -// public static Shell getActiveWorkbenchShell() { -// return getActiveWorkbenchWindow().getShell(); -// } + public static void createStandardGroups(IMenuManager menu) { + if (!menu.isEmpty()) + return; + menu.add(new Separator(IContextMenuConstants.GROUP_NEW)); + menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO)); + menu.add(new Separator(IContextMenuConstants.GROUP_OPEN)); + menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW)); + menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); + menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); + menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH)); + menu.add(new Separator(IContextMenuConstants.GROUP_BUILD)); + menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS)); + menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP)); + menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES)); + } + + public static IWorkbenchPage getActivePage() { + return getDefault().internalGetActivePage(); + } + + public static Shell getActiveWorkbenchShell() { + return getActiveWorkbenchWindow().getShell(); + } /** * Returns an array of all editors that have an unsaved content. If the @@ -445,31 +441,31 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @return an array of all dirty editor parts. */ -// public static IEditorPart[] getDirtyEditors() { -// Set inputs = new HashSet(); -// List result = new ArrayList(0); -// IWorkbench workbench = getDefault().getWorkbench(); -// IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); -// for (int i = 0; i < windows.length; i++) { -// IWorkbenchPage[] pages = windows[i].getPages(); -// for (int x = 0; x < pages.length; x++) { -// IEditorPart[] editors = pages[x].getDirtyEditors(); -// for (int z = 0; z < editors.length; z++) { -// IEditorPart ep = editors[z]; -// IEditorInput input = ep.getEditorInput(); -// if (!inputs.contains(input)) { -// inputs.add(input); -// result.add(ep); -// } -// } -// } -// } -// return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]); -// } -// -// public static IWorkbenchWindow getActiveWorkbenchWindow() { -// return getDefault().getWorkbench().getActiveWorkbenchWindow(); -// } + public static IEditorPart[] getDirtyEditors() { + Set inputs = new HashSet(); + List result = new ArrayList(0); + IWorkbench workbench = getDefault().getWorkbench(); + IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); + for (int i = 0; i < windows.length; i++) { + IWorkbenchPage[] pages = windows[i].getPages(); + for (int x = 0; x < pages.length; x++) { + IEditorPart[] editors = pages[x].getDirtyEditors(); + for (int z = 0; z < editors.length; z++) { + IEditorPart ep = editors[z]; + IEditorInput input = ep.getEditorInput(); + if (!inputs.contains(input)) { + inputs.add(input); + result.add(ep); + } + } + } + } + return (IEditorPart[]) result.toArray(new IEditorPart[result.size()]); + } + + public static IWorkbenchWindow getActiveWorkbenchWindow() { + return getDefault().getWorkbench().getActiveWorkbenchWindow(); + } /** * Returns the shared instance. @@ -478,13 +474,13 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements return plugin; } -// public static ImageDescriptorRegistry getImageDescriptorRegistry() { -// return getDefault().internalGetImageDescriptorRegistry(); -// } + public static ImageDescriptorRegistry getImageDescriptorRegistry() { + return getDefault().internalGetImageDescriptorRegistry(); + } -// static IPath getInstallLocation() { -// return new Path(getDefault().getBundle().getEntry("/").getFile()); -// } + static IPath getInstallLocation() { + return new Path(getDefault().getBundle().getEntry("/").getFile()); + } // public static int getJVM() { // return jvm; @@ -499,13 +495,13 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * thread calling this method has an associated display. If so, this display * is returned. Otherwise the method returns the default display. */ -// public static Display getStandardDisplay() { -// Display display = Display.getCurrent(); -// if (display == null) { -// display = Display.getDefault(); -// } -// return display; -// } + public static Display getStandardDisplay() { + Display display = Display.getCurrent(); + if (display == null) { + display = Display.getDefault(); + } + return display; + } // public static ExternalToolsPlugin getExternalTools() { // return externalTools; @@ -560,10 +556,10 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements log(error(message, t)); } -// public static void logErrorMessage(String message) { -// log(new Status(IStatus.ERROR, getPluginId(), -// IJavaStatusConstants.INTERNAL_ERROR, message, null)); -// } + public static void logErrorMessage(String message) { + log(new Status(IStatus.ERROR, getPluginId(), + IJavaStatusConstants.INTERNAL_ERROR, message, null)); + } public static IStatus error(Throwable t) { return error("PHPeclipsePlugin.internalErrorOccurred", t); //$NON-NLS-1$ @@ -602,11 +598,11 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements // } // TODO: refactor this into a better method name ! -// public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { -// if (fCompilationUnitDocumentProvider == null) -// fCompilationUnitDocumentProvider = new PHPDocumentProvider(); -// return fCompilationUnitDocumentProvider; -// } + public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() { + if (fCompilationUnitDocumentProvider == null) + fCompilationUnitDocumentProvider = new PHPDocumentProvider(); + return fCompilationUnitDocumentProvider; + } /** * Get the identifier index manager for the given project @@ -634,53 +630,53 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements } return indexManager; } -// -// public synchronized IWorkingCopyManager getWorkingCopyManager() { -// if (fWorkingCopyManager == null) { -// ICompilationUnitDocumentProvider provider = getCompilationUnitDocumentProvider(); -// fWorkingCopyManager = new WorkingCopyManager(provider); -// } -// return fWorkingCopyManager; -// } -// -// public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() { -// if (fMembersOrderPreferenceCache == null) -// fMembersOrderPreferenceCache = new MembersOrderPreferenceCache(); -// return fMembersOrderPreferenceCache; -// } -// -// /** -// * Returns the mockup preference store for firing events and registering -// * listeners on project setting changes. Temporary solution. -// */ -// public MockupPreferenceStore getMockupPreferenceStore() { -// if (fMockupPreferenceStore == null) -// fMockupPreferenceStore = new MockupPreferenceStore(); -// -// return fMockupPreferenceStore; -// } -// -// public synchronized ProblemMarkerManager getProblemMarkerManager() { -// if (fProblemMarkerManager == null) -// fProblemMarkerManager = new ProblemMarkerManager(); -// return fProblemMarkerManager; -// } + + public synchronized IWorkingCopyManager getWorkingCopyManager() { + if (fWorkingCopyManager == null) { + ICompilationUnitDocumentProvider provider = getCompilationUnitDocumentProvider(); + fWorkingCopyManager = new WorkingCopyManager(provider); + } + return fWorkingCopyManager; + } + + public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() { + if (fMembersOrderPreferenceCache == null) + fMembersOrderPreferenceCache = new MembersOrderPreferenceCache(); + return fMembersOrderPreferenceCache; + } + + /** + * Returns the mockup preference store for firing events and registering + * listeners on project setting changes. Temporary solution. + */ + public MockupPreferenceStore getMockupPreferenceStore() { + if (fMockupPreferenceStore == null) + fMockupPreferenceStore = new MockupPreferenceStore(); + + return fMockupPreferenceStore; + } + + public synchronized ProblemMarkerManager getProblemMarkerManager() { + if (fProblemMarkerManager == null) + fProblemMarkerManager = new ProblemMarkerManager(); + return fProblemMarkerManager; + } // public synchronized JavaTextTools getJavaTextTools() { // if (fJavaTextTools == null) // fJavaTextTools = new JavaTextTools(getPreferenceStore()); // return fJavaTextTools; // } -// public synchronized JavaTextTools getJavaTextTools() { -// if (fJavaTextTools == null) -// fJavaTextTools = new JavaTextTools(getPreferenceStore(), JavaCore -// .getPlugin().getPluginPreferences()); -// return fJavaTextTools; -// } + public synchronized JavaTextTools getJavaTextTools() { + if (fJavaTextTools == null) + fJavaTextTools = new JavaTextTools(getPreferenceStore(), JavaCore + .getPlugin().getPluginPreferences()); + return fJavaTextTools; + } -// public IFile getLastEditorFile() { -// return fLastEditorFile; -// } + public IFile getLastEditorFile() { + return fLastEditorFile; + } /** * Returns the string from the plugin's resource bundle, or 'key' if not @@ -701,118 +697,118 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements // public ResourceBundle getResourceBundle() { // return resourceBundle; // } -// protected void initializeDefaultPreferences(IPreferenceStore store) { -// String operatingSystem = Platform.getOS(); -// // maxosx, linux, solaris, win32,... -// try { -// InputStream is = getDefault() -// .openStream( -// new Path("prefs/default_" + operatingSystem -// + ".properties")); -// PropertyResourceBundle resourceBundle = new PropertyResourceBundle( -// is); -// Enumeration e = resourceBundle.getKeys(); -// String key; -// while (e.hasMoreElements()) { -// key = (String) e.nextElement(); -// store.setDefault(key, resourceBundle.getString(key)); -// } -// } catch (Exception e) { -// // no default properties found -// if (operatingSystem.equals(Platform.OS_WIN32)) { -// // store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); -// // store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -// // -l -f {0}"); -// // store.setDefault(MYSQL_RUN_PREF, -// // "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); -// // store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); -// // store.setDefault(XAMPP_START_PREF, -// // "c:\\xampp\\xampp_start.exe"); -// // store.setDefault(XAMPP_STOP_PREF, -// // "c:\\xampp\\xampp_stop.exe"); -// // store.setDefault( -// // ETC_HOSTS_PATH_PREF, -// // "c:\\windows\\system32\\drivers\\etc\\hosts"); -// } else { -// // store.setDefault(PHP_RUN_PREF, "/apache/php/php"); -// // store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f -// // {0}"); -// // store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); -// // store.setDefault(APACHE_RUN_PREF, "/apache/apache"); -// // store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); -// // store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); -// } -// // store.setDefault(MYSQL_PREF, "--standalone"); -// // store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot -// // \"{0}\"\""); -// // store.setDefault(APACHE_STOP_PREF, "-k shutdown"); -// // store.setDefault(APACHE_RESTART_PREF, "-k restart"); -// // store.setDefault(MYSQL_START_BACKGROUND, "true"); -// // store.setDefault(APACHE_START_BACKGROUND, "true"); -// // store.setDefault(APACHE_STOP_BACKGROUND, "true"); -// // store.setDefault(APACHE_RESTART_BACKGROUND, "true"); -// } -// -// // php syntax highlighting -// store.setDefault(PHP_USERDEF_XMLFILE, ""); -// PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG); -// PreferenceConverter.setDefault(store, PHP_KEYWORD, -// PHPColorProvider.KEYWORD); -// PreferenceConverter.setDefault(store, PHP_VARIABLE, -// PHPColorProvider.VARIABLE); -// PreferenceConverter.setDefault(store, PHP_VARIABLE_DOLLAR, -// PHPColorProvider.VARIABLE); -// PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, -// PHPColorProvider.FUNCTION_NAME); -// PreferenceConverter.setDefault(store, PHP_CONSTANT, -// PHPColorProvider.CONSTANT); -// PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); -// PreferenceConverter.setDefault(store, PHP_DEFAULT, -// PHPColorProvider.DEFAULT); -// PreferenceConverter.setDefault(store, PHPDOC_KEYWORD, -// PHPColorProvider.PHPDOC_KEYWORD); -// PreferenceConverter.setDefault(store, PHPDOC_TAG, -// PHPColorProvider.PHPDOC_TAG); -// PreferenceConverter.setDefault(store, PHPDOC_LINK, -// PHPColorProvider.PHPDOC_LINK); -// PreferenceConverter.setDefault(store, PHPDOC_DEFAULT, -// PHPColorProvider.PHPDOC_DEFAULT); -// -// PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, -// new RGB(127, 0, 85)); -// store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); -// store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); -// -// PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, -// new RGB(0, 0, 0)); -// store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); -// store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); -// -// PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, -// new RGB(0, 0, 0)); -// store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); -// store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); -// -// // this will initialize the static fields in the syntaxrdr class -// new PHPSyntaxRdr(); -// JavaCore.initializeDefaultPluginPreferences(); -// PreferenceConstants.initializeDefaultValues(store); -// // externalTools.initializeDefaultPreferences(store); -// // MarkerAnnotationPreferences.initializeDefaultValues(store); -// } -// -// private IWorkbenchPage internalGetActivePage() { -// IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); -// if (window != null) -// return window.getActivePage(); -// return null; -// } -// -// private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { -// if (fImageDescriptorRegistry == null) -// fImageDescriptorRegistry = new ImageDescriptorRegistry(); -// return fImageDescriptorRegistry; -// } + protected void initializeDefaultPreferences(IPreferenceStore store) { + String operatingSystem = Platform.getOS(); + // maxosx, linux, solaris, win32,... + try { + InputStream is = getDefault() + .openStream( + new Path("prefs/default_" + operatingSystem + + ".properties")); + PropertyResourceBundle resourceBundle = new PropertyResourceBundle( + is); + Enumeration e = resourceBundle.getKeys(); + String key; + while (e.hasMoreElements()) { + key = (String) e.nextElement(); + store.setDefault(key, resourceBundle.getString(key)); + } + } catch (Exception e) { + // no default properties found + if (operatingSystem.equals(Platform.OS_WIN32)) { + // store.setDefault(PHP_RUN_PREF, "c:\\apache\\php\\php.exe"); + // store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php + // -l -f {0}"); + // store.setDefault(MYSQL_RUN_PREF, + // "c:\\apache\\mysql\\bin\\mysqld-nt.exe"); + // store.setDefault(APACHE_RUN_PREF, "c:\\apache\\apache.exe"); + // store.setDefault(XAMPP_START_PREF, + // "c:\\xampp\\xampp_start.exe"); + // store.setDefault(XAMPP_STOP_PREF, + // "c:\\xampp\\xampp_stop.exe"); + // store.setDefault( + // ETC_HOSTS_PATH_PREF, + // "c:\\windows\\system32\\drivers\\etc\\hosts"); + } else { + // store.setDefault(PHP_RUN_PREF, "/apache/php/php"); + // store.setDefault(EXTERNAL_PARSER_PREF, "/apache/php/php -l -f + // {0}"); + // store.setDefault(MYSQL_RUN_PREF, "/apache/mysql/bin/mysqld"); + // store.setDefault(APACHE_RUN_PREF, "/apache/apache"); + // store.setDefault(XAMPP_START_PREF, "xamp/xampp_start"); + // store.setDefault(XAMPP_STOP_PREF, "xampp/xampp_stop"); + } + // store.setDefault(MYSQL_PREF, "--standalone"); + // store.setDefault(APACHE_START_PREF, "-c \"DocumentRoot + // \"{0}\"\""); + // store.setDefault(APACHE_STOP_PREF, "-k shutdown"); + // store.setDefault(APACHE_RESTART_PREF, "-k restart"); + // store.setDefault(MYSQL_START_BACKGROUND, "true"); + // store.setDefault(APACHE_START_BACKGROUND, "true"); + // store.setDefault(APACHE_STOP_BACKGROUND, "true"); + // store.setDefault(APACHE_RESTART_BACKGROUND, "true"); + } + + // php syntax highlighting + store.setDefault(PHP_USERDEF_XMLFILE, ""); + PreferenceConverter.setDefault(store, PHP_TAG, PHPColorProvider.TAG); + PreferenceConverter.setDefault(store, PHP_KEYWORD, + PHPColorProvider.KEYWORD); + PreferenceConverter.setDefault(store, PHP_VARIABLE, + PHPColorProvider.VARIABLE); + PreferenceConverter.setDefault(store, PHP_VARIABLE_DOLLAR, + PHPColorProvider.VARIABLE); + PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, + PHPColorProvider.FUNCTION_NAME); + PreferenceConverter.setDefault(store, PHP_CONSTANT, + PHPColorProvider.CONSTANT); + PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); + PreferenceConverter.setDefault(store, PHP_DEFAULT, + PHPColorProvider.DEFAULT); + PreferenceConverter.setDefault(store, PHPDOC_KEYWORD, + PHPColorProvider.PHPDOC_KEYWORD); + PreferenceConverter.setDefault(store, PHPDOC_TAG, + PHPColorProvider.PHPDOC_TAG); + PreferenceConverter.setDefault(store, PHPDOC_LINK, + PHPColorProvider.PHPDOC_LINK); + PreferenceConverter.setDefault(store, PHPDOC_DEFAULT, + PHPColorProvider.PHPDOC_DEFAULT); + + PreferenceConverter.setDefault(store, EDITOR_PHP_KEYWORD_RETURN_COLOR, + new RGB(127, 0, 85)); + store.setDefault(EDITOR_PHP_KEYWORD_RETURN_BOLD, true); + store.setDefault(EDITOR_PHP_KEYWORD_RETURN_ITALIC, false); + + PreferenceConverter.setDefault(store, EDITOR_PHP_OPERATOR_COLOR, + new RGB(0, 0, 0)); + store.setDefault(EDITOR_PHP_OPERATOR_BOLD, false); + store.setDefault(EDITOR_PHP_OPERATOR_ITALIC, false); + + PreferenceConverter.setDefault(store, EDITOR_PHP_BRACE_OPERATOR_COLOR, + new RGB(0, 0, 0)); + store.setDefault(EDITOR_PHP_BRACE_OPERATOR_BOLD, false); + store.setDefault(EDITOR_PHP_BRACE_OPERATOR_ITALIC, false); + + // this will initialize the static fields in the syntaxrdr class + new PHPSyntaxRdr(); + JavaCore.initializeDefaultPluginPreferences(); + PreferenceConstants.initializeDefaultValues(store); + // externalTools.initializeDefaultPreferences(store); + // MarkerAnnotationPreferences.initializeDefaultValues(store); + } + + private IWorkbenchPage internalGetActivePage() { + IWorkbenchWindow window = getWorkbench().getActiveWorkbenchWindow(); + if (window != null) + return window.getActivePage(); + return null; + } + + private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { + if (fImageDescriptorRegistry == null) + fImageDescriptorRegistry = new ImageDescriptorRegistry(); + return fImageDescriptorRegistry; + } /** * Open a file in the Workbench that may or may not exist in the workspace. @@ -821,49 +817,49 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @param filename * @throws CoreException */ -// public ITextEditor openFileInTextEditor(String filename) -// throws CoreException { -// // reject directories -// if (new File(filename).isDirectory()) -// return null; -// IWorkbench workbench = PlatformUI.getWorkbench(); -// IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; -// IWorkbenchPage page = window.getActivePage(); -// IPath path = new Path(filename); -// // If the file exists in the workspace, open it -// IFile file = getWorkspace().getRoot().getFile(path); -// IEditorPart editor; -// ITextEditor textEditor; -// if (file != null && file.exists()) { -// editor = IDE.openEditor(page, file, true); -// textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); -// } else { -// // Otherwise open the stream directly -// if (page == null) -// return null; -// FileStorage storage = new FileStorage(path); -// IEditorRegistry registry = getWorkbench().getEditorRegistry(); -// IEditorDescriptor desc = registry.getDefaultEditor(filename); -// if (desc == null) { -// desc = registry -// .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); -// // desc = registry.getDefaultEditor(); -// } -// IEditorInput input = new ExternalEditorInput(storage); -// editor = page.openEditor(input, desc.getId()); -// textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); -// // If the storage provider is not ours, we can't guarantee -// // read/write. -// if (textEditor != null) { -// IDocumentProvider documentProvider = textEditor -// .getDocumentProvider(); -// if (!(documentProvider instanceof ExternalStorageDocumentProvider)) { -// storage.setReadOnly(); -// } -// } -// } -// return textEditor; -// } + public ITextEditor openFileInTextEditor(String filename) + throws CoreException { + // reject directories + if (new File(filename).isDirectory()) + return null; + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; + IWorkbenchPage page = window.getActivePage(); + IPath path = new Path(filename); + // If the file exists in the workspace, open it + IFile file = getWorkspace().getRoot().getFile(path); + IEditorPart editor; + ITextEditor textEditor; + if (file != null && file.exists()) { + editor = IDE.openEditor(page, file, true); + textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); + } else { + // Otherwise open the stream directly + if (page == null) + return null; + FileStorage storage = new FileStorage(path); + IEditorRegistry registry = getWorkbench().getEditorRegistry(); + IEditorDescriptor desc = registry.getDefaultEditor(filename); + if (desc == null) { + desc = registry + .findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); + // desc = registry.getDefaultEditor(); + } + IEditorInput input = new ExternalEditorInput(storage); + editor = page.openEditor(input, desc.getId()); + textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); + // If the storage provider is not ours, we can't guarantee + // read/write. + if (textEditor != null) { + IDocumentProvider documentProvider = textEditor + .getDocumentProvider(); + if (!(documentProvider instanceof ExternalStorageDocumentProvider)) { + storage.setReadOnly(); + } + } + } + return textEditor; + } /** * Open a file in the Workbench that may or may not exist in the workspace. @@ -873,24 +869,24 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @param line * @throws CoreException */ -// public void openFileAndGotoLine(String filename, int line) -// throws CoreException { -// ITextEditor textEditor = openFileInTextEditor(filename); -// if (textEditor != null) { -// // If a line number was given, go to it -// if (line > 0) { -// try { -// line--; // document is 0 based -// IDocument document = textEditor.getDocumentProvider() -// .getDocument(textEditor.getEditorInput()); -// textEditor.selectAndReveal(document.getLineOffset(line), -// document.getLineLength(line)); -// } catch (BadLocationException e) { -// // invalid text position -> do nothing -// } -// } -// } -// } + public void openFileAndGotoLine(String filename, int line) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a line number was given, go to it + if (line > 0) { + try { + line--; // document is 0 based + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + textEditor.selectAndReveal(document.getLineOffset(line), + document.getLineLength(line)); + } catch (BadLocationException e) { + // invalid text position -> do nothing + } + } + } + } /** * Open a file in the Workbench that may or may not exist in the workspace. @@ -900,282 +896,282 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @param offset * @throws CoreException */ -// public void openFileAndGotoOffset(String filename, int offset, int length) -// throws CoreException { -// ITextEditor textEditor = openFileInTextEditor(filename); -// if (textEditor != null) { -// // If a line number was given, go to it -// if (offset >= 0) { -// IDocument document = textEditor.getDocumentProvider() -// .getDocument(textEditor.getEditorInput()); -// textEditor.selectAndReveal(offset, length); -// } -// } -// } -// -// public void openFileAndFindString(String filename, String findString) -// throws CoreException { -// ITextEditor textEditor = openFileInTextEditor(filename); -// if (textEditor != null) { -// // If a string was given, go to it -// if (findString != null) { -// try { -// IDocument document = textEditor.getDocumentProvider() -// .getDocument(textEditor.getEditorInput()); -// int offset = document.search(0, findString, true, false, -// true); -// textEditor.selectAndReveal(offset, findString.length()); -// } catch (BadLocationException e) { -// // invalid text position -> do nothing -// } -// } -// } -// } + public void openFileAndGotoOffset(String filename, int offset, int length) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a line number was given, go to it + if (offset >= 0) { + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + textEditor.selectAndReveal(offset, length); + } + } + } + + public void openFileAndFindString(String filename, String findString) + throws CoreException { + ITextEditor textEditor = openFileInTextEditor(filename); + if (textEditor != null) { + // If a string was given, go to it + if (findString != null) { + try { + IDocument document = textEditor.getDocumentProvider() + .getDocument(textEditor.getEditorInput()); + int offset = document.search(0, findString, true, false, + true); + textEditor.selectAndReveal(offset, findString.length()); + } catch (BadLocationException e) { + // invalid text position -> do nothing + } + } + } + } public void setLastEditorFile(IFile textEditor) { - //this.fLastEditorFile = textEditor; + this.fLastEditorFile = textEditor; } /* * @see org.eclipse.core.runtime.Plugin#stop */ -// public void stop(BundleContext context) throws Exception { -// try { -// // JavaCore.stop(this, context); -// plugin.savePluginPreferences(); -// IWorkspace workspace = ResourcesPlugin.getWorkspace(); -// workspace.removeResourceChangeListener(JavaModelManager -// .getJavaModelManager().deltaState); -// workspace.removeSaveParticipant(plugin); -// -// JavaModelManager.getJavaModelManager().shutdown(); -// -// // save the information from the php index files if necessary -// Collection collection = fIndexManagerMap.values(); -// Iterator iterator = collection.iterator(); -// IdentifierIndexManager indexManager = null; -// while (iterator.hasNext()) { -// indexManager = (IdentifierIndexManager) iterator.next(); -// indexManager.writeFile(); -// } -// if (fImageDescriptorRegistry != null) -// fImageDescriptorRegistry.dispose(); -// -// // AllTypesCache.terminate(); -// -// if (fImageDescriptorRegistry != null) -// fImageDescriptorRegistry.dispose(); -// -// unregisterAdapters(); -// -// // if (fASTProvider != null) { -// // fASTProvider.dispose(); -// // fASTProvider= null; -// // } -// -// if (fWorkingCopyManager != null) { -// fWorkingCopyManager.shutdown(); -// fWorkingCopyManager = null; -// } -// -// if (fCompilationUnitDocumentProvider != null) { -// fCompilationUnitDocumentProvider.shutdown(); -// fCompilationUnitDocumentProvider = null; -// } -// -// if (fJavaTextTools != null) { -// fJavaTextTools.dispose(); -// fJavaTextTools = null; -// } -// // JavaDocLocations.shutdownJavadocLocations(); -// -// uninstallPreferenceStoreBackwardsCompatibility(); -// -// // RefactoringCore.getUndoManager().shutdown(); -// } finally { -// super.stop(context); -// } -// } + public void stop(BundleContext context) throws Exception { + try { + // JavaCore.stop(this, context); + plugin.savePluginPreferences(); + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + workspace.removeResourceChangeListener(JavaModelManager + .getJavaModelManager().deltaState); + workspace.removeSaveParticipant(plugin); + + JavaModelManager.getJavaModelManager().shutdown(); + + // save the information from the php index files if necessary + Collection collection = fIndexManagerMap.values(); + Iterator iterator = collection.iterator(); + IdentifierIndexManager indexManager = null; + while (iterator.hasNext()) { + indexManager = (IdentifierIndexManager) iterator.next(); + indexManager.writeFile(); + } + if (fImageDescriptorRegistry != null) + fImageDescriptorRegistry.dispose(); + + // AllTypesCache.terminate(); + + if (fImageDescriptorRegistry != null) + fImageDescriptorRegistry.dispose(); + + unregisterAdapters(); + + // if (fASTProvider != null) { + // fASTProvider.dispose(); + // fASTProvider= null; + // } + + if (fWorkingCopyManager != null) { + fWorkingCopyManager.shutdown(); + fWorkingCopyManager = null; + } + + if (fCompilationUnitDocumentProvider != null) { + fCompilationUnitDocumentProvider.shutdown(); + fCompilationUnitDocumentProvider = null; + } + + if (fJavaTextTools != null) { + fJavaTextTools.dispose(); + fJavaTextTools = null; + } + // JavaDocLocations.shutdownJavadocLocations(); + + uninstallPreferenceStoreBackwardsCompatibility(); + + // RefactoringCore.getUndoManager().shutdown(); + } finally { + super.stop(context); + } + } /** * Installs backwards compatibility for the preference store. */ -// private void installPreferenceStoreBackwardsCompatibility() { -// -// /* -// * Installs backwards compatibility: propagate the Java editor font from -// * a pre-2.1 plug-in to the Platform UI's preference store to preserve -// * the Java editor font from a pre-2.1 workspace. This is done only -// * once. -// */ -// String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$ -// if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) -// && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) { -// if (!getPreferenceStore().getBoolean(fontPropagatedKey)) -// PreferenceConverter -// .setValue(PlatformUI.getWorkbench() -// .getPreferenceStore(), -// PreferenceConstants.EDITOR_TEXT_FONT, -// PreferenceConverter.getFontDataArray( -// getPreferenceStore(), -// JFaceResources.TEXT_FONT)); -// } -// getPreferenceStore().setValue(fontPropagatedKey, true); -// -// /* -// * Backwards compatibility: set the Java editor font in this plug-in's -// * preference store to let older versions access it. Since 2.1 the Java -// * editor font is managed by the workbench font preference page. -// */ -// PreferenceConverter.putValue(getPreferenceStore(), -// JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry() -// .getFontData(PreferenceConstants.EDITOR_TEXT_FONT)); -// -// fFontPropertyChangeListener = new IPropertyChangeListener() { -// public void propertyChange(PropertyChangeEvent event) { -// if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event -// .getProperty())) -// PreferenceConverter.putValue(getPreferenceStore(), -// JFaceResources.TEXT_FONT, -// JFaceResources.getFontRegistry().getFontData( -// PreferenceConstants.EDITOR_TEXT_FONT)); -// } -// }; -// JFaceResources.getFontRegistry().addListener( -// fFontPropertyChangeListener); -// } + private void installPreferenceStoreBackwardsCompatibility() { + + /* + * Installs backwards compatibility: propagate the Java editor font from + * a pre-2.1 plug-in to the Platform UI's preference store to preserve + * the Java editor font from a pre-2.1 workspace. This is done only + * once. + */ + String fontPropagatedKey = "fontPropagated"; //$NON-NLS-1$ + if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) + && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) { + if (!getPreferenceStore().getBoolean(fontPropagatedKey)) + PreferenceConverter + .setValue(PlatformUI.getWorkbench() + .getPreferenceStore(), + PreferenceConstants.EDITOR_TEXT_FONT, + PreferenceConverter.getFontDataArray( + getPreferenceStore(), + JFaceResources.TEXT_FONT)); + } + getPreferenceStore().setValue(fontPropagatedKey, true); + + /* + * Backwards compatibility: set the Java editor font in this plug-in's + * preference store to let older versions access it. Since 2.1 the Java + * editor font is managed by the workbench font preference page. + */ + PreferenceConverter.putValue(getPreferenceStore(), + JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry() + .getFontData(PreferenceConstants.EDITOR_TEXT_FONT)); + + fFontPropertyChangeListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event + .getProperty())) + PreferenceConverter.putValue(getPreferenceStore(), + JFaceResources.TEXT_FONT, + JFaceResources.getFontRegistry().getFontData( + PreferenceConstants.EDITOR_TEXT_FONT)); + } + }; + JFaceResources.getFontRegistry().addListener( + fFontPropertyChangeListener); + } /** * Uninstalls backwards compatibility for the preference store. */ -// private void uninstallPreferenceStoreBackwardsCompatibility() { -// JFaceResources.getFontRegistry().removeListener( -// fFontPropertyChangeListener); -// // getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); -// } + private void uninstallPreferenceStoreBackwardsCompatibility() { + JFaceResources.getFontRegistry().removeListener( + fFontPropertyChangeListener); + // getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); + } /* * (non - Javadoc) Method declared in Plugin */ -// public void start(BundleContext context) throws Exception { -// super.start(context); -// -// // JavaCore.start(this, context); -// final JavaModelManager modelManager = JavaModelManager -// .getJavaModelManager(); -// try { -// modelManager.configurePluginDebugOptions(); -// -// // request state folder creation (workaround 19885) -// getStateLocation(); -// // retrieve variable values -// PHPeclipsePlugin.getDefault().getPluginPreferences() -// .addPropertyChangeListener( -// new JavaModelManager.PluginPreferencesListener()); -// // manager.loadVariablesAndContainers(); -// -// final IWorkspace workspace = ResourcesPlugin.getWorkspace(); -// workspace.addResourceChangeListener(modelManager.deltaState, -// IResourceChangeEvent.PRE_BUILD -// | IResourceChangeEvent.POST_BUILD -// | IResourceChangeEvent.POST_CHANGE -// | IResourceChangeEvent.PRE_DELETE -// | IResourceChangeEvent.PRE_CLOSE); -// -// ISavedState savedState = workspace.addSaveParticipant( -// PHPeclipsePlugin.this, modelManager); -// -// // process deltas since last activated in indexer thread so that -// // indexes are up-to-date. -// // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 -//// This causes timeout at EclipseLazyStarter -//// Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$ -//// protected IStatus run(IProgressMonitor monitor) { -//// try { -//// // add save participant and process delta atomically -//// // see -//// // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 -//// workspace.run(new IWorkspaceRunnable() { -//// public void run(IProgressMonitor progress) -//// throws CoreException { -//// ISavedState savedState = workspace -//// .addSaveParticipant( -//// PHPeclipsePlugin.this, -//// modelManager); -//// if (savedState != null) { -//// // the event type coming from the saved -//// // state is always POST_AUTO_BUILD -//// // force it to be POST_CHANGE so that the -//// // delta processor can handle it -//// modelManager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; -//// savedState -//// .processResourceChangeEvents(modelManager.deltaState); -//// } -//// } -//// }, monitor); -//// } catch (CoreException e) { -//// return e.getStatus(); -//// } -//// return Status.OK_STATUS; -//// } -//// }; -//// Replace Job + IWorkspace.run() to WorkspaceJob -// WorkspaceJob processSavedState = new WorkspaceJob( -// Util.bind("savedState.jobName")) { //$NON-NLS-1$ -// public IStatus runInWorkspace(IProgressMonitor monitor) -// throws CoreException { -// ISavedState savedState = workspace.addSaveParticipant( -// PHPeclipsePlugin.this, modelManager); -// if (savedState != null) { -// modelManager.deltaState.getDeltaProcessor().overridenEventType -// = IResourceChangeEvent.POST_CHANGE; -// savedState.processResourceChangeEvents(modelManager.deltaState); + public void start(BundleContext context) throws Exception { + super.start(context); + + // JavaCore.start(this, context); + final JavaModelManager modelManager = JavaModelManager + .getJavaModelManager(); + try { + modelManager.configurePluginDebugOptions(); + + // request state folder creation (workaround 19885) + getStateLocation(); + // retrieve variable values + PHPeclipsePlugin.getDefault().getPluginPreferences() + .addPropertyChangeListener( + new JavaModelManager.PluginPreferencesListener()); + // manager.loadVariablesAndContainers(); + + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + workspace.addResourceChangeListener(modelManager.deltaState, + IResourceChangeEvent.PRE_BUILD + | IResourceChangeEvent.POST_BUILD + | IResourceChangeEvent.POST_CHANGE + | IResourceChangeEvent.PRE_DELETE + | IResourceChangeEvent.PRE_CLOSE); + + ISavedState savedState = workspace.addSaveParticipant( + PHPeclipsePlugin.this, modelManager); + + // process deltas since last activated in indexer thread so that + // indexes are up-to-date. + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 +// This causes timeout at EclipseLazyStarter +// Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$ +// protected IStatus run(IProgressMonitor monitor) { +// try { +// // add save participant and process delta atomically +// // see +// // https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 +// workspace.run(new IWorkspaceRunnable() { +// public void run(IProgressMonitor progress) +// throws CoreException { +// ISavedState savedState = workspace +// .addSaveParticipant( +// PHPeclipsePlugin.this, +// modelManager); +// if (savedState != null) { +// // the event type coming from the saved +// // state is always POST_AUTO_BUILD +// // force it to be POST_CHANGE so that the +// // delta processor can handle it +// modelManager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; +// savedState +// .processResourceChangeEvents(modelManager.deltaState); +// } +// } +// }, monitor); +// } catch (CoreException e) { +// return e.getStatus(); // } // return Status.OK_STATUS; // } // }; -// processSavedState.setSystem(true); -// processSavedState.setPriority(Job.SHORT); // process asap -// processSavedState.schedule(); -// } catch (RuntimeException e) { -// modelManager.shutdown(); -// throw e; -// } -// -// registerAdapters(); -// -// // if (USE_WORKING_COPY_OWNERS) { -// WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { -// public IBuffer createBuffer(ICompilationUnit workingCopy) { -// ICompilationUnit original = workingCopy.getPrimary(); -// IResource resource = original.getResource(); -// if (resource instanceof IFile) -// return new DocumentAdapter(workingCopy, (IFile) resource); -// return DocumentAdapter.NULL; -// } -// }); -// // } -// -// installPreferenceStoreBackwardsCompatibility(); -// -// } -// -// private void registerAdapters() { -// fJavaElementAdapterFactory = new JavaElementAdapterFactory(); -// fResourceAdapterFactory = new ResourceAdapterFactory(); -// -// IAdapterManager manager = Platform.getAdapterManager(); -// manager -// .registerAdapters(fJavaElementAdapterFactory, -// IJavaElement.class); -// manager.registerAdapters(fResourceAdapterFactory, IResource.class); -// } - -// private void unregisterAdapters() { -// IAdapterManager manager = Platform.getAdapterManager(); -// manager.unregisterAdapters(fJavaElementAdapterFactory); -// manager.unregisterAdapters(fResourceAdapterFactory); -// } +// Replace Job + IWorkspace.run() to WorkspaceJob + WorkspaceJob processSavedState = new WorkspaceJob( + Util.bind("savedState.jobName")) { //$NON-NLS-1$ + public IStatus runInWorkspace(IProgressMonitor monitor) + throws CoreException { + ISavedState savedState = workspace.addSaveParticipant( + PHPeclipsePlugin.this, modelManager); + if (savedState != null) { + modelManager.deltaState.getDeltaProcessor().overridenEventType + = IResourceChangeEvent.POST_CHANGE; + savedState.processResourceChangeEvents(modelManager.deltaState); + } + return Status.OK_STATUS; + } + }; + processSavedState.setSystem(true); + processSavedState.setPriority(Job.SHORT); // process asap + processSavedState.schedule(); + } catch (RuntimeException e) { + modelManager.shutdown(); + throw e; + } + + registerAdapters(); + + // if (USE_WORKING_COPY_OWNERS) { + WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { + public IBuffer createBuffer(ICompilationUnit workingCopy) { + ICompilationUnit original = workingCopy.getPrimary(); + IResource resource = original.getResource(); + if (resource instanceof IFile) + return new DocumentAdapter(workingCopy, (IFile) resource); + return DocumentAdapter.NULL; + } + }); + // } + + installPreferenceStoreBackwardsCompatibility(); + + } + + private void registerAdapters() { + fJavaElementAdapterFactory = new JavaElementAdapterFactory(); + fResourceAdapterFactory = new ResourceAdapterFactory(); + + IAdapterManager manager = Platform.getAdapterManager(); + manager + .registerAdapters(fJavaElementAdapterFactory, + IJavaElement.class); + manager.registerAdapters(fResourceAdapterFactory, IResource.class); + } + + private void unregisterAdapters() { + IAdapterManager manager = Platform.getAdapterManager(); + manager.unregisterAdapters(fJavaElementAdapterFactory); + manager.unregisterAdapters(fResourceAdapterFactory); + } /** * Returns a combined preference store, this store is read-only. @@ -1184,19 +1180,19 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * * @since 3.0 */ -// public IPreferenceStore getCombinedPreferenceStore() { -// if (fCombinedPreferenceStore == null) { -// IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); -// fCombinedPreferenceStore = new ChainedPreferenceStore( -// new IPreferenceStore[] { -// getPreferenceStore(), -// new PreferencesAdapter(PHPeclipsePlugin -// .getDefault().getPluginPreferences()), -// generalTextStore }); -// } -// return fCombinedPreferenceStore; -// } -// + public IPreferenceStore getCombinedPreferenceStore() { + if (fCombinedPreferenceStore == null) { + IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); + fCombinedPreferenceStore = new ChainedPreferenceStore( + new IPreferenceStore[] { + getPreferenceStore(), + new PreferencesAdapter(PHPeclipsePlugin + .getDefault().getPluginPreferences()), + generalTextStore }); + } + return fCombinedPreferenceStore; + } + public synchronized IBufferFactory getBufferFactory() { if (fBufferFactory == null) fBufferFactory = new CustomBufferFactory(); @@ -1212,11 +1208,11 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * IJavaFoldingStructureProvider * @since 3.0 */ -// public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() { -// if (fFoldingStructureProviderRegistry == null) -// fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry(); -// return fFoldingStructureProviderRegistry; -// } + public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() { + if (fFoldingStructureProviderRegistry == null) + fFoldingStructureProviderRegistry = new JavaFoldingStructureProviderRegistry(); + return fFoldingStructureProviderRegistry; + } /** * Runs the given action as an atomic Java model operation. @@ -1309,17 +1305,17 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @return the template context type registry for the java plugin * @since 3.0 */ -// public ContextTypeRegistry getTemplateContextRegistry() { -// if (fContextTypeRegistry == null) { -// fContextTypeRegistry = new ContributionContextTypeRegistry(); -// -// fContextTypeRegistry.addContextType(new JavaContextType()); -// fContextTypeRegistry.addContextType(new JavaDocContextType()); -// fContextTypeRegistry.addContextType(new HTMLContextType()); -// } -// -// return fContextTypeRegistry; -// } + public ContextTypeRegistry getTemplateContextRegistry() { + if (fContextTypeRegistry == null) { + fContextTypeRegistry = new ContributionContextTypeRegistry(); + + fContextTypeRegistry.addContextType(new JavaContextType()); + fContextTypeRegistry.addContextType(new JavaDocContextType()); + fContextTypeRegistry.addContextType(new HTMLContextType()); + } + + return fContextTypeRegistry; + } /** * Returns the template store for the java editor templates. @@ -1327,20 +1323,20 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @return the template store for the java editor templates * @since 3.0 */ -// public TemplateStore getTemplateStore() { -// if (fTemplateStore == null) { -// fTemplateStore = new ContributionTemplateStore( -// getTemplateContextRegistry(), getPreferenceStore(), -// TEMPLATES_KEY); -// try { -// fTemplateStore.load(); -// } catch (IOException e) { -// log(e); -// } -// } -// -// return fTemplateStore; -// } + public TemplateStore getTemplateStore() { + if (fTemplateStore == null) { + fTemplateStore = new ContributionTemplateStore( + getTemplateContextRegistry(), getPreferenceStore(), + TEMPLATES_KEY); + try { + fTemplateStore.load(); + } catch (IOException e) { + log(e); + } + } + + return fTemplateStore; + } /** * Returns the template context type registry for the code generation @@ -1350,16 +1346,16 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * templates * @since 3.0 */ -// public ContextTypeRegistry getCodeTemplateContextRegistry() { -// if (fCodeTemplateContextTypeRegistry == null) { -// fCodeTemplateContextTypeRegistry = new ContributionContextTypeRegistry(); -// -// CodeTemplateContextType -// .registerContextTypes(fCodeTemplateContextTypeRegistry); -// } -// -// return fCodeTemplateContextTypeRegistry; -// } + public ContextTypeRegistry getCodeTemplateContextRegistry() { + if (fCodeTemplateContextTypeRegistry == null) { + fCodeTemplateContextTypeRegistry = new ContributionContextTypeRegistry(); + + CodeTemplateContextType + .registerContextTypes(fCodeTemplateContextTypeRegistry); + } + + return fCodeTemplateContextTypeRegistry; + } /** * Returns the template store for the code generation templates. @@ -1367,18 +1363,18 @@ public class PHPeclipsePlugin extends /*AbstractUIPlugin*/Plugin implements * @return the template store for the code generation templates * @since 3.0 */ -// public TemplateStore getCodeTemplateStore() { -// if (fCodeTemplateStore == null) { -// fCodeTemplateStore = new ContributionTemplateStore( -// getCodeTemplateContextRegistry(), getPreferenceStore(), -// CODE_TEMPLATES_KEY); -// try { -// fCodeTemplateStore.load(); -// } catch (IOException e) { -// log(e); -// } -// } -// -// return fCodeTemplateStore; -// } + public TemplateStore getCodeTemplateStore() { + if (fCodeTemplateStore == null) { + fCodeTemplateStore = new ContributionTemplateStore( + getCodeTemplateContextRegistry(), getPreferenceStore(), + CODE_TEMPLATES_KEY); + try { + fCodeTemplateStore.load(); + } catch (IOException e) { + log(e); + } + } + + return fCodeTemplateStore; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java new file mode 100644 index 0000000..f6ec655 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/IncludesScanner.java @@ -0,0 +1,183 @@ +package net.sourceforge.phpeclipse.actions; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; +import net.sourceforge.phpdt.internal.compiler.util.Util; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.Path; +import org.eclipse.ui.IFileEditorInput; + +public class IncludesScanner implements ITerminalSymbols { + // private final PHPOpenAllIncludesEditorAction fOpenAllIncludesAction; + private IProject fProject; + + private IFileEditorInput fEditorInput; + + private HashSet fSet; + + public IncludesScanner(IProject project, IFileEditorInput editorInput) { + fProject = project; + // fOpenAllIncludesAction = action; + fEditorInput = editorInput; + fSet = new HashSet(); + } + + /** + * Add the information for a given IFile resource + * + */ + public void addFile(IFile fileToParse) { + + try { + if (fileToParse.exists()) { + addInputStream(new BufferedInputStream(fileToParse + .getContents()), fileToParse.getProjectRelativePath() + .toString()); + } + } catch (CoreException e1) { + e1.printStackTrace(); + } + } + + private void addInputStream(InputStream stream, String filePath) + throws CoreException { + try { + if (fSet.add(filePath)) { // new entry in set + parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, + null)); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + + /** + * Get the next token from input + */ + private TokenName getNextToken(Scanner scanner) { + TokenName token; + try { + token = scanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = scanner.getCurrentTokenEndPosition(); + int currentStartPosition = scanner + .getCurrentTokenStartPosition(); + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(scanner.toStringAction(token)); + } + return token; + } catch (InvalidInputException e) { + } + return TokenName.ERROR; + } + + private void parseIdentifiers(char[] charArray) { + IFile file; + Scanner scanner = new Scanner(false, false, false, false, true, null, + null, true /* taskCaseSensitive */); + scanner.setSource(charArray); + scanner.setPHPMode(false); + TokenName token = getNextToken(scanner); + try { + while (token != TokenName.EOF) { // && fToken != TokenName.ERROR) { + if (token == TokenName.INCLUDE || token == TokenName.INCLUDE_ONCE + || token == TokenName.REQUIRE + || token == TokenName.REQUIRE_ONCE) { + while (token != TokenName.EOF && token != TokenName.ERROR + && token != TokenName.SEMICOLON + && token != TokenName.RPAREN + && token != TokenName.LBRACE + && token != TokenName.RBRACE) { + token = getNextToken(scanner); + if (token == TokenName.STRINGDOUBLEQUOTE + || token == TokenName.STRINGSINGLEQUOTE) { + char[] includeName = scanner + .getCurrentStringLiteralSource(); + try { + System.out.println(includeName); + file = getIncludeFile(new String(includeName)); + addFile(file); + } catch (Exception e) { + // ignore + } + break; + } + } + } + token = getNextToken(scanner); + } + } catch (SyntaxError e) { + // e.printStackTrace(); + } + } + + private IContainer getWorkingLocation(IFileEditorInput editorInput) { + if (editorInput == null || editorInput.getFile() == null) { + return null; + } + return editorInput.getFile().getParent(); + } + + public IFile getIncludeFile(String relativeFilename) { + IContainer container = getWorkingLocation(fEditorInput); + IFile file = null; + if (relativeFilename.startsWith("../")) { + Path path = new Path(relativeFilename); + file = container.getFile(path); + return file; + } + int index = relativeFilename.lastIndexOf('/'); + + if (index >= 0) { + Path path = new Path(relativeFilename); + file = fProject.getFile(path); + if (file.exists()) { + return file; + } + } + Path path = new Path(relativeFilename); + file = container.getFile(path); + + return file; + } + + /** + * Returns a list of includes + * + * @return the determined list of includes + */ + public List getList() { + ArrayList list = new ArrayList(); + list.addAll(fSet); + return list; + } + + /** + * @return Returns the set. + */ + public Set getSet() { + return fSet; + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java new file mode 100644 index 0000000..6aeb43f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/OpenDeclarationEditorAction.java @@ -0,0 +1,307 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: www.phpeclipse.de + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.actions; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; +import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; +import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; +import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.graphics.Point; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.dialogs.ListSelectionDialog; + +public class OpenDeclarationEditorAction { + + private PHPEditor fEditor; + + private IProject fProject; + + private boolean isIncludeString; + + public OpenDeclarationEditorAction(PHPEditor editor) { + fEditor = editor; + fProject = null; + isIncludeString = false; + } + + /** + * @param selection + */ + protected void openSelectedElement(ITextSelection selection) { + IDocument doc = fEditor.getDocumentProvider().getDocument( + fEditor.getEditorInput()); + int pos = selection.getOffset(); + openSelectedPosition(doc, pos); + } + + protected void openSelectedPosition(IDocument doc, int position) { + IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); + fProject = f.getProject(); + // System.out.println(selection.getText()); + String identifierOrInclude = getIdentifierOrInclude(doc, position); + // System.out.println(word); + if (identifierOrInclude != null && !identifierOrInclude.equals("")) { + if (isIncludeString) { + openIncludeFile(identifierOrInclude); + } else { + openIdentifierDeclaration(f, identifierOrInclude); + } + } + } + + /** + * @param filename + */ + private void openIncludeFile(String filename) { + if (filename != null && !filename.equals("")) { + try { + IFile currentFile = ((IFileEditorInput) fEditor + .getEditorInput()).getFile(); + IPath path = PHPFileUtil.determineFilePath(filename, + currentFile, fProject); + if (path != null) { + //IFile file = PHPFileUtil.createFile(path, fProject); + //if (file != null && file.exists()) { + // PHPeclipsePlugin.getDefault().openFileInTextEditor( + // file.getLocation().toString()); + // return; + //} + PHPeclipsePlugin.getDefault().openFileInTextEditor( + path.toString()); + return; + } + } catch (Exception e) { + // ignore + } + + try { + + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(fProject); + // filename = StringUtil.replaceRegExChars(filename); + List list = indexManager.getFileList(filename); + if (list != null && list.size() > 0) { + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + String workspaceLocation = fProject.getFullPath() + .toString() + + java.io.File.separatorChar; + + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + list, new ListContentProvider(), + new LabelProvider(), "Select the includes to open."); + listSelectionDialog.setTitle("Multiple includes found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog.getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + // PHPIdentifierLocation location = + // (PHPIdentifierLocation) + // locations[i]; + String openFilename = workspaceLocation + + ((String) locations[i]); + PHPeclipsePlugin.getDefault() + .openFileInTextEditor(openFilename); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + } + } catch (Exception e) { + } + + } + return; + } + + /** + * @param f + * @param identiifer + */ + private void openIdentifierDeclaration(IFile f, String identiifer) { + if (identiifer != null && !identiifer.equals("")) { + IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault() + .getIndexManager(fProject); + List locationsList = indexManager.getLocations(identiifer); + if (locationsList != null && locationsList.size() > 0) { + + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot() + // .getLocation().toString(); + + String workspaceLocation = fProject.getFullPath().toString() + + java.io.File.separatorChar; + // TODO show all entries of the list in a dialog box + // at the moment always the first entry will be opened + if (locationsList.size() > 1) { + // determine all includes: + IncludesScanner includesScanner = new IncludesScanner( + fProject, (IFileEditorInput) fEditor + .getEditorInput()); + includesScanner.addFile(f); + Set exactIncludeSet = includesScanner.getSet(); + + PHPIdentifierLocation includeName; + for (int i = 0; i < locationsList.size(); i++) { + includeName = (PHPIdentifierLocation) locationsList + .get(i); + if (exactIncludeSet.contains(includeName.getFilename())) { + includeName + .setMatch(PHPIdentifierLocation.EXACT_MATCH); + } else { + includeName + .setMatch(PHPIdentifierLocation.UNDEFINED_MATCH); + } + } + Collections.sort(locationsList); + + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + locationsList, new ListContentProvider(), + new LabelProvider(), + "Select the resources to open."); + listSelectionDialog.setTitle("Multiple declarations found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog.getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + PHPIdentifierLocation location = (PHPIdentifierLocation) locations[i]; + String filename = workspaceLocation + + location.getFilename(); + // System.out.println(filename); + if (location.getOffset() >= 0) { + PHPeclipsePlugin.getDefault() + .openFileAndGotoOffset( + filename, + location.getOffset(), + identiifer.length()); + } else { + PHPeclipsePlugin.getDefault() + .openFileAndFindString( + filename, identiifer); + } + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } else { + try { + PHPIdentifierLocation location = (PHPIdentifierLocation) locationsList + .get(0); + String filename = workspaceLocation + + location.getFilename(); + // System.out.println(filename); + if (location.getOffset() >= 0) { + PHPeclipsePlugin.getDefault() + .openFileAndGotoOffset(filename, + location.getOffset(), + identiifer.length()); + } else { + PHPeclipsePlugin + .getDefault() + .openFileAndFindString(filename, identiifer); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + } + + private String getIdentifierOrInclude(IDocument doc, int pos) { + // private String getPHPIncludeText(IDocument doc, int pos) { + Point word = null; + int start = -1; + int end = -1; + isIncludeString = false; + try { + // try to find an include string + int position = pos; + char character = ' '; + + while (position >= 0) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + --position; + } + if ((character == '\"') || (character == '\'')) { + start = position; + + position = pos; + int length = doc.getLength(); + character = ' '; + while (position < length) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + ++position; + } + if ((character == '\"') || (character == '\'')) { + start++; + end = position; + + if (end > start) { + word = new Point(start, end - start); // include name + // found + isIncludeString = true; + } + } + } + + // try to find an identifier + if (word == null) { + word = PHPWordExtractor.findWord(doc, pos); // identifier found + isIncludeString = false; + } + } catch (BadLocationException x) { + } + + if (word != null) { + try { + return doc.get(word.x, word.y); + } catch (BadLocationException e) { + } + } + return ""; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPActionMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java new file mode 100644 index 0000000..1b5ca01 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPEclipseShowAction.java @@ -0,0 +1,159 @@ +/*********************************************************************************************************************************** + * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made + * available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - Initial implementation + * www.phpeclipse.de + **********************************************************************************************************************************/ +package net.sourceforge.phpeclipse.actions; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Iterator; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +//import net.sourceforge.phpeclipse.ui.IPreferenceConstants; +import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; +//import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil; +import net.sourceforge.phpeclipse.webbrowser.IWebBrowser; +import net.sourceforge.phpeclipse.webbrowser.internal.BrowserManager; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IObjectActionDelegate; +import org.eclipse.ui.IWorkbenchPart; + +public class PHPEclipseShowAction implements IObjectActionDelegate { + private IWorkbenchPart workbenchPart; + + /** + * Constructor for Action1. + */ + public PHPEclipseShowAction() { + super(); + } + + /** + * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) + */ + public void setActivePart(IAction action, IWorkbenchPart targetPart) { + workbenchPart = targetPart; + } + + public void run(IAction action) { + ISelectionProvider selectionProvider = null; + selectionProvider = workbenchPart.getSite().getSelectionProvider(); + StructuredSelection selection = null; + selection = (StructuredSelection) selectionProvider.getSelection(); + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + Shell shell = null; + Iterator iterator = null; + iterator = selection.iterator(); + while (iterator.hasNext()) { + // obj => selected object in the view + Object obj = iterator.next(); + // is it a resource + if (obj instanceof IResource) { + IResource resource = (IResource) obj; + // check if it's a file resource + switch (resource.getType()) { + case IResource.FILE: + // single file: + IFile previewFile = (IFile) resource; +// String extension = previewFile.getFileExtension() +// .toLowerCase(); +// boolean bringToTopPreview = ProjectPrefUtil +// .getPreviewBooleanValue( +// previewFile, +// IPreferenceConstants.PHP_BRING_TO_TOP_PREVIEW_DEFAULT); + // boolean showHTMLFilesLocal = + // ProjectPrefUtil.getPreviewBooleanValue(previewFile, + // IPreferenceConstants.PHP_SHOW_HTML_FILES_LOCAL); + // boolean showXMLFilesLocal = + // ProjectPrefUtil.getPreviewBooleanValue(previewFile, + // IPreferenceConstants.PHP_SHOW_XML_FILES_LOCAL); +// boolean isHTMLFileName = "html".equals(extension) +// || "htm".equals(extension) +// || "xhtml".equals(extension); +// boolean isXMLFileName = "xml".equals(extension) +// || "xsd".equals(extension) +// || "dtd".equals(extension); + + String localhostURL; + // if (showHTMLFilesLocal && isHTMLFileName) { + // localhostURL = + // "file://"+previewFile.getLocation().toString(); + // } else if (showXMLFilesLocal && isXMLFileName) { + // localhostURL = + // "file://"+previewFile.getLocation().toString(); + // } else + if ((localhostURL = ShowExternalPreviewAction + .getLocalhostURL(store, previewFile)) == null) { + MessageDialog + .openInformation(shell, + "Couldn't create localhost URL", + "Please configure your localhost and documentRoot"); + return; + } + + try { + // if + // (store.getBoolean(PHPeclipsePlugin.USE_EXTERNAL_BROWSER_PREF)) + // { + // String[] arguments = { localhostURL }; + // MessageFormat form = new + // MessageFormat(store.getString(PHPeclipsePlugin.EXTERNAL_BROWSER_PREF)); + // Runtime runtime = Runtime.getRuntime(); + // String command = form.format(arguments); + // // console.write("External Browser command: " + + // command + "\n"); + // runtime.exec(command); + // } else { + open(new URL(localhostURL), shell, localhostURL); + // } + } catch (MalformedURLException e) { + MessageDialog.openInformation(shell, + "MalformedURLException: ", e.toString()); + } + } + } + } + } + + /** + * @see IActionDelegate#selectionChanged(IAction, ISelection) + */ + public void selectionChanged(IAction action, ISelection selection) { + } + + public static void open(final URL url, final Shell shell, + final String dialogTitle) { + // if (WebBrowserUtil.canUseInternalWebBrowser()) { + // IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); + // try { + // IViewPart part = page.findView(BrowserView.ID_BROWSER); + // if (part == null) { + // part = page.showView(BrowserView.ID_BROWSER); + // } else { + // page.bringToTop(part); + // } + // ((BrowserView) part).setUrl(url.toExternalForm()); + // } catch (Exception e) { + // } + // } else { + BrowserManager manager = BrowserManager.getInstance(); + IWebBrowser browser = manager.getCurrentWebBrowser(); + browser.openURL(url); + // } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java new file mode 100644 index 0000000..62e913b --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenAllIncludesEditorAction.java @@ -0,0 +1,242 @@ +/******************************************************************************* + * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This + * program and the accompanying materials are made available under the terms of + * the Common Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: www.phpeclipse.de + ******************************************************************************/ +package net.sourceforge.phpeclipse.actions; + +import java.io.File; +import java.util.List; + +import net.sourceforge.phpdt.internal.ui.viewsupport.ListContentProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +//import org.eclipse.core.runtime.Path; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.graphics.Point; +import org.eclipse.ui.IEditorActionDelegate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +//import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.actions.ActionDelegate; +import org.eclipse.ui.dialogs.ListSelectionDialog; + +public class PHPOpenAllIncludesEditorAction extends ActionDelegate implements + IEditorActionDelegate { + + private IWorkbenchWindow fWindow; + + private PHPEditor fEditor; + + private IProject fProject; + + private IncludesScanner fIncludesScanner; + + public void dispose() { + } + + public void init(IWorkbenchWindow window) { + this.fWindow = window; + } + + public void selectionChanged(IAction action, ISelection selection) { + if (!selection.isEmpty()) { + if (selection instanceof TextSelection) { + action.setEnabled(true); + } else if (fWindow.getActivePage() != null + && fWindow.getActivePage().getActivePart() != null) { + // + } + } + } + +// private IWorkbenchPage getActivePage() { +// IWorkbenchWindow workbenchWindow = fEditor.getEditorSite() +// .getWorkbenchWindow(); +// IWorkbenchPage page = workbenchWindow.getActivePage(); +// return page; +// } + + public IContainer getWorkingLocation(IFileEditorInput editorInput) { + if (editorInput == null || editorInput.getFile() == null) { + return null; + } + return editorInput.getFile().getParent(); + } + +// private IFile getIncludeFile(IProject project, +// IFileEditorInput editorInput, String relativeFilename) { +// IContainer container = getWorkingLocation(editorInput); +// String fullPath = project.getFullPath().toString(); +// IFile file = null; +// if (relativeFilename.startsWith("../")) { +// Path path = new Path(relativeFilename); +// file = container.getFile(path); +// return file; +// } +// int index = relativeFilename.lastIndexOf('/'); +// +// if (index >= 0) { +// Path path = new Path(relativeFilename); +// file = project.getFile(path); +// if (file.exists()) { +// return file; +// } +// } +// +// Path path = new Path(relativeFilename); +// file = container.getFile(path); +// +// return file; +// } + + public void run(IAction action) { + if (fEditor == null) { + IEditorPart targetEditor = fWindow.getActivePage() + .getActiveEditor(); + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } + if (fEditor != null) { + // determine the current Project from a (file-based) Editor + IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile(); + fProject = f.getProject(); + // System.out.println(fProject.toString()); + + ITextSelection selection = (ITextSelection) fEditor + .getSelectionProvider().getSelection(); + IDocument doc = fEditor.getDocumentProvider().getDocument( + fEditor.getEditorInput()); + fIncludesScanner = new IncludesScanner(fProject, + (IFileEditorInput) fEditor.getEditorInput()); + int pos = selection.getOffset(); + // System.out.println(selection.getText()); + String filename = getPHPIncludeText(doc, pos); + + if (filename != null && !filename.equals("")) { + try { + IFile file = fIncludesScanner.getIncludeFile(filename); + fIncludesScanner.addFile(file); + } catch (Exception e) { + // ignore + } + + try { + + List list = fIncludesScanner.getList(); + if (list != null && list.size() > 0) { + // String workspaceLocation = + // PHPeclipsePlugin.getWorkspace().getRoot().getLocation().toString(); + String workspaceLocation = fProject.getFullPath() + .toString() + + File.separatorChar; + + ListSelectionDialog listSelectionDialog = new ListSelectionDialog( + PHPeclipsePlugin.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getShell(), + list, new ListContentProvider(), + new LabelProvider(), + "Select the includes to open."); + listSelectionDialog.setTitle("Multiple includes found"); + if (listSelectionDialog.open() == Window.OK) { + Object[] locations = listSelectionDialog + .getResult(); + if (locations != null) { + try { + for (int i = 0; i < locations.length; i++) { + // PHPIdentifierLocation location = + // (PHPIdentifierLocation) + // locations[i]; + String openFilename = workspaceLocation + + ((String) locations[i]); + PHPeclipsePlugin.getDefault() + .openFileInTextEditor( + openFilename); + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + } + } catch (Exception e) { + } + + } + } + } + + public void setActiveEditor(IAction action, IEditorPart targetEditor) { + if (targetEditor != null && (targetEditor instanceof PHPEditor)) { + fEditor = (PHPEditor) targetEditor; + } + } + + private String getPHPIncludeText(IDocument doc, int pos) { + Point word = null; + int start = -1; + int end = -1; + + try { + + int position = pos; + char character; + + while (position >= 0) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + --position; + } + + start = position; + + position = pos; + int length = doc.getLength(); + + while (position < length) { + character = doc.getChar(position); + if ((character == '\"') || (character == '\'') + || (character == '\r') || (character == '\n')) + break; + ++position; + } + + start++; + end = position; + + if (end > start) + word = new Point(start, end - start); + + } catch (BadLocationException x) { + } + + if (word != null) { + try { + return doc.get(word.x, word.y); + } catch (BadLocationException e) { + } + } + return ""; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/actions/PHPOpenDeclarationEditorAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalEditorInput.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ExternalStorageDocumentProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/FileStorage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/builder/FileStorage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/FileStorage.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java index 9eba696..78a6e2d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java @@ -38,7 +38,7 @@ public class IdentifierIndexManager { public class LineCreator implements ITerminalSymbols { private Scanner fScanner; - private int fToken; + private TokenName fToken; public LineCreator() { fScanner = new Scanner(true, false, false, false, true, null, null, @@ -132,7 +132,7 @@ public class IdentifierIndexManager { { try { getNextToken(); - while (fToken == TokenNameCOMMENT_BLOCK || fToken == TokenNameCOMMENT_PHPDOC) { + while (fToken == TokenName.COMMENT_BLOCK || fToken == TokenName.COMMENT_PHPDOC) { getNextToken(); } } catch (InvalidInputException e1) { @@ -150,33 +150,33 @@ public class IdentifierIndexManager { int phpdocOffset = -1; int phpdocLength = -1; try { - while (fToken != TokenNameEOF && fToken != TokenNameERROR) { + while (fToken != TokenName.EOF && fToken != TokenName.ERROR) { phpdocOffset = -1; hasModifiers = false; - if (fToken == TokenNameCOMMENT_PHPDOC) { + if (fToken == TokenName.COMMENT_PHPDOC) { phpdocOffset = fScanner.getCurrentTokenStartPosition(); phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; getNextToken(); - while (fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate - || fToken == TokenNameabstract) { + while (fToken == TokenName.STATIC + || fToken == TokenName.FINAL + || fToken == TokenName.PUBLIC + || fToken == TokenName.PROTECTED + || fToken == TokenName.PRIVATE + || fToken == TokenName.ABSTRACT) { hasModifiers = true; getNextToken(); } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { + if (fToken == TokenName.EOF || fToken == TokenName.ERROR) { break; } } - if (fToken == TokenNamefunction) { + if (fToken == TokenName.FUNCTION) { skipComments(); - if (fToken == TokenNameAND) { + if (fToken == TokenName.OP_AND) { getNextToken(); } - if (fToken == TokenNameIdentifier) { + if (fToken == TokenName.IDENTIFIER) { ident = fScanner.getCurrentIdentifierSource(); if (parent != null && equalCharArrays(parent, ident)) { @@ -197,36 +197,36 @@ public class IdentifierIndexManager { skipComments(); parseDeclarations(null, buf, true); } - } else if (fToken == TokenNameclass - || fToken == TokenNameinterface) { + } else if (fToken == TokenName.CLASS + || fToken == TokenName.INTERFACE) { skipComments(); - if (fToken == TokenNameIdentifier) { + if (fToken == TokenName.IDENTIFIER) { ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); skipComments(); - if (fToken == TokenNameextends) { + if (fToken == TokenName.EXTENDS) { skipComments(); - while (fToken == TokenNameIdentifier) { + while (fToken == TokenName.IDENTIFIER) { ident = fScanner .getCurrentIdentifierSource(); // extends ident addIdentifierInformation('e', ident, buf); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); } } } - if (fToken == TokenNameimplements) { + if (fToken == TokenName.IMPLEMENTS) { skipComments(); - while (fToken == TokenNameIdentifier) { + while (fToken == TokenName.IDENTIFIER) { ident = fScanner .getCurrentIdentifierSource(); // implements ident addIdentifierInformation('e', ident, buf); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); // getNextToken(); } @@ -235,28 +235,28 @@ public class IdentifierIndexManager { // skip tokens for classname, extends and others // until we have // the opening '{' - while (fToken != TokenNameLBRACE - && fToken != TokenNameEOF - && fToken != TokenNameERROR) { + while (fToken != TokenName.LBRACE + && fToken != TokenName.EOF + && fToken != TokenName.ERROR) { getNextToken(); } parseDeclarations(ident, buf, true); } - } else if (fToken == TokenNamevar || hasModifiers - || fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate) { - while (fToken == TokenNamevar - || fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate) { + } else if (fToken == TokenName.VAR || hasModifiers + || fToken == TokenName.STATIC + || fToken == TokenName.FINAL + || fToken == TokenName.PUBLIC + || fToken == TokenName.PROTECTED + || fToken == TokenName.PRIVATE) { + while (fToken == TokenName.VAR + || fToken == TokenName.STATIC + || fToken == TokenName.FINAL + || fToken == TokenName.PUBLIC + || fToken == TokenName.PROTECTED + || fToken == TokenName.PRIVATE) { skipComments(); } - while (fToken == TokenNameVariable) { + while (fToken == TokenName.VARIABLE) { ident = fScanner.getCurrentIdentifierSource(); classVariable = new char[ident.length - 1]; System.arraycopy(ident, 1, classVariable, 0, @@ -264,26 +264,26 @@ public class IdentifierIndexManager { addClassVariableInformation('v', classVariable, buf, phpdocOffset, phpdocLength); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); } } - } else if (!hasModifiers && fToken == TokenNameIdentifier) { + } else if (!hasModifiers && fToken == TokenName.IDENTIFIER) { ident = fScanner.getCurrentIdentifierSource(); getNextToken(); if (ident.length == 6 && ident[0] == 'd' && ident[1] == 'e' && ident[2] == 'f' && ident[3] == 'i' && ident[4] == 'n' && ident[5] == 'e') { - if (fToken == TokenNameLPAREN) { + if (fToken == TokenName.LPAREN) { getNextToken(); - if (fToken == TokenNameStringDoubleQuote) { + if (fToken == TokenName.STRINGDOUBLEQUOTE) { ident = fScanner .getCurrentStringLiteralSource(); addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); getNextToken(); - } else if (fToken == TokenNameStringSingleQuote) { + } else if (fToken == TokenName.STRINGSINGLEQUOTE) { ident = fScanner .getCurrentStringLiteralSource(); addIdentifierInformation('d', ident, buf, @@ -292,24 +292,24 @@ public class IdentifierIndexManager { } } } - } else if (fToken == TokenNameglobal) { + } else if (fToken == TokenName.GLOBAL) { // global variable - while (fToken != TokenNameEOF - && fToken != TokenNameERROR - && fToken != TokenNameSEMICOLON - && fToken != TokenNameLBRACE - && fToken != TokenNameRBRACE) { + while (fToken != TokenName.EOF + && fToken != TokenName.ERROR + && fToken != TokenName.SEMICOLON + && fToken != TokenName.LBRACE + && fToken != TokenName.RBRACE) { getNextToken(); - if (fToken == TokenNameVariable) { + if (fToken == TokenName.VARIABLE) { ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('g', ident, buf, phpdocOffset, phpdocLength); } } - } else if (fToken == TokenNameLBRACE) { + } else if (fToken == TokenName.LBRACE) { getNextToken(); counter++; - } else if (fToken == TokenNameRBRACE) { + } else if (fToken == TokenName.RBRACE) { getNextToken(); --counter; if (counter == 0 && goBack) { @@ -336,92 +336,92 @@ public class IdentifierIndexManager { int phpdocLength = -1; fScanner.setSource(charArray); fScanner.setPHPMode(false); - fToken = TokenNameEOF; + fToken = TokenName.EOF; try { getNextToken(); - while (fToken != TokenNameEOF) { // && fToken != - // TokenNameERROR) { + while (fToken != TokenName.EOF) { // && fToken != + // TokenName.ERROR) { phpdocOffset = -1; hasModifiers = false; switch (fToken) { - case TokenNameCOMMENT_PHPDOC: + case COMMENT_PHPDOC: phpdocOffset = fScanner.getCurrentTokenStartPosition(); phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; getNextToken(); - while (fToken == TokenNamestatic - || fToken == TokenNamefinal - || fToken == TokenNamepublic - || fToken == TokenNameprotected - || fToken == TokenNameprivate - || fToken == TokenNameabstract) { + while (fToken == TokenName.STATIC + || fToken == TokenName.FINAL + || fToken == TokenName.PUBLIC + || fToken == TokenName.PROTECTED + || fToken == TokenName.PRIVATE + || fToken == TokenName.ABSTRACT) { hasModifiers = true; getNextToken(); } - if (fToken == TokenNameEOF || fToken == TokenNameERROR) { + if (fToken == TokenName.EOF || fToken == TokenName.ERROR) { break; } break; - case TokenNamefunction: + case FUNCTION: skipComments(); - if (fToken == TokenNameAND) { + if (fToken == TokenName.OP_AND) { getNextToken(); } - if (fToken == TokenNameIdentifier) { + if (fToken == TokenName.IDENTIFIER) { ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('f', ident, buf, phpdocOffset, phpdocLength); skipComments(); - if (fToken == TokenNameLPAREN) { + if (fToken == TokenName.LPAREN) { skipComments(); do { - if (fToken == TokenNameVariable) { + if (fToken == TokenName.VARIABLE) { ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('v', ident, buf, phpdocOffset, phpdocLength); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); } } getNextToken (); - } while ((fToken != TokenNameRPAREN) && (fToken != 0)); + } while ((fToken != TokenName.RPAREN) && (fToken.compareTo (TokenName.EOF) > 0)); } parseDeclarations(null, buf, true); } break; - case TokenNameclass: - case TokenNameinterface: + case CLASS: + case INTERFACE: skipComments(); - if (fToken == TokenNameIdentifier) { + if (fToken == TokenName.IDENTIFIER) { ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); skipComments(); - if (fToken == TokenNameextends) { + if (fToken == TokenName.EXTENDS) { skipComments(); - while (fToken == TokenNameIdentifier) { + while (fToken == TokenName.IDENTIFIER) { ident = fScanner .getCurrentIdentifierSource(); // extends ident addIdentifierInformation('e', ident, buf); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); } } } - if (fToken == TokenNameimplements) { + if (fToken == TokenName.IMPLEMENTS) { skipComments(); - while (fToken == TokenNameIdentifier) { + while (fToken == TokenName.IDENTIFIER) { ident = fScanner .getCurrentIdentifierSource(); // implements ident addIdentifierInformation('e', ident, buf); skipComments(); - if (fToken == TokenNameCOMMA) { + if (fToken == TokenName.COMMA) { skipComments(); } } @@ -429,16 +429,16 @@ public class IdentifierIndexManager { // skip fTokens for classname, extends and others // until we have // the opening '{' - while (fToken != TokenNameLBRACE - && fToken != TokenNameEOF - && fToken != TokenNameERROR) { + while (fToken != TokenName.LBRACE + && fToken != TokenName.EOF + && fToken != TokenName.ERROR) { getNextToken(); } parseDeclarations(ident, buf, true); } break; - case TokenNameVariable: + case VARIABLE: // global variable ident = fScanner.getCurrentIdentifierSource(); addIdentifierInformation('g', ident, buf, phpdocOffset, diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnoreSet.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorIgnores.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java new file mode 100644 index 0000000..604132f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass1Exporter.java @@ -0,0 +1,257 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.obfuscator; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; +import net.sourceforge.phpdt.internal.compiler.util.Util; +import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +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.IPath; +//import org.eclipse.jface.preference.IPreferenceStore; + +/** + * Analyzing php files in a first pass over all resources ! + */ +public class ObfuscatorPass1Exporter implements ITerminalSymbols { + + protected Scanner fScanner; + + protected TokenName fToken; + + protected HashMap fIdentifierMap; + + public ObfuscatorPass1Exporter(Scanner scanner, HashMap identifierMap) { + fScanner = scanner; + fIdentifierMap = identifierMap; + } + + /** + * Get the next token from input + */ + private void getNextToken() { + + try { + fToken = fScanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = fScanner.getCurrentTokenEndPosition(); + int currentStartPosition = fScanner + .getCurrentTokenStartPosition(); + + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(fScanner.toStringAction(fToken)); + } + return; + } catch (InvalidInputException e) { + + } + fToken = TokenName.ERROR; + } + + private void parseIdentifiers(boolean goBack) { + //char[] ident; + String identifier; + PHPIdentifier value; + int counter = 0; + +// IPreferenceStore store = PHPeclipsePlugin.getDefault() +// .getPreferenceStore(); + try { + while (fToken != TokenName.EOF && fToken != TokenName.ERROR) { + if (fToken == TokenName.VARIABLE) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value == null) { + fIdentifierMap.put(identifier, new PHPIdentifier(null, + PHPIdentifier.VARIABLE)); + } + getNextToken(); + // } else if (fToken == TokenNamefunction) { + // getNextToken(); + // if (fToken == TokenNameAND) { + // getNextToken(); + // } + // if (fToken == TokenNameIdentifier) { + // ident = fScanner.getCurrentIdentifierSource(); + // outlineInfo.addVariable(new String(ident)); + // temp = new PHPFunctionDeclaration(current, new + // String(ident), fScanner.getCurrentTokenStartPosition()); + // current.add(temp); + // getNextToken(); + // parseDeclarations(outlineInfo, temp, true); + // } + // } else if (fToken == TokenNameclass) { + // getNextToken(); + // if (fToken == TokenNameIdentifier) { + // ident = fScanner.getCurrentIdentifierSource(); + // outlineInfo.addVariable(new String(ident)); + // temp = new PHPClassDeclaration(current, new + // String(ident), fScanner.getCurrentTokenStartPosition()); + // current.add(temp); + // getNextToken(); + // + // //skip fTokens for classname, extends and others until we + // have the opening '{' + // while (fToken != TokenNameLBRACE && fToken != + // TokenNameEOF && fToken != TokenNameERROR) { + // getNextToken(); + // } + // parseDeclarations(outlineInfo, temp, true); + // // stack.pop(); + // } + } else if (fToken == TokenName.STRINGDOUBLEQUOTE) { + char currentCharacter; + int i = fScanner.startPosition; + ArrayList varList = new ArrayList(); + + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (currentCharacter == '$' + && fScanner.source[i - 2] != '\\') { + StringBuffer varName = new StringBuffer(); + varName.append("$"); + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (!Scanner + .isPHPIdentifierPart(currentCharacter)) { + break; // while loop + } + varName.append(currentCharacter); + } + varList.add(varName.toString()); + } + } + + for (i = 0; i < varList.size(); i++) { + identifier = (String) varList.get(i); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value == null) { + fIdentifierMap.put(identifier, new PHPIdentifier( + null, PHPIdentifier.VARIABLE)); + } + } + + getNextToken(); + } else if (fToken == TokenName.LBRACE) { + getNextToken(); + counter++; + } else if (fToken == TokenName.RBRACE) { + getNextToken(); + --counter; + if (counter == 0 && goBack) { + return; + } + } else { + getNextToken(); + } + } + } catch (SyntaxError sytaxErr) { + // do nothing + } + } + + /** + * Do nothing in first pass + */ + public void createFolder(IPath destinationPath) { + // do nothing here + // new File(destinationPath.toOSString()).mkdir(); + } + + /** + * Writes the passed resource to the specified location recursively + */ + public void write(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else + writeChildren((IContainer) resource, destinationPath); + } + + /** + * Exports the passed container's children + */ + protected void writeChildren(IContainer folder, IPath destinationPath) + throws CoreException, IOException { + if (folder.isAccessible()) { + IResource[] children = folder.members(); + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + writeResource(child, destinationPath.append(child.getName())); + } + } + } + + /** + * Analyzes the passed file resource for the PHP obfuscator + */ + protected void writeFile(IFile file, IPath destinationPath) + throws IOException, CoreException { + if (!PHPFileUtil.isPHPFile(file)) { + return; + } + InputStream stream = null; + char[] charArray = null; + try { + stream = new BufferedInputStream(file.getContents()); + charArray = Util.getInputStreamAsCharArray(stream, -1, null); + } catch (IOException e) { + return; + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + + if (charArray == null) { + // TODO show error message + return; + } + /* fScanner initialization */ + fScanner.setSource(charArray); + fScanner.setPHPMode(false); + fToken = TokenName.EOF; + getNextToken(); + parseIdentifiers(false); + } + + /** + * Writes the passed resource to the specified location recursively + */ + protected void writeResource(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else { + createFolder(destinationPath); + writeChildren((IContainer) resource, destinationPath); + } + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java new file mode 100644 index 0000000..b143f41 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/ObfuscatorPass2Exporter.java @@ -0,0 +1,381 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.obfuscator; + +import java.io.BufferedInputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; + +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; +import net.sourceforge.phpdt.internal.compiler.util.Util; +import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +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.IPath; +//import org.eclipse.jface.preference.IPreferenceStore; + +/** + * Helper class for exporting resources to the file system. + */ +public class ObfuscatorPass2Exporter implements ITerminalSymbols { + private Scanner fScanner; + + private TokenName fToken; + + private int fCounter; + + protected HashMap fIdentifierMap; + + public ObfuscatorPass2Exporter(Scanner scanner, HashMap identifierMap) { + fScanner = scanner; + fIdentifierMap = identifierMap; + fCounter = 0; + } + + /** + * gets the next token from input + */ + private void getNextToken() { + + try { + fToken = fScanner.getNextToken(); + if (Scanner.DEBUG) { + int currentEndPosition = fScanner.getCurrentTokenEndPosition(); + int currentStartPosition = fScanner + .getCurrentTokenStartPosition(); + + System.out.print(currentStartPosition + "," + + currentEndPosition + ": "); + System.out.println(fScanner.toStringAction(fToken)); + } + return; + } catch (InvalidInputException e) { + + } + fToken = TokenName.ERROR; + } + + private boolean obfuscate(StringBuffer buf) { + //char[] ident; + String identifier; + PHPIdentifier value; + + int startPosition = 0; + int lastPosition = 0; + +// IPreferenceStore store = PHPeclipsePlugin.getDefault() +// .getPreferenceStore(); + try { + while (fToken != TokenName.EOF && fToken != TokenName.ERROR) { + if (fToken == TokenName.VARIABLE) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + buf.append("$v" + Integer.toString(fCounter)); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + buf.append(obfuscatedIdentifier); + } + // System.out.println(hexString.toString()); + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + } else if (fToken == TokenName.IDENTIFIER) { + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get(identifier); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + buf.append("_" + Integer.toString(fCounter)); + value.setIdentifier("_" + + Integer.toString(fCounter++)); + } else { + buf.append(obfuscatedIdentifier); + } + // System.out.println(hexString.toString()); + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + + } else if (fToken == TokenName.COMMENT_LINE + || fToken == TokenName.COMMENT_BLOCK + || fToken == TokenName.COMMENT_PHPDOC) { + lastPosition = fScanner.startPosition; + buf.append(fScanner.source, startPosition, lastPosition + - startPosition); + startPosition = fScanner.currentPosition; + getNextToken(); + } else if (fToken == TokenName.STRINGDOUBLEQUOTE) { + char currentCharacter; + int i = fScanner.startPosition; + ArrayList varList = new ArrayList(); + + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (currentCharacter == '$' + && fScanner.source[i - 2] != '\\') { + StringBuffer varName = new StringBuffer(); + varName.append("$"); + while (i < fScanner.currentPosition) { + currentCharacter = fScanner.source[i++]; + if (!Scanner + .isPHPIdentifierPart(currentCharacter)) { + break; // while loop + } + varName.append(currentCharacter); + } + varList.add(varName.toString()); + } + } + StringBuffer stringLiteral = new StringBuffer(); + stringLiteral.append(fScanner.source, + fScanner.startPosition, fScanner.currentPosition + - fScanner.startPosition); + String stringIdent; + String replacement; + int index; + + for (int j = 0; j < varList.size(); j++) { + stringIdent = (String) varList.get(j); + len = stringIdent.length(); + value = (PHPIdentifier) fIdentifierMap.get(stringIdent); + if (value != null) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + replacement = "$v" + Integer.toString(fCounter); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + replacement = obfuscatedIdentifier; + } + // System.out.println(hexString.toString()); + } else { + replacement = stringIdent; + } + index = stringLiteral.indexOf(stringIdent); + if (index >= 0) { + if (index > 0 + && stringLiteral.charAt(index - 1) != '\\') { + stringLiteral.replace(index, index + + stringIdent.length(), replacement); + } else if (index == 0) { + stringLiteral.replace(index, index + + stringIdent.length(), replacement); + } + } + } + buf.append(stringLiteral); + startPosition = fScanner.currentPosition; + getNextToken(); + } + if (fToken == TokenName.MINUS_GREATER) { // i.e. $this->var_name + getNextToken(); + if (fToken == TokenName.IDENTIFIER) { + // assuming this is a dereferenced variable + identifier = new String(fScanner + .getCurrentIdentifierSource()); + lastPosition = fScanner.startPosition; + int len = lastPosition - startPosition; + buf.append(fScanner.source, startPosition, len); + value = (PHPIdentifier) fIdentifierMap.get("$" + + identifier); + if (value != null && value.isVariable()) { + String obfuscatedIdentifier = value.getIdentifier(); + if (obfuscatedIdentifier == null) { + // note: don't place a $ before the identifier + buf.append("v" + Integer.toString(fCounter)); + value.setIdentifier("$v" + + Integer.toString(fCounter++)); + } else { + if (obfuscatedIdentifier.charAt(0) == '$') { + buf.append(obfuscatedIdentifier + .substring(1)); + } else { + buf.append(obfuscatedIdentifier); + } + } + } else { + buf.append(identifier); + } + startPosition = fScanner.currentPosition; + getNextToken(); + } + + } else { + getNextToken(); + } + } + if (startPosition < fScanner.source.length) { + buf.append(fScanner.source, startPosition, + fScanner.source.length - startPosition); + } + return true; + } catch (SyntaxError sytaxErr) { + // do nothing + } + + return false; + } + + /** + * Creates the specified file system directory at + * destinationPath. This creates a new file system + * directory. + */ + public void createFolder(IPath destinationPath) { + new File(destinationPath.toOSString()).mkdir(); + } + + /** + * Writes the passed resource to the specified location recursively + */ + public void write(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else + writeChildren((IContainer) resource, destinationPath); + } + + /** + * Exports the passed container's children + */ + protected void writeChildren(IContainer folder, IPath destinationPath) + throws CoreException, IOException { + if (folder.isAccessible()) { + IResource[] children = folder.members(); + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + writeResource(child, destinationPath.append(child.getName())); + } + } + } + + /** + * Writes the passed file resource to the specified destination on the local + * file system + */ + protected void writeFile(IFile file, IPath destinationPath) + throws IOException, CoreException { + if (PHPFileUtil.isPHPFile(file)) { + InputStream stream = null; + char[] charArray = null; + try { + stream = new BufferedInputStream(file.getContents()); + charArray = Util.getInputStreamAsCharArray(stream, -1, null); + } catch (IOException e) { + return; + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + + if (charArray == null) { + // TODO show error message + return; + } + + fScanner.setSource(charArray); + fScanner.setPHPMode(false); + fToken = TokenName.EOF; + getNextToken(); + + StringBuffer buf = new StringBuffer(); + if (!obfuscate(buf)) { + copyFile(file, destinationPath); + } else { + // charArray = buf.toString().toCharArray(); + // File targetFile = new File(destinationPath.toOSString()); + BufferedWriter bw = new BufferedWriter(new FileWriter( + destinationPath.toOSString())); + bw.write(buf.toString()); + bw.close(); + } + + } else { + copyFile(file, destinationPath); + } + } + + private void copyFile(IFile file, IPath destinationPath) + throws FileNotFoundException, CoreException, IOException { + FileOutputStream output = null; + InputStream contentStream = null; + + try { + output = new FileOutputStream(destinationPath.toOSString()); + contentStream = file.getContents(false); + int chunkSize = contentStream.available(); + byte[] readBuffer = new byte[chunkSize]; + int n = contentStream.read(readBuffer); + + while (n > 0) { + output.write(readBuffer); + n = contentStream.read(readBuffer); + } + } finally { + if (output != null) + output.close(); + if (contentStream != null) + contentStream.close(); + } + } + + /** + * Writes the passed resource to the specified location recursively + */ + protected void writeResource(IResource resource, IPath destinationPath) + throws CoreException, IOException { + if (resource.getType() == IResource.FILE) + writeFile((IFile) resource, destinationPath); + else { + createFolder(destinationPath); + writeChildren((IContainer) resource, destinationPath); + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/default-obfuscator.xml b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/default-obfuscator.xml similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/default-obfuscator.xml rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/default-obfuscator.xml diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportMessages.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java new file mode 100644 index 0000000..3f7f44b --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportOperation.java @@ -0,0 +1,741 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.obfuscator.export; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.obfuscator.ObfuscatorIgnores; +import net.sourceforge.phpeclipse.obfuscator.ObfuscatorPass1Exporter; +import net.sourceforge.phpeclipse.obfuscator.ObfuscatorPass2Exporter; + +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.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.operation.ModalContext; +//import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.dialogs.IOverwriteQuery; + +/** + * Operation for exporting the contents of a resource to the local file system. + */ +/* package */ +class ObfuscatorExportOperation implements IRunnableWithProgress { + private IPath fPath; + + private IProgressMonitor fMonitor; + + private ObfuscatorPass1Exporter fExporter1 = null; + + private ObfuscatorPass2Exporter fExporter2 = null; + + private HashMap fCurrentIdentifierMap = null; + + private HashMap fProjectMap = null; + + private String fCurrentProjectName = ""; + + private List fResourcesToExport; + + private IOverwriteQuery fOverwriteCallback; + + private IResource fResource; + + private List errorTable = new ArrayList(1); + + // The constants for the overwrite 3 state + private static final int OVERWRITE_NOT_SET = 0; + + private static final int OVERWRITE_NONE = 1; + + private static final int OVERWRITE_ALL = 2; + + private int overwriteState = OVERWRITE_NOT_SET; + + // private boolean createLeadupStructure = true; + private boolean createContainerDirectories = true; + + /** + * Create an instance of this class. Use this constructor if you wish to + * export specific resources without a common parent resource + */ + // public ObfuscatorExportOperation(List resources, String destinationPath, + // IOverwriteQuery overwriteImplementor) { + // super(); + // + // exporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), + // identifierMap); + // exporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), + // identifierMap); + // identifierMap = null; + // + // // Eliminate redundancies in list of resources being exported + // Iterator elementsEnum = resources.iterator(); + // while (elementsEnum.hasNext()) { + // IResource currentResource = (IResource) elementsEnum.next(); + // if (isDescendent(resources, currentResource)) + // elementsEnum.remove(); //Remove currentResource + // } + // + // resourcesToExport = resources; + // path = new Path(destinationPath); + // overwriteCallback = overwriteImplementor; + // } + /** + * Create an instance of this class. Use this constructor if you wish to + * recursively export a single resource + */ + public ObfuscatorExportOperation(IResource res, String destinationPath, + IOverwriteQuery overwriteImplementor) { + super(); + + fResource = res; + fPath = new Path(destinationPath); + fOverwriteCallback = overwriteImplementor; + } + + /** + * Create an instance of this class. Use this constructor if you wish to + * export specific resources with a common parent resource (affects + * container directory creation) + */ + public ObfuscatorExportOperation(IResource res, List resources, + String destinationPath, IOverwriteQuery overwriteImplementor) { + this(res, destinationPath, overwriteImplementor); + fResourcesToExport = resources; + } + + /** + * Add a new entry to the error table with the passed information + */ + protected void addError(String message, Throwable e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + message, e)); + } + + /** + * Answer the total number of file resources that exist at or below self in + * the resources hierarchy. + * + * @return int + * @param resource + * org.eclipse.core.resources.IResource + */ + protected int countChildrenOf(IResource resource) throws CoreException { + if (resource.getType() == IResource.FILE) + return 1; + + int count = 0; + if (resource.isAccessible()) { + IResource[] children = ((IContainer) resource).members(); + for (int i = 0; i < children.length; i++) + count += countChildrenOf(children[i]); + } + + return count; + } + + /** + * Answer a boolean indicating the number of file resources that were + * specified for export + * + * @return int + */ + protected int countSelectedResources() throws CoreException { + int result = 0; + Iterator resources = fResourcesToExport.iterator(); + + while (resources.hasNext()) + result += countChildrenOf((IResource) resources.next()); + + return result; + } + + /** + * Create the directories required for exporting the passed resource, based + * upon its container hierarchy + * + * @param resource + * org.eclipse.core.resources.IResource + */ + protected void createLeadupDirectoriesFor(IResource resource) { + IPath resourcePath = resource.getFullPath().removeLastSegments(1); + + for (int i = 0; i < resourcePath.segmentCount(); i++) { + fPath = fPath.append(resourcePath.segment(i)); + fExporter2.createFolder(fPath); + } + } + + /** + * Recursively export the previously-specified resource + */ + protected void exportAllResources1() throws InterruptedException { + if (fResource.getType() == IResource.FILE) { + exportFile1((IFile) fResource, fPath); + } else { + try { + setExporters(fResource); + exportChildren1(((IContainer) fResource).members(), fPath); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because the file system export wizard + // ensures that the + // single resource chosen for export is both existent and + // accessible + errorTable.add(e); + } + } + } + + /** + * Recursively export the previously-specified resource + */ + protected void exportAllResources2() throws InterruptedException { + if (fResource.getType() == IResource.FILE) { + exportFile2((IFile) fResource, fPath); + } else { + try { + setExporters(fResource); + exportChildren2(((IContainer) fResource).members(), fPath); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because the file system export wizard + // ensures that the + // single resource chosen for export is both existent and + // accessible + errorTable.add(e); + } + } + } + + /** + * Export all of the resources contained in the passed collection + * + * @param children + * java.util.Enumeration + * @param currentPath + * IPath + */ + protected void exportChildren1(IResource[] children, IPath currentPath) + throws InterruptedException { + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + if (!child.isAccessible()) + continue; + + if (child.getType() == IResource.FILE) + exportFile1((IFile) child, currentPath); + else { + IPath destination = currentPath.append(child.getName()); + fExporter1.createFolder(destination); + try { + exportChildren1(((IContainer) child).members(), destination); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because: + // i. this method is called recursively iterating over the + // result of #members, + // which only answers existing children + // ii. there is an #isAccessible check done before #members + // is invoked + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Export all of the resources contained in the passed collection + * + * @param children + * java.util.Enumeration + * @param currentPath + * IPath + */ + protected void exportChildren2(IResource[] children, IPath currentPath) + throws InterruptedException { + for (int i = 0; i < children.length; i++) { + IResource child = children[i]; + if (!child.isAccessible()) + continue; + + if (child.getType() == IResource.FILE) + exportFile2((IFile) child, currentPath); + else { + IPath destination = currentPath.append(child.getName()); + fExporter2.createFolder(destination); + try { + exportChildren2(((IContainer) child).members(), destination); + } catch (CoreException e) { + // not safe to show a dialog + // should never happen because: + // i. this method is called recursively iterating over the + // result of #members, + // which only answers existing children + // ii. there is an #isAccessible check done before #members + // is invoked + errorTable.add(e.getStatus()); + } + } + } + } + + protected void exportFile1(IFile file, IPath location) + throws InterruptedException { + IPath fullPath = location.append(file.getName()); + fMonitor.subTask(file.getFullPath().toString()); + //String properPathString = fullPath.toOSString(); + //File targetFile = new File(properPathString); + + // if (targetFile.exists()) { + // if (!targetFile.canWrite()) { + // errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + // ObfuscatorExportMessages.format("ObfuscatorTransfer.cannotOverwrite", + // //$NON-NLS-1$ + // new Object[] { targetFile.getAbsolutePath()}), null)); + // monitor.worked(1); + // return; + // } + // + // if (overwriteState == OVERWRITE_NONE) + // return; + // + // if (overwriteState != OVERWRITE_ALL) { + // String overwriteAnswer = + // overwriteCallback.queryOverwrite(properPathString); + // + // if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) + // throw new InterruptedException(); + // + // if (overwriteAnswer.equals(IOverwriteQuery.NO)) { + // monitor.worked(1); + // return; + // } + // + // if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { + // monitor.worked(1); + // overwriteState = OVERWRITE_NONE; + // return; + // } + // + // if (overwriteAnswer.equals(IOverwriteQuery.ALL)) + // overwriteState = OVERWRITE_ALL; + // } + // } + + try { + setExporters(file); + fExporter1.write(file, fullPath); + } catch (IOException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } catch (CoreException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } + + fMonitor.worked(1); + ModalContext.checkCanceled(fMonitor); + } + + /** + * Export the passed file to the specified location + * + * @param file + * org.eclipse.core.resources.IFile + * @param location + * org.eclipse.core.runtime.IPath + */ + protected void exportFile2(IFile file, IPath location) + throws InterruptedException { + IPath fullPath = location.append(file.getName()); + fMonitor.subTask(file.getFullPath().toString()); + String properPathString = fullPath.toOSString(); + File targetFile = new File(properPathString); + + if (targetFile.exists()) { + if (!targetFile.canWrite()) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, + 0, ObfuscatorExportMessages.format( + "ObfuscatorTransfer.cannotOverwrite", //$NON-NLS-1$ + new Object[] { targetFile.getAbsolutePath() }), + null)); + fMonitor.worked(1); + return; + } + + if (overwriteState == OVERWRITE_NONE) + return; + + if (overwriteState != OVERWRITE_ALL) { + String overwriteAnswer = fOverwriteCallback + .queryOverwrite(properPathString); + + if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) + throw new InterruptedException(); + + if (overwriteAnswer.equals(IOverwriteQuery.NO)) { + fMonitor.worked(1); + return; + } + + if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) { + fMonitor.worked(1); + overwriteState = OVERWRITE_NONE; + return; + } + + if (overwriteAnswer.equals(IOverwriteQuery.ALL)) + overwriteState = OVERWRITE_ALL; + } + } + + try { + setExporters(file); + fExporter2.write(file, fullPath); + } catch (IOException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } catch (CoreException e) { + errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, + ObfuscatorExportMessages.format( + "ObfuscatorTransfer.errorExporting", //$NON-NLS-1$ + new Object[] { fullPath, e.getMessage() }), e)); + } + + fMonitor.worked(1); + ModalContext.checkCanceled(fMonitor); + } + + protected void exportSpecifiedResources1() throws InterruptedException { + Iterator resources = fResourcesToExport.iterator(); + IPath initPath = (IPath) fPath.clone(); + + while (resources.hasNext()) { + IResource currentResource = (IResource) resources.next(); + if (!currentResource.isAccessible()) + continue; + setExporters(currentResource); + fPath = initPath; + + if (fResource == null) { + // No root resource specified and creation of containment + // directories + // is required. Create containers from depth 2 onwards (ie.- + // project's + // child inclusive) for each resource being exported. + // if (createLeadupStructure) + // createLeadupDirectoriesFor(currentResource); + + } else { + // Root resource specified. Must create containment directories + // from this point onwards for each resource being exported + IPath containersToCreate = currentResource.getFullPath() + .removeFirstSegments( + fResource.getFullPath().segmentCount()) + .removeLastSegments(1); + + for (int i = 0; i < containersToCreate.segmentCount(); i++) { + fPath = fPath.append(containersToCreate.segment(i)); + fExporter1.createFolder(fPath); + } + } + + if (currentResource.getType() == IResource.FILE) + exportFile1((IFile) currentResource, fPath); + else { + if (createContainerDirectories) { + fPath = fPath.append(currentResource.getName()); + fExporter1.createFolder(fPath); + } + + try { + exportChildren1(((IContainer) currentResource).members(), + fPath); + } catch (CoreException e) { + // should never happen because #isAccessible is called + // before #members is invoked, + // which implicitly does an existence check + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Export the resources contained in the previously-defined + * resourcesToExport collection + */ + protected void exportSpecifiedResources2() throws InterruptedException { + Iterator resources = fResourcesToExport.iterator(); + IPath initPath = (IPath) fPath.clone(); + + while (resources.hasNext()) { + IResource currentResource = (IResource) resources.next(); + if (!currentResource.isAccessible()) + continue; + setExporters(currentResource); + + fPath = initPath; + + if (fResource == null) { + // No root resource specified and creation of containment + // directories + // is required. Create containers from depth 2 onwards (ie.- + // project's + // child inclusive) for each resource being exported. + // if (createLeadupStructure) + // createLeadupDirectoriesFor(currentResource); + + } else { + // Root resource specified. Must create containment directories + // from this point onwards for each resource being exported + IPath containersToCreate = currentResource.getFullPath() + .removeFirstSegments( + fResource.getFullPath().segmentCount()) + .removeLastSegments(1); + + for (int i = 0; i < containersToCreate.segmentCount(); i++) { + fPath = fPath.append(containersToCreate.segment(i)); + fExporter2.createFolder(fPath); + } + } + + if (currentResource.getType() == IResource.FILE) + exportFile2((IFile) currentResource, fPath); + else { + if (createContainerDirectories) { + fPath = fPath.append(currentResource.getName()); + fExporter2.createFolder(fPath); + } + + try { + exportChildren2(((IContainer) currentResource).members(), + fPath); + } catch (CoreException e) { + // should never happen because #isAccessible is called + // before #members is invoked, + // which implicitly does an existence check + errorTable.add(e.getStatus()); + } + } + } + } + + /** + * Returns the status of the export operation. If there were any errors, the + * result is a status object containing individual status objects for each + * error. If there were no errors, the result is a status object with error + * code OK. + * + * @return the status + */ + public IStatus getStatus() { + IStatus[] errors = new IStatus[errorTable.size()]; + errorTable.toArray(errors); + return new MultiStatus( + PlatformUI.PLUGIN_ID, + IStatus.OK, + errors, + ObfuscatorExportMessages + .getString("ObfuscatorExportOperation.problemsExporting"), //$NON-NLS-1$ + null); + } + + /** + * Answer a boolean indicating whether the passed child is a descendent of + * one or more members of the passed resources collection + * + * @return boolean + * @param resources + * java.util.List + * @param child + * org.eclipse.core.resources.IResource + */ + protected boolean isDescendent(List resources, IResource child) { + if (child.getType() == IResource.PROJECT) + return false; + + IResource parent = child.getParent(); + if (resources.contains(parent)) + return true; + + return isDescendent(resources, parent); + } + + private void setExporters(IResource resource) { + if (fCurrentIdentifierMap == null) { + if (fProjectMap == null) { + fProjectMap = new HashMap(); + } + createExporters(resource); + } else { + IProject project = resource.getProject(); + if (!fCurrentProjectName.equals(project.getName())) { + HashMap temp = (HashMap) fProjectMap.get(project.getName()); + if (temp != null) { + fCurrentProjectName = project.getName(); + fCurrentIdentifierMap = temp; + fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, + false), fCurrentIdentifierMap); + fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, + true), fCurrentIdentifierMap); + return; + } + createExporters(resource); + } + } + } + + private void createExporters(IResource resource) { + IProject project = resource.getProject(); +// IPreferenceStore store = PHPeclipsePlugin.getDefault() +// .getPreferenceStore(); + ObfuscatorIgnores ignore = new ObfuscatorIgnores(project); + fCurrentIdentifierMap = ignore.getIdentifierMap(); + fCurrentProjectName = project.getName(); + fProjectMap.put(fCurrentProjectName, fCurrentIdentifierMap); + fExporter1 = new ObfuscatorPass1Exporter(new Scanner(false, false), + fCurrentIdentifierMap); + fExporter2 = new ObfuscatorPass2Exporter(new Scanner(true, true), + fCurrentIdentifierMap); + } + + /** + * Export the resources that were previously specified for export (or if a + * single resource was specified then export it recursively) + */ + public void run(IProgressMonitor monitor) throws InterruptedException { + this.fMonitor = monitor; + final IPath tempPath = (IPath) fPath.clone(); + if (fResource != null) { + setExporters(fResource); + // if (createLeadupStructure) + // createLeadupDirectoriesFor(resource); + + if (createContainerDirectories + && fResource.getType() != IResource.FILE) { + // ensure it's a container + fPath = fPath.append(fResource.getName()); + fExporter2.createFolder(fPath); + } + } + + try { + // reset variables for this run: + fCurrentIdentifierMap = null; + fProjectMap = null; + fCurrentProjectName = ""; + + // count number of files + int totalWork = IProgressMonitor.UNKNOWN; + try { + if (fResourcesToExport == null) { + totalWork = countChildrenOf(fResource); + } else { + totalWork = countSelectedResources(); + } + } catch (CoreException e) { + // Should not happen + errorTable.add(e.getStatus()); + } + monitor + .beginTask( + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.exportingTitle1"), totalWork); //$NON-NLS-1$ + if (fResourcesToExport == null) { + exportAllResources1(); + } else { + exportSpecifiedResources1(); + } + + // try { + // if (resourcesToExport == null) + // totalWork = countChildrenOf(resource); + // else + // totalWork = countSelectedResources(); + // } catch (CoreException e) { + // // Should not happen + // errorTable.add(e.getStatus()); + // } + + // reset path: + fPath = tempPath; + monitor + .beginTask( + ObfuscatorExportMessages + .getString("ObfuscatorTransfer.exportingTitle2"), totalWork); //$NON-NLS-1$ + if (fResourcesToExport == null) { + exportAllResources2(); + } else { + exportSpecifiedResources2(); + } + } finally { + monitor.done(); + } + } + + /** + * Set this boolean indicating whether a directory should be created for + * Folder resources that are explicitly passed for export + * + * @param value + * boolean + */ + // public void setCreateContainerDirectories(boolean value) { + // createContainerDirectories = value; + // } + /** + * Set this boolean indicating whether each exported resource's complete + * path should include containment hierarchies as dictated by its parents + * + * @param value + * boolean + */ + // public void setCreateLeadupStructure(boolean value) { + // createLeadupStructure = value; + // } + /** + * Set this boolean indicating whether exported resources should + * automatically overwrite existing files when a conflict occurs. If not + * query the user. + * + * @param value + * boolean + */ + public void setOverwriteFiles(boolean value) { + if (value) + overwriteState = OVERWRITE_ALL; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/ObfuscatorExportWizard.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/WizardObfuscatorResourceExportPage1.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/messages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/messages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/obfuscator/export/messages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/export/messages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/AnnotationType.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicEditorActionContributor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BasicJavaEditorActionContributor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/BracketPainter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitAnnotationModelEvent.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/CompilationUnitEditorActionContributor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorHighlightingSynchronizer.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java new file mode 100644 index 0000000..33d847c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/EditorUtility.java @@ -0,0 +1,436 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.IWorkingCopy; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.ui.JavaUI; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.action.Action; +import org.eclipse.swt.SWT; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * A number of routines for working with JavaElements in editors + * + * Use 'isOpenInEditor' to test if an element is already open in a editor Use + * 'openInEditor' to force opening an element in a editor With 'getWorkingCopy' + * you get the working copy (element in the editor) of an element + */ +public class EditorUtility { + +// public static boolean isEditorInput(Object element, IEditorPart editor) { +// if (editor != null) { +// try { +// return editor.getEditorInput().equals(getEditorInput(element)); +// } catch (JavaModelException x) { +// PHPeclipsePlugin.log(x.getStatus()); +// } +// } +// return false; +// } + + /** + * Tests if a cu is currently shown in an editor + * + * @return the IEditorPart if shown, null if element is not open in an + * editor + */ +// public static IEditorPart isOpenInEditor(Object inputElement) { +// IEditorInput input = null; +// +// try { +// input = getEditorInput(inputElement); +// } catch (JavaModelException x) { +// PHPeclipsePlugin.log(x.getStatus()); +// } +// +// if (input != null) { +// IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); +// if (p != null) { +// return p.findEditor(input); +// } +// } +// +// return null; +// } + + /** + * Opens a Java editor for an element such as IJavaElement, + * IFile, or IStorage. The editor is + * activated by default. + * + * @return the IEditorPart or null if wrong element type or opening failed + */ + public static IEditorPart openInEditor(Object inputElement) + throws JavaModelException, PartInitException { + return openInEditor(inputElement, true); + } + + /** + * Opens a Java editor for an element (IJavaElement, IFile, IStorage...) + * + * @return the IEditorPart or null if wrong element type or opening failed + */ + public static IEditorPart openInEditor(Object inputElement, boolean activate) + throws JavaModelException, PartInitException { + + if (inputElement instanceof IFile) + return openInEditor((IFile) inputElement, activate); + + IEditorInput input = getEditorInput(inputElement); + if (input instanceof IFileEditorInput) { + IFileEditorInput fileInput = (IFileEditorInput) input; + return openInEditor(fileInput.getFile(), activate); + } + + if (input != null) + return openInEditor(input, getEditorID(input, inputElement), + activate); + + return null; + } + + /** + * Selects a Java Element in an editor + */ + public static void revealInEditor(IEditorPart part, IJavaElement element) { + if (element != null && part instanceof PHPEditor) { + ((PHPEditor) part).setSelection(element); + } + } + + private static IEditorPart openInEditor(IFile file, boolean activate) + throws PartInitException { + if (file != null) { + IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); + if (p != null) { + IEditorPart editorPart = IDE.openEditor(p, file, activate); + initializeHighlightRange(editorPart); + return editorPart; + } + } + return null; + } + + private static IEditorPart openInEditor(IEditorInput input, + String editorID, boolean activate) throws PartInitException { + if (input != null) { + IWorkbenchPage p = PHPeclipsePlugin.getActivePage(); + if (p != null) { + IEditorPart editorPart = p + .openEditor(input, editorID, activate); + initializeHighlightRange(editorPart); + return editorPart; + } + } + return null; + } + + private static void initializeHighlightRange(IEditorPart editorPart) { + if (editorPart instanceof ITextEditor) { + TogglePresentationAction toggleAction = new TogglePresentationAction(); + // Initialize editor + toggleAction.setEditor((ITextEditor) editorPart); + // Reset action + toggleAction.setEditor(null); + } + } + + /** + * @deprecated Made it public again for java debugger UI. + */ + public static String getEditorID(IEditorInput input, Object inputObject) { + IEditorRegistry registry = PlatformUI.getWorkbench() + .getEditorRegistry(); + IEditorDescriptor descriptor = registry.getDefaultEditor(input + .getName()); + if (descriptor != null) + return descriptor.getId(); + return null; + } + + private static IEditorInput getEditorInput(IJavaElement element) + throws JavaModelException { + while (element != null) { + if (element instanceof IWorkingCopy + && ((IWorkingCopy) element).isWorkingCopy()) + element = ((IWorkingCopy) element).getOriginalElement(); + + if (element instanceof ICompilationUnit) { + ICompilationUnit unit = (ICompilationUnit) element; + IResource resource = unit.getResource(); + if (resource instanceof IFile) + return new FileEditorInput((IFile) resource); + } + + // if (element instanceof IClassFile) + // return new InternalClassFileEditorInput((IClassFile) element); + // + element = element.getParent(); + } + + return null; + } + + public static IEditorInput getEditorInput(Object input) + throws JavaModelException { + + if (input instanceof IJavaElement) + return getEditorInput((IJavaElement) input); + + if (input instanceof IFile) + return new FileEditorInput((IFile) input); + + // if (input instanceof IStorage) + // return new JarEntryEditorInput((IStorage)input); + + return null; + } + + /** + * If the current active editor edits a java element return it, else return + * null + */ +// public static IJavaElement getActiveEditorJavaInput() { +// IWorkbenchPage page = PHPeclipsePlugin.getActivePage(); +// if (page != null) { +// IEditorPart part = page.getActiveEditor(); +// if (part != null) { +// IEditorInput editorInput = part.getEditorInput(); +// if (editorInput != null) { +// return (IJavaElement) editorInput +// .getAdapter(IJavaElement.class); +// } +// } +// } +// return null; +// } + + /** + * Gets the working copy of an compilation unit opened in an editor + * + * @param part + * the editor part + * @param cu + * the original compilation unit (or another working copy) + * @return the working copy of the compilation unit, or null if not found + */ + public static ICompilationUnit getWorkingCopy(ICompilationUnit cu) { + if (cu == null) + return null; + if (cu.isWorkingCopy()) + return cu; + + return (ICompilationUnit) cu.findSharedWorkingCopy(JavaUI + .getBufferFactory()); + } + + /** + * Gets the working copy of an member opened in an editor + * + * @param member + * the original member or a member in a working copy + * @return the corresponding member in the shared working copy or + * null if not found + */ +// public static IMember getWorkingCopy(IMember member) +// throws JavaModelException { +// ICompilationUnit cu = member.getCompilationUnit(); +// if (cu != null) { +// ICompilationUnit workingCopy = getWorkingCopy(cu); +// if (workingCopy != null) { +// return JavaModelUtil.findMemberInCompilationUnit(workingCopy, +// member); +// } +// } +// return null; +// } + + /** + * Returns the compilation unit for the given java element. + * + * @param element + * the java element whose compilation unit is searched for + * @return the compilation unit of the given java element + */ + private static ICompilationUnit getCompilationUnit(IJavaElement element) { + + if (element == null) + return null; + + if (element instanceof IMember) + return ((IMember) element).getCompilationUnit(); + + int type = element.getElementType(); + if (IJavaElement.COMPILATION_UNIT == type) + return (ICompilationUnit) element; + if (IJavaElement.CLASS_FILE == type) + return null; + + return getCompilationUnit(element.getParent()); + } + + /** + * Returns the working copy of the given java element. + * + * @param javaElement + * the javaElement for which the working copyshould be found + * @param reconcile + * indicates whether the working copy must be reconcile prior to + * searching it + * @return the working copy of the given element or null if + * none + */ + public static IJavaElement getWorkingCopy(IJavaElement element, + boolean reconcile) throws JavaModelException { + ICompilationUnit unit = getCompilationUnit(element); + if (unit == null) + return null; + + if (unit.isWorkingCopy()) + return element; + + ICompilationUnit workingCopy = getWorkingCopy(unit); + if (workingCopy != null) { + if (reconcile) { + synchronized (workingCopy) { + workingCopy.reconcile(); + return JavaModelUtil.findInCompilationUnit(workingCopy, + element); + } + } else { + return JavaModelUtil + .findInCompilationUnit(workingCopy, element); + } + } + + return null; + } + + /** + * Maps the localized modifier name to a code in the same manner as + * #findModifier. + * + * @return the SWT modifier bit, or 0 if no match was found + * @see findModifier + * @since 2.1.1 + */ + public static int findLocalizedModifier(String token) { + if (token == null) + return 0; + + if (token.equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) + return SWT.CTRL; + if (token.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) + return SWT.SHIFT; + if (token.equalsIgnoreCase(Action.findModifierString(SWT.ALT))) + return SWT.ALT; + if (token.equalsIgnoreCase(Action.findModifierString(SWT.COMMAND))) + return SWT.COMMAND; + + return 0; + } + + /** + * Returns the modifier string for the given SWT modifier modifier bits. + * + * @param stateMask + * the SWT modifier bits + * @return the modifier string + * @since 2.1.1 + */ + public static String getModifierString(int stateMask) { + String modifierString = ""; //$NON-NLS-1$ + if ((stateMask & SWT.CTRL) == SWT.CTRL) + modifierString = appendModifierString(modifierString, SWT.CTRL); + if ((stateMask & SWT.ALT) == SWT.ALT) + modifierString = appendModifierString(modifierString, SWT.ALT); + if ((stateMask & SWT.SHIFT) == SWT.SHIFT) + modifierString = appendModifierString(modifierString, SWT.SHIFT); + if ((stateMask & SWT.COMMAND) == SWT.COMMAND) + modifierString = appendModifierString(modifierString, SWT.COMMAND); + + return modifierString; + } + + /** + * Appends to modifier string of the given SWT modifier bit to the given + * modifierString. + * + * @param modifierString + * the modifier string + * @param modifier + * an int with SWT modifier bit + * @return the concatenated modifier string + * @since 2.1.1 + */ + private static String appendModifierString(String modifierString, + int modifier) { + if (modifierString == null) + modifierString = ""; //$NON-NLS-1$ + String newModifierString = Action.findModifierString(modifier); + if (modifierString.length() == 0) + return newModifierString; + return PHPEditorMessages + .getFormattedString( + "EditorUtility.concatModifierStrings", new String[] { modifierString, newModifierString }); //$NON-NLS-1$ + } + + /** + * Returns the Java project for a given editor input or null + * if no corresponding Java project exists. + * + * @param input + * the editor input + * @return the corresponding Java project + * + * @since 3.0 + */ + public static IJavaProject getJavaProject(IEditorInput input) { + IJavaProject jProject = null; + if (input instanceof IFileEditorInput) { + IProject project = ((IFileEditorInput) input).getFile() + .getProject(); + if (project != null) { + jProject = JavaCore.create(project); + if (!jProject.exists()) + jProject = null; + } + } + // else if (input instanceof IClassFileEditorInput) { + // jProject= + // ((IClassFileEditorInput)input).getClassFile().getJavaProject(); + // } + return jProject; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoAnnotationAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/GotoErrorAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java new file mode 100644 index 0000000..3e07d2c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/HTMLDocumentSetupParticipant.java @@ -0,0 +1,37 @@ +/********************************************************************** + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.filebuffers.IDocumentSetupParticipant; +import org.eclipse.jface.text.IDocument; + +/** + * The document setup participant for PHPDT. + */ +public class HTMLDocumentSetupParticipant implements IDocumentSetupParticipant { + + public HTMLDocumentSetupParticipant() { + } + + /* + * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) + */ + public void setup(IDocument document) { + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupHTMLDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, + // null); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ICompilationUnitDocumentProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaAnnotation.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IJavaEditorActionConstants.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPainter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IPositionManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/IProblemAnnotation.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ISavePolicy.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationImageProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaAnnotationIterator.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentFactory.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java new file mode 100644 index 0000000..ce4929a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaDocumentSetupParticipant.java @@ -0,0 +1,40 @@ +/********************************************************************** + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.filebuffers.IDocumentSetupParticipant; +import org.eclipse.jface.text.IDocument; + +/** + * The document setup participant for PHPDT. + */ +public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant { + + public JavaDocumentSetupParticipant() { + } + + /* + * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) + */ + public void setup(IDocument document) { + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + + // tools.setupJavaDocumentPartitioner(document, + // IPHPPartitions.PHP_PARTITIONING, null); + // //IPHPPartitions.PHP_PARTITIONING, null); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java new file mode 100644 index 0000000..cde8050 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaEditorErrorTickUpdater.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.internal.ui.viewsupport.IProblemChangedListener; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaUILabelProvider; +import net.sourceforge.phpdt.ui.ProblemsLabelDecorator; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IResource; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; + +/** + * The JavaEditorErrorTickUpdater will register as a + * IProblemChangedListener to listen on problem changes of the editor's input. + * It updates the title images when the annotation model changed. + */ +public class JavaEditorErrorTickUpdater implements IProblemChangedListener { + + private PHPEditor fJavaEditor; + + private JavaUILabelProvider fLabelProvider; + + public JavaEditorErrorTickUpdater(PHPEditor editor) { + Assert.isNotNull(editor); + fJavaEditor = editor; + fLabelProvider = new JavaUILabelProvider(0, + JavaElementImageProvider.SMALL_ICONS); + fLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null)); + PHPeclipsePlugin.getDefault().getProblemMarkerManager().addListener( + this); + } + + /* + * (non-Javadoc) + * + * @see IProblemChangedListener#problemsChanged(IResource[], boolean) + */ + public void problemsChanged(IResource[] changedResources, + boolean isMarkerChange) { + if (isMarkerChange) { + return; + } + IEditorInput input = fJavaEditor.getEditorInput(); + if (input != null) { // might run async, tests needed + IJavaElement jelement = (IJavaElement) input + .getAdapter(IJavaElement.class); + if (jelement != null) { + IResource resource = jelement.getResource(); + for (int i = 0; i < changedResources.length; i++) { + if (changedResources[i].equals(resource)) { + updateEditorImage(jelement); + } + } + } + } + } + + public void updateEditorImage(IJavaElement jelement) { + Image titleImage = fJavaEditor.getTitleImage(); + if (titleImage == null) { + return; + } + Image newImage = fLabelProvider.getImage(jelement); + if (titleImage != newImage) { + postImageChange(newImage); + } + } + + private void postImageChange(final Image newImage) { + Shell shell = fJavaEditor.getEditorSite().getShell(); + if (shell != null && !shell.isDisposed()) { + shell.getDisplay().syncExec(new Runnable() { + public void run() { + fJavaEditor.updatedTitleImage(newImage); + } + }); + } + } + + public void dispose() { + fLabelProvider.dispose(); + PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener( + this); + } + +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaMarkerAnnotation.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java new file mode 100644 index 0000000..a8c8a0f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java @@ -0,0 +1,1429 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; +import java.util.ResourceBundle; +import java.util.Vector; + +import net.sourceforge.phpdt.core.ElementChangedEvent; +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IElementChangedListener; +import net.sourceforge.phpdt.core.IField; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaElementDelta; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IParent; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.actions.AbstractToggleLinkingAction; +import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; +import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache; +import net.sourceforge.phpdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels; +import net.sourceforge.phpdt.internal.ui.viewsupport.StatusBarUpdater; +import net.sourceforge.phpdt.ui.JavaElementSorter; +import net.sourceforge.phpdt.ui.JavaUI; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; +import net.sourceforge.phpdt.ui.actions.CustomFiltersActionGroup; +import net.sourceforge.phpdt.ui.actions.GenerateActionGroup; +import net.sourceforge.phpdt.ui.actions.MemberFilterActionGroup; +import net.sourceforge.phpdt.ui.actions.PHPdtActionConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.IMenuListener; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.action.IStatusLineManager; +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.IBaseLabelProvider; +import org.eclipse.jface.viewers.IPostSelectionProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProviderChangedEvent; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jface.viewers.ViewerFilter; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.BusyIndicator; +//import org.eclipse.swt.dnd.DND; +//import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.Tree; +import org.eclipse.swt.widgets.Widget; +import org.eclipse.ui.IActionBars; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.actions.ActionContext; +import org.eclipse.ui.actions.ActionFactory; +import org.eclipse.ui.actions.ActionGroup; +import org.eclipse.ui.model.IWorkbenchAdapter; +import org.eclipse.ui.model.WorkbenchAdapter; +import org.eclipse.ui.part.IPageSite; +import org.eclipse.ui.part.IShowInSource; +import org.eclipse.ui.part.IShowInTarget; +import org.eclipse.ui.part.IShowInTargetList; +import org.eclipse.ui.part.Page; +import org.eclipse.ui.part.ShowInContext; +import org.eclipse.ui.texteditor.GotoAnnotationAction; +import org.eclipse.ui.texteditor.ITextEditorActionConstants; +import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; +import org.eclipse.ui.texteditor.IUpdate; +import org.eclipse.ui.texteditor.TextEditorAction; +import org.eclipse.ui.views.contentoutline.IContentOutlinePage; +//import org.eclipse.ui.views.navigator.LocalSelectionTransfer; + +/** + * The content outline page of the Java editor. The viewer implements a + * proprietary update mechanism based on Java model deltas. It does not react on + * domain changes. It is specified to show the content of ICompilationUnits and + * IClassFiles. Publishes its context menu under + * PHPeclipsePlugin.getDefault().getPluginId() + ".outline". + */ +public class JavaOutlinePage extends Page implements IContentOutlinePage, + IAdaptable, IPostSelectionProvider { + + static Object[] NO_CHILDREN = new Object[0]; + + /** + * The element change listener of the java outline viewer. + * + * @see IElementChangedListener + */ + class ElementChangedListener implements IElementChangedListener { + + public void elementChanged(final ElementChangedEvent e) { + + if (getControl() == null) + return; + + Display d = getControl().getDisplay(); + if (d != null) { + d.asyncExec(new Runnable() { + public void run() { + //ICompilationUnit cu = (ICompilationUnit) fInput; + //IJavaElement base = cu; + // if (fTopLevelTypeOnly) { + // base= getMainType(cu); + // if (base == null) { + if (fOutlineViewer != null) + fOutlineViewer.refresh(true); + return; + // } + // } + // IJavaElementDelta delta= findElement(base, + // e.getDelta()); + // if (delta != null && fOutlineViewer != null) { + // fOutlineViewer.reconcile(delta); + // } + } + }); + } + } + + private boolean isPossibleStructuralChange(IJavaElementDelta cuDelta) { + if (cuDelta.getKind() != IJavaElementDelta.CHANGED) { + return true; // add or remove + } + int flags = cuDelta.getFlags(); + if ((flags & IJavaElementDelta.F_CHILDREN) != 0) { + return true; + } + return (flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT; + } + + protected IJavaElementDelta findElement(IJavaElement unit, + IJavaElementDelta delta) { + + if (delta == null || unit == null) + return null; + + IJavaElement element = delta.getElement(); + + if (unit.equals(element)) { + if (isPossibleStructuralChange(delta)) { + return delta; + } + return null; + } + + if (element.getElementType() > IJavaElement.CLASS_FILE) + return null; + + IJavaElementDelta[] children = delta.getAffectedChildren(); + if (children == null || children.length == 0) + return null; + + for (int i = 0; i < children.length; i++) { + IJavaElementDelta d = findElement(unit, children[i]); + if (d != null) + return d; + } + + return null; + } + } + + static class NoClassElement extends WorkbenchAdapter implements IAdaptable { + /* + * @see java.lang.Object#toString() + */ + public String toString() { + return PHPEditorMessages + .getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) + */ + public Object getAdapter(Class clas) { + if (clas == IWorkbenchAdapter.class) + return this; + return null; + } + } + + /** + * Content provider for the children of an ICompilationUnit or an IClassFile + * + * @see ITreeContentProvider + */ + class ChildrenProvider implements ITreeContentProvider { + + private Object[] NO_CLASS = new Object[] { new NoClassElement() }; + + private ElementChangedListener fListener; + + protected boolean matches(IJavaElement element) { + if (element.getElementType() == IJavaElement.METHOD) { + String name = element.getElementName(); + return (name != null && name.indexOf('<') >= 0); + } + return false; + } + + protected IJavaElement[] filter(IJavaElement[] children) { + boolean initializers = false; + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) { + initializers = true; + break; + } + } + + if (!initializers) + return children; + + Vector v = new Vector(); + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) + continue; + v.addElement(children[i]); + } + + IJavaElement[] result = new IJavaElement[v.size()]; + v.copyInto(result); + return result; + } + + public Object[] getChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + return filter(c.getChildren()); + } catch (JavaModelException x) { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 + // don't log NotExist exceptions as this is a valid case + // since we might have been posted and the element + // removed in the meantime. + if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) + PHPeclipsePlugin.log(x); + } + } + return NO_CHILDREN; + } + + public Object[] getElements(Object parent) { + if (fTopLevelTypeOnly) { + if (parent instanceof ICompilationUnit) { + try { + IType type = getMainType((ICompilationUnit) parent); + return type != null ? type.getChildren() : NO_CLASS; + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); + } + } + // else if (parent instanceof IClassFile) { + // try { + // IType type= getMainType((IClassFile) parent); + // return type != null ? type.getChildren() : NO_CLASS; + // } catch (JavaModelException e) { + // PHPeclipsePlugin.log(e); + // } + // } + } + return getChildren(parent); + } + + public Object getParent(Object child) { + if (child instanceof IJavaElement) { + IJavaElement e = (IJavaElement) child; + return e.getParent(); + } + return null; + } + + public boolean hasChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + IJavaElement[] children = filter(c.getChildren()); + return (children != null && children.length > 0); + } catch (JavaModelException x) { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38341 + // don't log NotExist exceptions as this is a valid case + // since we might have been posted and the element + // removed in the meantime. + if (PHPeclipsePlugin.isDebug() || !x.isDoesNotExist()) + PHPeclipsePlugin.log(x); + } + } + return false; + } + + public boolean isDeleted(Object o) { + return false; + } + + public void dispose() { + if (fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } + + /* + * @see IContentProvider#inputChanged(Viewer, Object, Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + boolean isCU = (newInput instanceof ICompilationUnit); + + if (isCU && fListener == null) { + fListener = new ElementChangedListener(); + JavaCore.addElementChangedListener(fListener); + } else if (!isCU && fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } + } + + class JavaOutlineViewer extends TreeViewer { + + /** + * Indicates an item which has been reused. At the point of its reuse it + * has been expanded. This field is used to communicate between + * internalExpandToLevel and reuseTreeItem. + */ + private Item fReusedExpandedItem; + + private boolean fReorderedMembers; + + private boolean fForceFireSelectionChanged; + + public JavaOutlineViewer(Tree tree) { + super(tree); + setAutoExpandLevel(ALL_LEVELS); + setUseHashlookup(true); + } + + /** + * Investigates the given element change event and if affected + * incrementally updates the Java outline. + * + * @param delta + * the Java element delta used to reconcile the Java outline + */ + public void reconcile(IJavaElementDelta delta) { + fReorderedMembers = false; + fForceFireSelectionChanged = false; + if (getSorter() == null) { + if (fTopLevelTypeOnly && delta.getElement() instanceof IType + && (delta.getKind() & IJavaElementDelta.ADDED) != 0) { + refresh(true); + + } else { + Widget w = findItem(fInput); + if (w != null && !w.isDisposed()) + update(w, delta); + if (fForceFireSelectionChanged) + fireSelectionChanged(new SelectionChangedEvent( + getSite().getSelectionProvider(), this + .getSelection())); + if (fReorderedMembers) { + refresh(false); + fReorderedMembers = false; + } + } + } else { + // just for now + refresh(true); + } + } + + /* + * @see TreeViewer#internalExpandToLevel + */ + protected void internalExpandToLevel(Widget node, int level) { + if (node instanceof Item) { + Item i = (Item) node; + if (i.getData() instanceof IJavaElement) { + IJavaElement je = (IJavaElement) i.getData(); + if (je.getElementType() == IJavaElement.IMPORT_CONTAINER + || isInnerType(je)) { + if (i != fReusedExpandedItem) { + setExpanded(i, false); + return; + } + } + } + } + super.internalExpandToLevel(node, level); + } + + protected void reuseTreeItem(Item item, Object element) { + + // remove children + Item[] c = getChildren(item); + if (c != null && c.length > 0) { + + if (getExpanded(item)) + fReusedExpandedItem = item; + + for (int k = 0; k < c.length; k++) { + if (c[k].getData() != null) + disassociate(c[k]); + c[k].dispose(); + } + } + + updateItem(item, element); + updatePlus(item, element); + internalExpandToLevel(item, ALL_LEVELS); + + fReusedExpandedItem = null; + fForceFireSelectionChanged = true; + } + + protected boolean mustUpdateParent(IJavaElementDelta delta, + IJavaElement element) { + if (element instanceof IMethod) { + if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { + try { + return ((IMethod) element).isMainMethod(); + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e.getStatus()); + } + } + return "main".equals(element.getElementName()); //$NON-NLS-1$ + } + return false; + } + + /* + * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) + */ + public boolean isExpandable(Object element) { + if (hasFilters()) { + return getFilteredChildren(element).length > 0; + } + return super.isExpandable(element); + } + + protected ISourceRange getSourceRange(IJavaElement element) + throws JavaModelException { + if (element instanceof ISourceReference) + return ((ISourceReference) element).getSourceRange(); + if (element instanceof IMember)// && !(element instanceof + // IInitializer)) + return ((IMember) element).getNameRange(); + return null; + } + + protected boolean overlaps(ISourceRange range, int start, int end) { + return start <= (range.getOffset() + range.getLength() - 1) + && range.getOffset() <= end; + } + + protected boolean filtered(IJavaElement parent, IJavaElement child) { + + Object[] result = new Object[] { child }; + ViewerFilter[] filters = getFilters(); + for (int i = 0; i < filters.length; i++) { + result = filters[i].filter(this, parent, result); + if (result.length == 0) + return true; + } + + return false; + } + + protected void update(Widget w, IJavaElementDelta delta) { + + Item item; + + IJavaElement parent = delta.getElement(); + IJavaElementDelta[] affected = delta.getAffectedChildren(); + Item[] children = getChildren(w); + + boolean doUpdateParent = false; + boolean doUpdateParentsPlus = false; + + Vector deletions = new Vector(); + Vector additions = new Vector(); + + for (int i = 0; i < affected.length; i++) { + IJavaElementDelta affectedDelta = affected[i]; + IJavaElement affectedElement = affectedDelta.getElement(); + int status = affected[i].getKind(); + + // find tree item with affected element + int j; + for (j = 0; j < children.length; j++) + if (affectedElement.equals(children[j].getData())) + break; + + if (j == children.length) { + // remove from collapsed parent + if ((status & IJavaElementDelta.REMOVED) != 0) { + doUpdateParentsPlus = true; + continue; + } + // addition + if ((status & IJavaElementDelta.CHANGED) != 0 + && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 + && !filtered(parent, affectedElement)) { + additions.addElement(affectedDelta); + } + continue; + } + + item = children[j]; + + // removed + if ((status & IJavaElementDelta.REMOVED) != 0) { + deletions.addElement(item); + doUpdateParent = doUpdateParent + || mustUpdateParent(affectedDelta, affectedElement); + + // changed + } else if ((status & IJavaElementDelta.CHANGED) != 0) { + int change = affectedDelta.getFlags(); + doUpdateParent = doUpdateParent + || mustUpdateParent(affectedDelta, affectedElement); + + if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { + if (filtered(parent, affectedElement)) + deletions.addElement(item); + else + updateItem(item, affectedElement); + } + + if ((change & IJavaElementDelta.F_CONTENT) != 0) + updateItem(item, affectedElement); + + if ((change & IJavaElementDelta.F_CHILDREN) != 0) + update(item, affectedDelta); + + if ((change & IJavaElementDelta.F_REORDER) != 0) + fReorderedMembers = true; + } + } + + // find all elements to add + IJavaElementDelta[] add = delta.getAddedChildren(); + if (additions.size() > 0) { + IJavaElementDelta[] tmp = new IJavaElementDelta[add.length + + additions.size()]; + System.arraycopy(add, 0, tmp, 0, add.length); + for (int i = 0; i < additions.size(); i++) + tmp[i + add.length] = (IJavaElementDelta) additions + .elementAt(i); + add = tmp; + } + + // add at the right position + go2: for (int i = 0; i < add.length; i++) { + + try { + + IJavaElement e = add[i].getElement(); + if (filtered(parent, e)) + continue go2; + + doUpdateParent = doUpdateParent + || mustUpdateParent(add[i], e); + ISourceRange rng = getSourceRange(e); + int start = rng.getOffset(); + int end = start + rng.getLength() - 1; + int nameOffset = Integer.MAX_VALUE; + if (e instanceof IField) { + ISourceRange nameRange = ((IField) e).getNameRange(); + if (nameRange != null) + nameOffset = nameRange.getOffset(); + } + + Item last = null; + item = null; + children = getChildren(w); + + for (int j = 0; j < children.length; j++) { + item = children[j]; + IJavaElement r = (IJavaElement) item.getData(); + + if (r == null) { + // parent node collapsed and not be opened before -> + // do nothing + continue go2; + } + + try { + rng = getSourceRange(r); + + // multi-field declarations always start at + // the same offset. They also have the same + // end offset if the field sequence is terminated + // with a semicolon. If not, the source range + // ends behind the identifier / initializer + // see + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=51851 + boolean multiFieldDeclaration = r.getElementType() == IJavaElement.FIELD + && e.getElementType() == IJavaElement.FIELD + && rng.getOffset() == start; + + // elements are inserted by occurrence + // however, multi-field declarations have + // equal source ranges offsets, therefore we + // compare name-range offsets. + boolean multiFieldOrderBefore = false; + if (multiFieldDeclaration) { + if (r instanceof IField) { + ISourceRange nameRange = ((IField) r) + .getNameRange(); + if (nameRange != null) { + if (nameRange.getOffset() > nameOffset) + multiFieldOrderBefore = true; + } + } + } + + if (!multiFieldDeclaration + && overlaps(rng, start, end)) { + + // be tolerant if the delta is not correct, or + // if + // the tree has been updated other than by a + // delta + reuseTreeItem(item, e); + continue go2; + + } else if (multiFieldOrderBefore + || rng.getOffset() > start) { + + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, e); + } else { + // nothing to reuse + createTreeItem(w, e, j); + } + continue go2; + } + + } catch (JavaModelException x) { + // stumbled over deleted element + } + + last = item; + } + + // add at the end of the list + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, e); + } else { + // nothing to reuse + createTreeItem(w, e, -1); + } + + } catch (JavaModelException x) { + // the element to be added is not present -> don't add it + } + } + + // remove items which haven't been reused + Enumeration e = deletions.elements(); + while (e.hasMoreElements()) { + item = (Item) e.nextElement(); + disassociate(item); + item.dispose(); + } + + if (doUpdateParent) + updateItem(w, delta.getElement()); + if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item) + updatePlus((Item) w, delta.getElement()); + } + + /* + * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) + */ + protected void handleLabelProviderChanged( + LabelProviderChangedEvent event) { + Object input = getInput(); + if (event instanceof ProblemsLabelChangedEvent) { + ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; + if (e.isMarkerChange() && input instanceof ICompilationUnit) { + return; // marker changes can be ignored + } + } + // look if the underlying resource changed + Object[] changed = event.getElements(); + if (changed != null) { + IResource resource = getUnderlyingResource(); + if (resource != null) { + for (int i = 0; i < changed.length; i++) { + if (changed[i] != null && changed[i].equals(resource)) { + // change event to a full refresh + event = new LabelProviderChangedEvent( + (IBaseLabelProvider) event.getSource()); + break; + } + } + } + } + super.handleLabelProviderChanged(event); + } + + private IResource getUnderlyingResource() { + Object input = getInput(); + if (input instanceof ICompilationUnit) { + ICompilationUnit cu = (ICompilationUnit) input; + cu = JavaModelUtil.toOriginal(cu); + return cu.getResource(); + } + // else if (input instanceof IClassFile) { + // return ((IClassFile) input).getResource(); + // } + return null; + } + + } + + class LexicalSortingAction extends Action { + + private JavaElementSorter fSorter = new JavaElementSorter(); + + public LexicalSortingAction() { + super(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); + setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages + .getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ + + boolean checked = PHPeclipsePlugin.getDefault() + .getPreferenceStore().getBoolean( + "LexicalSortingAction.isChecked"); //$NON-NLS-1$ + valueChanged(checked, false); + } + + public void run() { + valueChanged(isChecked(), true); + } + + private void valueChanged(final boolean on, boolean store) { + setChecked(on); + BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), + new Runnable() { + public void run() { + fOutlineViewer.setSorter(on ? fSorter : null); + } + }); + + if (store) + PHPeclipsePlugin.getDefault().getPreferenceStore().setValue( + "LexicalSortingAction.isChecked", on); //$NON-NLS-1$ + } + } + + class ClassOnlyAction extends Action { + + public ClassOnlyAction() { + super(); + PlatformUI.getWorkbench().getHelpSystem().setHelp(this, + IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); + setText(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages + .getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, + "gointo_toplevel_type.gif"); //$NON-NLS-1$ + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + boolean showclass = preferenceStore + .getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ + setTopLevelTypeOnly(showclass); + } + + /* + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + setTopLevelTypeOnly(!fTopLevelTypeOnly); + } + + private void setTopLevelTypeOnly(boolean show) { + fTopLevelTypeOnly = show; + setChecked(show); + fOutlineViewer.refresh(false); + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + preferenceStore + .setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ + } + } + + /** + * This action toggles whether this Java Outline page links its selection to + * the active editor. + * + * @since 3.0 + */ + public class ToggleLinkingAction extends AbstractToggleLinkingAction { + + JavaOutlinePage fJavaOutlinePage; + + /** + * Constructs a new action. + * + * @param outlinePage + * the Java outline page + */ + public ToggleLinkingAction(JavaOutlinePage outlinePage) { + boolean isLinkingEnabled = PreferenceConstants + .getPreferenceStore() + .getBoolean( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); + setChecked(isLinkingEnabled); + fJavaOutlinePage = outlinePage; + } + + /** + * Runs the action. + */ + public void run() { + PreferenceConstants.getPreferenceStore().setValue( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, + isChecked()); + if (isChecked() && fEditor != null) + fEditor.synchronizeOutlinePage(fEditor + .computeHighlightRangeSourceReference(), false); + } + + } + + /** A flag to show contents of top level type only */ + private boolean fTopLevelTypeOnly; + + private IJavaElement fInput; + + private String fContextMenuID; + + private Menu fMenu; + + private JavaOutlineViewer fOutlineViewer; + + private PHPEditor fEditor; + + private MemberFilterActionGroup fMemberFilterActionGroup; + + private ListenerList fSelectionChangedListeners = new ListenerList(); + + private ListenerList fPostSelectionChangedListeners = new ListenerList(); + + private Hashtable fActions = new Hashtable(); + + private TogglePresentationAction fTogglePresentation; + + private GotoAnnotationAction fPreviousAnnotation; + + private GotoAnnotationAction fNextAnnotation; + + private TextEditorAction fShowJavadoc; + + private IAction fUndo; + + private IAction fRedo; + + private ToggleLinkingAction fToggleLinkingAction; + + private CompositeActionGroup fActionGroups; + + private IPropertyChangeListener fPropertyChangeListener; + + /** + * Custom filter action group. + * + * @since 3.0 + */ + private CustomFiltersActionGroup fCustomFiltersActionGroup; + + public JavaOutlinePage(String contextMenuID, PHPEditor editor) { + super(); + + Assert.isNotNull(editor); + + fContextMenuID = contextMenuID; + fEditor = editor; + fTogglePresentation = new TogglePresentationAction(); + ResourceBundle bundle = PHPEditorMessages.getResourceBundle(); + fPreviousAnnotation = new GotoAnnotationAction(bundle, + "PreviousAnnotation.", null, false); //$NON-NLS-1$ + fNextAnnotation = new GotoAnnotationAction(bundle, + "NextAnnotation.", null, true); //$NON-NLS-1$ + fShowJavadoc = (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ + fUndo = fEditor.getAction(ITextEditorActionConstants.UNDO); + fRedo = fEditor.getAction(ITextEditorActionConstants.REDO); + + fTogglePresentation.setEditor(editor); + fPreviousAnnotation.setEditor(editor); + fNextAnnotation.setEditor(editor); + + fPropertyChangeListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + doPropertyChange(event); + } + }; + PHPeclipsePlugin.getDefault().getPreferenceStore() + .addPropertyChangeListener(fPropertyChangeListener); + } + + /** + * Returns the primary type of a compilation unit (has the same name as the + * compilation unit). + * + * @param compilationUnit + * the compilation unit + * @return returns the primary type of the compilation unit, or + * null if is does not have one + */ + protected IType getMainType(ICompilationUnit compilationUnit) { + + if (compilationUnit == null) + return null; + + String name = compilationUnit.getElementName(); + int index = name.indexOf('.'); + if (index != -1) + name = name.substring(0, index); + IType type = compilationUnit.getType(name); + return type.exists() ? type : null; + } + + /** + * Returns the primary type of a class file. + * + * @param classFile + * the class file + * @return returns the primary type of the class file, or null + * if is does not have one + */ + // protected IType getMainType(IClassFile classFile) { + // try { + // IType type= classFile.getType(); + // return type != null && type.exists() ? type : null; + // } catch (JavaModelException e) { + // return null; + // } + // } + /* + * (non-Javadoc) Method declared on Page + */ + public void init(IPageSite pageSite) { + super.init(pageSite); + } + + private void doPropertyChange(PropertyChangeEvent event) { + if (fOutlineViewer != null) { + if (MembersOrderPreferenceCache.isMemberOrderProperty(event + .getProperty())) { + fOutlineViewer.refresh(false); + } + } + } + + /* + * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) + */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.addSelectionChangedListener(listener); + else + fSelectionChangedListeners.add(listener); + } + + /* + * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) + */ + public void removeSelectionChangedListener( + ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.removeSelectionChangedListener(listener); + else + fSelectionChangedListeners.remove(listener); + } + + /* + * @see ISelectionProvider#setSelection(ISelection) + */ + public void setSelection(ISelection selection) { + if (fOutlineViewer != null) + fOutlineViewer.setSelection(selection); + } + + /* + * @see ISelectionProvider#getSelection() + */ + public ISelection getSelection() { + if (fOutlineViewer == null) + return StructuredSelection.EMPTY; + return fOutlineViewer.getSelection(); + } + + /* + * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void addPostSelectionChangedListener( + ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.addPostSelectionChangedListener(listener); + else + fPostSelectionChangedListeners.add(listener); + } + + /* + * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void removePostSelectionChangedListener( + ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.removePostSelectionChangedListener(listener); + else + fPostSelectionChangedListeners.remove(listener); + } + + private void registerToolbarActions(IActionBars actionBars) { + + IToolBarManager toolBarManager = actionBars.getToolBarManager(); + if (toolBarManager != null) { + toolBarManager.add(new LexicalSortingAction()); + + fMemberFilterActionGroup = new MemberFilterActionGroup( + fOutlineViewer, + "net.sourceforge.phpeclipse.JavaOutlinePage"); //$NON-NLS-1$ + fMemberFilterActionGroup.contributeToToolBar(toolBarManager); + + fCustomFiltersActionGroup.fillActionBars(actionBars); + + IMenuManager menu = actionBars.getMenuManager(); + menu.add(new Separator("EndFilterGroup")); //$NON-NLS-1$ + + fToggleLinkingAction = new ToggleLinkingAction(this); + menu.add(new ClassOnlyAction()); + menu.add(fToggleLinkingAction); + } + } + + /* + * @see IPage#createControl + */ + public void createControl(Composite parent) { + + Tree tree = new Tree(parent, SWT.MULTI); + + AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider( + AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS + | JavaElementLabels.F_APP_TYPE_SIGNATURE, + AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); + + fOutlineViewer = new JavaOutlineViewer(tree); + initDragAndDrop(); + fOutlineViewer.setContentProvider(new ChildrenProvider()); + fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider( + lprovider)); + + Object[] listeners = fSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + fSelectionChangedListeners.remove(listeners[i]); + fOutlineViewer + .addSelectionChangedListener((ISelectionChangedListener) listeners[i]); + } + + listeners = fPostSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + fPostSelectionChangedListeners.remove(listeners[i]); + fOutlineViewer + .addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); + } + + MenuManager manager = new MenuManager(fContextMenuID, fContextMenuID); + manager.setRemoveAllWhenShown(true); + manager.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager m) { + contextMenuAboutToShow(m); + } + }); + fMenu = manager.createContextMenu(tree); + tree.setMenu(fMenu); + + IPageSite site = getSite(); + site + .registerContextMenu(PHPeclipsePlugin.getPluginId() + + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ + site.setSelectionProvider(fOutlineViewer); + + // we must create the groups after we have set the selection provider to + // the site + fActionGroups = new CompositeActionGroup(new ActionGroup[] { + // new OpenViewActionGroup(this), + // new CCPActionGroup(this), + new GenerateActionGroup(this) }); + // new RefactorActionGroup(this), + // new JavaSearchActionGroup(this)}); + + // register global actions + IActionBars bars = site.getActionBars(); + + bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); + bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); + bars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), + fPreviousAnnotation); + bars + .setGlobalActionHandler(ActionFactory.NEXT.getId(), + fNextAnnotation); + bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_JAVA_DOC, + fShowJavadoc); + bars + .setGlobalActionHandler( + ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, + fTogglePresentation); + bars.setGlobalActionHandler( + ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, + fNextAnnotation); + bars.setGlobalActionHandler( + ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, + fPreviousAnnotation); + + fActionGroups.fillActionBars(bars); + + IStatusLineManager statusLineManager = bars.getStatusLineManager(); + if (statusLineManager != null) { + StatusBarUpdater updater = new StatusBarUpdater(statusLineManager); + fOutlineViewer.addPostSelectionChangedListener(updater); + } + // Custom filter group + fCustomFiltersActionGroup = new CustomFiltersActionGroup( + "net.sourceforge.phpdt.ui.JavaOutlinePage", fOutlineViewer); //$NON-NLS-1$ + + registerToolbarActions(bars); + + fOutlineViewer.setInput(fInput); + } + + public void dispose() { + + if (fEditor == null) + return; + + if (fMemberFilterActionGroup != null) { + fMemberFilterActionGroup.dispose(); + fMemberFilterActionGroup = null; + } + + if (fCustomFiltersActionGroup != null) { + fCustomFiltersActionGroup.dispose(); + fCustomFiltersActionGroup = null; + } + + fEditor.outlinePageClosed(); + fEditor = null; + + fSelectionChangedListeners.clear(); + fSelectionChangedListeners = null; + + fPostSelectionChangedListeners.clear(); + fPostSelectionChangedListeners = null; + + if (fPropertyChangeListener != null) { + PHPeclipsePlugin.getDefault().getPreferenceStore() + .removePropertyChangeListener(fPropertyChangeListener); + fPropertyChangeListener = null; + } + + if (fMenu != null && !fMenu.isDisposed()) { + fMenu.dispose(); + fMenu = null; + } + + if (fActionGroups != null) + fActionGroups.dispose(); + + fTogglePresentation.setEditor(null); + fPreviousAnnotation.setEditor(null); + fNextAnnotation.setEditor(null); + + fOutlineViewer = null; + + super.dispose(); + } + + public Control getControl() { + if (fOutlineViewer != null) + return fOutlineViewer.getControl(); + return null; + } + + public void setInput(IJavaElement inputElement) { + fInput = inputElement; + if (fOutlineViewer != null) + fOutlineViewer.setInput(fInput); + } + + public void select(ISourceReference reference) { + if (fOutlineViewer != null) { + + ISelection s = fOutlineViewer.getSelection(); + if (s instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) s; + List elements = ss.toList(); + if (!elements.contains(reference)) { + s = (reference == null ? StructuredSelection.EMPTY + : new StructuredSelection(reference)); + fOutlineViewer.setSelection(s, true); + } + } + } + } + + public void setAction(String actionID, IAction action) { + Assert.isNotNull(actionID); + if (action == null) + fActions.remove(actionID); + else + fActions.put(actionID, action); + } + + public IAction getAction(String actionID) { + Assert.isNotNull(actionID); + return (IAction) fActions.get(actionID); + } + + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class key) { + if (key == IShowInSource.class) { + return getShowInSource(); + } + if (key == IShowInTargetList.class) { + return new IShowInTargetList() { + public String[] getShowInTargetIds() { + return new String[] { JavaUI.ID_PACKAGES }; + } + + }; + } + if (key == IShowInTarget.class) { + return getShowInTarget(); + } + + return null; + } + + /** + * Convenience method to add the action installed under the given actionID + * to the specified group of the menu. + * + * @param menu + * the menu manager + * @param group + * the group to which to add the action + * @param actionID + * the ID of the new action + */ + protected void addAction(IMenuManager menu, String group, String actionID) { + IAction action = getAction(actionID); + if (action != null) { + if (action instanceof IUpdate) + ((IUpdate) action).update(); + + if (action.isEnabled()) { + IMenuManager subMenu = menu.findMenuUsingPath(group); + if (subMenu != null) + subMenu.add(action); + else + menu.appendToGroup(group, action); + } + } + } + + protected void contextMenuAboutToShow(IMenuManager menu) { + + PHPeclipsePlugin.createStandardGroups(menu); + + IStructuredSelection selection = (IStructuredSelection) getSelection(); + fActionGroups.setContext(new ActionContext(selection)); + fActionGroups.fillContextMenu(menu); + } + + /* + * @see Page#setFocus() + */ + public void setFocus() { + if (fOutlineViewer != null) + fOutlineViewer.getControl().setFocus(); + } + + /** + * Checks whether a given Java element is an inner type. + * + * @param element + * the java element + * @return true iff the given element is an inner type + */ + private boolean isInnerType(IJavaElement element) { + + if (element != null && element.getElementType() == IJavaElement.TYPE) { + IType type = (IType) element; + try { + return type.isMember(); + } catch (JavaModelException e) { + IJavaElement parent = type.getParent(); + if (parent != null) { + int parentElementType = parent.getElementType(); + return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE); + } + } + } + + return false; + } + + /** + * Returns the IShowInSource for this view. + * + * @return the {@link IShowInSource} + */ + protected IShowInSource getShowInSource() { + return new IShowInSource() { + public ShowInContext getShowInContext() { + return new ShowInContext(null, getSite().getSelectionProvider() + .getSelection()); + } + }; + } + + /** + * Returns the IShowInTarget for this view. + * + * @return the {@link IShowInTarget} + */ + protected IShowInTarget getShowInTarget() { + return new IShowInTarget() { + public boolean show(ShowInContext context) { + ISelection sel = context.getSelection(); + if (sel instanceof ITextSelection) { + ITextSelection tsel = (ITextSelection) sel; + int offset = tsel.getOffset(); + IJavaElement element = fEditor.getElementAt(offset); + if (element != null) { + setSelection(new StructuredSelection(element)); + return true; + } + } + return false; + } + }; + } + + private void initDragAndDrop() { +// int ops = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; +// Transfer[] transfers = new Transfer[] { LocalSelectionTransfer +// .getInstance() }; + + // Drop Adapter + // TransferDropTargetListener[] dropListeners= new + // TransferDropTargetListener[] { + // new SelectionTransferDropAdapter(fOutlineViewer) + // }; + // fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new + // DelegatingDropAdapter(dropListeners)); + + // Drag Adapter + // TransferDragSourceListener[] dragListeners= new + // TransferDragSourceListener[] { + // new SelectionTransferDragAdapter(fOutlineViewer) + // }; + // fOutlineViewer.addDragSupport(ops, transfers, new + // JdtViewerDragAdapter(fOutlineViewer, dragListeners)); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectMarkerRulerAction2.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSelectRulerAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java new file mode 100644 index 0000000..cbecbe3 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaStorageDocumentProvider.java @@ -0,0 +1,46 @@ +/********************************************************************** + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.ui.editors.text.StorageDocumentProvider; + +/** + * @since 3.0 + */ +public class JavaStorageDocumentProvider extends StorageDocumentProvider { + + public JavaStorageDocumentProvider() { + super(); + } + + /* + * @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, + * org.eclipse.jface.text.IDocument) + */ + protected void setupDocument(Object element, IDocument document) { + + if (document != null) { + JavaTextTools tools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING); + + // tools.setupJavaDocumentPartitioner(document, + // IDocument.DEFAULT_CONTENT_TYPE, element); //IPHPPartitions.HTML, + // element); + } + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/LinePainter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPAnnotationHover.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java new file mode 100644 index 0000000..606ec56 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPDocumentProvider.java @@ -0,0 +1,1733 @@ +package net.sourceforge.phpeclipse.phpeditor; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IProblemRequestor; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.compiler.IProblem; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension; +import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy.SpellProblem; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceRuleFactory; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.jobs.ISchedulingRule; +import org.eclipse.jface.preference.IPreferenceStore; +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultLineTracker; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ILineTracker; +import org.eclipse.jface.text.ISynchronizable; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationModelEvent; +import org.eclipse.jface.text.source.IAnnotationAccessExtension; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IAnnotationModelListener; +import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; +import org.eclipse.jface.text.source.IAnnotationPresentation; +import org.eclipse.jface.text.source.ImageUtilities; +import org.eclipse.jface.util.IPropertyChangeListener; +//incastrix +//import org.eclipse.jface.util.ListenerList; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.widgets.Canvas; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.editors.text.EditorsUI; +import org.eclipse.ui.editors.text.ForwardingDocumentProvider; +import org.eclipse.ui.editors.text.TextFileDocumentProvider; +import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.MarkerAnnotation; +import org.eclipse.ui.texteditor.MarkerUtilities; +import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; + +/** + * The PHPDocumentProvider provides the IDocuments used by java editors. + */ + +public class PHPDocumentProvider extends TextFileDocumentProvider implements + ICompilationUnitDocumentProvider { + /** + * Here for visibility issues only. + */ + + /** + * Bundle of all required informations to allow working copy management. + */ + /** + * Bundle of all required informations to allow working copy management. + */ + static protected class CompilationUnitInfo extends FileInfo { + public ICompilationUnit fCopy; + } + + /** + * Annotation model dealing with java marker annotations and temporary + * problems. Also acts as problem requestor for its compilation unit. + * Initialiy inactive. Must explicitly be activated. + */ + protected static class CompilationUnitAnnotationModel extends + ResourceMarkerAnnotationModel implements IProblemRequestor, + IProblemRequestorExtension { + + private static class ProblemRequestorState { + boolean fInsideReportingSequence = false; + + List fReportedProblems; + } + + private ThreadLocal fProblemRequestorState = new ThreadLocal(); + + private int fStateCount = 0; + + private ICompilationUnit fCompilationUnit; + + private List fGeneratedAnnotations; + + private IProgressMonitor fProgressMonitor; + + private boolean fIsActive = false; + + private ReverseMap fReverseMap = new ReverseMap(); + + private List fPreviouslyOverlaid = null; + + private List fCurrentlyOverlaid = new ArrayList(); + + public CompilationUnitAnnotationModel(IResource resource) { + super(resource); + } + + public void setCompilationUnit(ICompilationUnit unit) { + fCompilationUnit = unit; + } + + protected MarkerAnnotation createMarkerAnnotation(IMarker marker) { + String markerType = MarkerUtilities.getMarkerType(marker); + if (markerType != null + && markerType + .startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX)) + return new JavaMarkerAnnotation(marker); + return super.createMarkerAnnotation(marker); + } + + /* + * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent() + */ + protected AnnotationModelEvent createAnnotationModelEvent() { + return new CompilationUnitAnnotationModelEvent(this, getResource()); + } + + protected Position createPositionFromProblem(IProblem problem) { + int start = problem.getSourceStart(); + if (start < 0) + return null; + + int length = problem.getSourceEnd() - problem.getSourceStart() + 1; + if (length < 0) + return null; + + return new Position(start, length); + } + + /* + * @see IProblemRequestor#beginReporting() + */ + public void beginReporting() { + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); + if (state == null) + internalBeginReporting(false); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence() + */ + public void beginReportingSequence() { + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); + if (state == null) + internalBeginReporting(true); + } + + /** + * Sets up the infrastructure necessary for problem reporting. + * + * @param insideReportingSequence + * true if this method call is issued from + * inside a reporting sequence + */ + private void internalBeginReporting(boolean insideReportingSequence) { + if (fCompilationUnit != null) { + // && + // fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) + // { + ProblemRequestorState state = new ProblemRequestorState(); + state.fInsideReportingSequence = insideReportingSequence; + state.fReportedProblems = new ArrayList(); + synchronized (getLockObject()) { + fProblemRequestorState.set(state); + ++fStateCount; + } + } + } + + /* + * @see IProblemRequestor#acceptProblem(IProblem) + */ + public void acceptProblem(IProblem problem) { + if (isActive()) { + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); + if (state != null) + state.fReportedProblems.add(problem); + } + } + + /* + * @see IProblemRequestor#endReporting() + */ + public void endReporting() { + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); + if (state != null && !state.fInsideReportingSequence) + internalEndReporting(state); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence() + */ + public void endReportingSequence() { + ProblemRequestorState state = (ProblemRequestorState) fProblemRequestorState + .get(); + if (state != null && state.fInsideReportingSequence) + internalEndReporting(state); + } + + private void internalEndReporting(ProblemRequestorState state) { + int stateCount = 0; + synchronized (getLockObject()) { + --fStateCount; + stateCount = fStateCount; + fProblemRequestorState.set(null); + } + + if (stateCount == 0 && isActive()) + reportProblems(state.fReportedProblems); + } + + /** + * Signals the end of problem reporting. + */ + private void reportProblems(List reportedProblems) { + if (fProgressMonitor != null && fProgressMonitor.isCanceled()) + return; + + boolean temporaryProblemsChanged = false; + + synchronized (getLockObject()) { + + boolean isCanceled = false; + + fPreviouslyOverlaid = fCurrentlyOverlaid; + fCurrentlyOverlaid = new ArrayList(); + + if (fGeneratedAnnotations.size() > 0) { + temporaryProblemsChanged = true; + removeAnnotations(fGeneratedAnnotations, false, true); + fGeneratedAnnotations.clear(); + } + + if (reportedProblems != null && reportedProblems.size() > 0) { + + Iterator e = reportedProblems.iterator(); + while (e.hasNext()) { + + if (fProgressMonitor != null + && fProgressMonitor.isCanceled()) { + isCanceled = true; + break; + } + + IProblem problem = (IProblem) e.next(); + Position position = createPositionFromProblem(problem); + if (position != null) { + + try { + ProblemAnnotation annotation = new ProblemAnnotation( + problem, fCompilationUnit); + overlayMarkers(position, annotation); + addAnnotation(annotation, position, false); + fGeneratedAnnotations.add(annotation); + + temporaryProblemsChanged = true; + } catch (BadLocationException x) { + // ignore invalid position + } + } + } + } + + removeMarkerOverlays(isCanceled); + fPreviouslyOverlaid = null; + } + + if (temporaryProblemsChanged) + fireModelChanged(); + } + + private void removeMarkerOverlays(boolean isCanceled) { + if (isCanceled) { + fCurrentlyOverlaid.addAll(fPreviouslyOverlaid); + } else if (fPreviouslyOverlaid != null) { + Iterator e = fPreviouslyOverlaid.iterator(); + while (e.hasNext()) { + JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) e + .next(); + annotation.setOverlay(null); + } + } + } + + /** + * Overlays value with problem annotation. + * + * @param problemAnnotation + */ + private void setOverlay(Object value, + ProblemAnnotation problemAnnotation) { + if (value instanceof JavaMarkerAnnotation) { + JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) value; + if (annotation.isProblem()) { + annotation.setOverlay(problemAnnotation); + fPreviouslyOverlaid.remove(annotation); + fCurrentlyOverlaid.add(annotation); + } + } else { + } + } + + private void overlayMarkers(Position position, + ProblemAnnotation problemAnnotation) { + Object value = getAnnotations(position); + if (value instanceof List) { + List list = (List) value; + for (Iterator e = list.iterator(); e.hasNext();) + setOverlay(e.next(), problemAnnotation); + } else { + setOverlay(value, problemAnnotation); + } + } + + /** + * Tells this annotation model to collect temporary problems from now + * on. + */ + private void startCollectingProblems() { + fGeneratedAnnotations = new ArrayList(); + } + + /** + * Tells this annotation model to no longer collect temporary problems. + */ + private void stopCollectingProblems() { + if (fGeneratedAnnotations != null) + removeAnnotations(fGeneratedAnnotations, true, true); + fGeneratedAnnotations = null; + } + + /* + * @see IProblemRequestor#isActive() + */ + public boolean isActive() { + return fIsActive; + } + + /* + * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor) + */ + public void setProgressMonitor(IProgressMonitor monitor) { + fProgressMonitor = monitor; + } + + /* + * @see IProblemRequestorExtension#setIsActive(boolean) + */ + public void setIsActive(boolean isActive) { + if (fIsActive != isActive) { + fIsActive = isActive; + if (fIsActive) + startCollectingProblems(); + else + stopCollectingProblems(); + } + } + + private Object getAnnotations(Position position) { + return fReverseMap.get(position); + } + + /* + * @see AnnotationModel#addAnnotation(Annotation, Position, boolean) + */ + protected void addAnnotation(Annotation annotation, Position position, + boolean fireModelChanged) throws BadLocationException { + super.addAnnotation(annotation, position, fireModelChanged); + + Object cached = fReverseMap.get(position); + if (cached == null) + fReverseMap.put(position, annotation); + else if (cached instanceof List) { + List list = (List) cached; + list.add(annotation); + } else if (cached instanceof Annotation) { + List list = new ArrayList(2); + list.add(cached); + list.add(annotation); + fReverseMap.put(position, list); + } + } + + /* + * @see AnnotationModel#removeAllAnnotations(boolean) + */ + protected void removeAllAnnotations(boolean fireModelChanged) { + super.removeAllAnnotations(fireModelChanged); + fReverseMap.clear(); + } + + /* + * @see AnnotationModel#removeAnnotation(Annotation, boolean) + */ + protected void removeAnnotation(Annotation annotation, + boolean fireModelChanged) { + Position position = getPosition(annotation); + Object cached = fReverseMap.get(position); + if (cached instanceof List) { + List list = (List) cached; + list.remove(annotation); + if (list.size() == 1) { + fReverseMap.put(position, list.get(0)); + list.clear(); + } + } else if (cached instanceof Annotation) { + fReverseMap.remove(position); + } + super.removeAnnotation(annotation, fireModelChanged); + } + } + + protected static class GlobalAnnotationModelListener implements + IAnnotationModelListener, IAnnotationModelListenerExtension { + + private ListenerList fListenerList; + + public GlobalAnnotationModelListener() { + fListenerList = new ListenerList(); + } + + public void addListener(IAnnotationModelListener listener) { + fListenerList.add(listener); + } + + /** + * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) + */ + public void modelChanged(AnnotationModelEvent event) { + Object[] listeners = fListenerList.getListeners(); + for (int i = 0; i < listeners.length; i++) { + Object curr = listeners[i]; + if (curr instanceof IAnnotationModelListenerExtension) { + ((IAnnotationModelListenerExtension) curr) + .modelChanged(event); + } + } + } + + /** + * @see IAnnotationModelListener#modelChanged(IAnnotationModel) + */ + public void modelChanged(IAnnotationModel model) { + Object[] listeners = fListenerList.getListeners(); + for (int i = 0; i < listeners.length; i++) { + ((IAnnotationModelListener) listeners[i]).modelChanged(model); + } + } + + public void removeListener(IAnnotationModelListener listener) { + fListenerList.remove(listener); + } + } + + /** + * Annotation representating an IProblem. + */ + static public class ProblemAnnotation extends Annotation implements + IJavaAnnotation, IAnnotationPresentation { + + private static final String SPELLING_ANNOTATION_TYPE = "org.eclipse.ui.workbench.texteditor.spelling"; + + // XXX: To be fully correct these constants should be non-static + /** + * The layer in which task problem annotations are located. + */ + private static final int TASK_LAYER; + + /** + * The layer in which info problem annotations are located. + */ + private static final int INFO_LAYER; + + /** + * The layer in which warning problem annotations representing are + * located. + */ + private static final int WARNING_LAYER; + + /** + * The layer in which error problem annotations representing are + * located. + */ + private static final int ERROR_LAYER; + + static { + AnnotationPreferenceLookup lookup = EditorsUI + .getAnnotationPreferenceLookup(); + TASK_LAYER = computeLayer( + "org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$ + INFO_LAYER = computeLayer("net.sourceforge.phpdt.ui.info", lookup); //$NON-NLS-1$ + WARNING_LAYER = computeLayer( + "net.sourceforge.phpdt.ui.warning", lookup); //$NON-NLS-1$ + ERROR_LAYER = computeLayer("net.sourceforge.phpdt.ui.error", lookup); //$NON-NLS-1$ + } + + private static int computeLayer(String annotationType, + AnnotationPreferenceLookup lookup) { + Annotation annotation = new Annotation(annotationType, false, null); + AnnotationPreference preference = lookup + .getAnnotationPreference(annotation); + if (preference != null) + return preference.getPresentationLayer() + 1; + else + return IAnnotationAccessExtension.DEFAULT_LAYER + 1; + } + + // private static Image fgQuickFixImage; + // private static Image fgQuickFixErrorImage; + // private static boolean fgQuickFixImagesInitialized= false; + + private ICompilationUnit fCompilationUnit; + + private List fOverlaids; + + private IProblem fProblem; + + private Image fImage; + + //private boolean fQuickFixImagesInitialized = false; + + private int fLayer = IAnnotationAccessExtension.DEFAULT_LAYER; + + public ProblemAnnotation(IProblem problem, ICompilationUnit cu) { + + fProblem = problem; + fCompilationUnit = cu; + + if (SpellProblem.Spelling == fProblem.getID()) { + setType(SPELLING_ANNOTATION_TYPE); + fLayer = WARNING_LAYER; + } else if (IProblem.Task == fProblem.getID()) { + setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE); + fLayer = TASK_LAYER; + } else if (fProblem.isWarning()) { + setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE); + fLayer = WARNING_LAYER; + } else if (fProblem.isError()) { + setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE); + fLayer = ERROR_LAYER; + } else { + setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE); + fLayer = INFO_LAYER; + } + } + + /* + * @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer() + */ + public int getLayer() { + return fLayer; + } + + private void initializeImages() { + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936 + // if (!fQuickFixImagesInitialized) { + // if (isProblem() && indicateQuixFixableProblems() && + // JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb + // for tasks + // if (!fgQuickFixImagesInitialized) { + // fgQuickFixImage= + // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); + // fgQuickFixErrorImage= + // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); + // fgQuickFixImagesInitialized= true; + // } + // if (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType())) + // fImage= fgQuickFixErrorImage; + // else + // fImage= fgQuickFixImage; + // } + // fQuickFixImagesInitialized= true; + // } + } + +// private boolean indicateQuixFixableProblems() { +// return PreferenceConstants.getPreferenceStore().getBoolean( +// PreferenceConstants.EDITOR_CORRECTION_INDICATION); +// } + + /* + * @see Annotation#paint + */ + public void paint(GC gc, Canvas canvas, Rectangle r) { + initializeImages(); + if (fImage != null) + ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, + SWT.TOP); + } + + /* + * @see IJavaAnnotation#getImage(Display) + */ + public Image getImage(Display display) { + initializeImages(); + return fImage; + } + + /* + * @see IJavaAnnotation#getMessage() + */ + public String getText() { + return fProblem.getMessage(); + } + + /* + * @see IJavaAnnotation#getArguments() + */ + public String[] getArguments() { + return isProblem() ? fProblem.getArguments() : null; + } + + /* + * @see IJavaAnnotation#getId() + */ + public int getId() { + return fProblem.getID(); + } + + /* + * @see IJavaAnnotation#isProblem() + */ + public boolean isProblem() { + String type = getType(); + return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) + || JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) + || SPELLING_ANNOTATION_TYPE.equals(type); + } + + /* + * @see IJavaAnnotation#hasOverlay() + */ + public boolean hasOverlay() { + return false; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay() + */ + public IJavaAnnotation getOverlay() { + return null; + } + + /* + * @see IJavaAnnotation#addOverlaid(IJavaAnnotation) + */ + public void addOverlaid(IJavaAnnotation annotation) { + if (fOverlaids == null) + fOverlaids = new ArrayList(1); + fOverlaids.add(annotation); + } + + /* + * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation) + */ + public void removeOverlaid(IJavaAnnotation annotation) { + if (fOverlaids != null) { + fOverlaids.remove(annotation); + if (fOverlaids.size() == 0) + fOverlaids = null; + } + } + + /* + * @see IJavaAnnotation#getOverlaidIterator() + */ + public Iterator getOverlaidIterator() { + if (fOverlaids != null) + return fOverlaids.iterator(); + return null; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit() + */ + public ICompilationUnit getCompilationUnit() { + return fCompilationUnit; + } + } + + /** + * Internal structure for mapping positions to some value. The reason for + * this specific structure is that positions can change over time. Thus a + * lookup is based on value and not on hash value. + */ + protected static class ReverseMap { + + static class Entry { + Position fPosition; + + Object fValue; + } + + private int fAnchor = 0; + + private List fList = new ArrayList(2); + + public ReverseMap() { + } + + public void clear() { + fList.clear(); + } + + public Object get(Position position) { + + Entry entry; + + // behind anchor + int length = fList.size(); + for (int i = fAnchor; i < length; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) { + fAnchor = i; + return entry.fValue; + } + } + + // before anchor + for (int i = 0; i < fAnchor; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) { + fAnchor = i; + return entry.fValue; + } + } + + return null; + } + + private int getIndex(Position position) { + Entry entry; + int length = fList.size(); + for (int i = 0; i < length; i++) { + entry = (Entry) fList.get(i); + if (entry.fPosition.equals(position)) + return i; + } + return -1; + } + + public void put(Position position, Object value) { + int index = getIndex(position); + if (index == -1) { + Entry entry = new Entry(); + entry.fPosition = position; + entry.fValue = value; + fList.add(entry); + } else { + Entry entry = (Entry) fList.get(index); + entry.fValue = value; + } + } + + public void remove(Position position) { + int index = getIndex(position); + if (index > -1) + fList.remove(index); + } + } + + /** + * Document that can also be used by a background reconciler. + */ + protected static class PartiallySynchronizedDocument extends Document { + + /* + * @see IDocumentExtension#startSequentialRewrite(boolean) + */ + synchronized public void startSequentialRewrite(boolean normalized) { + super.startSequentialRewrite(normalized); + } + + /* + * @see IDocumentExtension#stopSequentialRewrite() + */ + synchronized public void stopSequentialRewrite() { + super.stopSequentialRewrite(); + } + + /* + * @see IDocument#get() + */ + synchronized public String get() { + return super.get(); + } + + /* + * @see IDocument#get(int, int) + */ + synchronized public String get(int offset, int length) + throws BadLocationException { + return super.get(offset, length); + } + + /* + * @see IDocument#getChar(int) + */ + synchronized public char getChar(int offset) + throws BadLocationException { + return super.getChar(offset); + } + + /* + * @see IDocument#replace(int, int, String) + */ + synchronized public void replace(int offset, int length, String text) + throws BadLocationException { + super.replace(offset, length, text); + } + + /* + * @see IDocument#set(String) + */ + synchronized public void set(String text) { + super.set(text); + } + }; + + // + // private static PHPPartitionScanner HTML_PARTITION_SCANNER = null; + // + // private static PHPPartitionScanner PHP_PARTITION_SCANNER = null; + // private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null; + // + // // private final static String[] TYPES= new String[] { + // PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, + // PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; + // private final static String[] TYPES = + // new String[] { + // IPHPPartitionScannerConstants.PHP, + // IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT, + // IPHPPartitionScannerConstants.HTML, + // IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT, + // IPHPPartitionScannerConstants.JAVASCRIPT, + // IPHPPartitionScannerConstants.CSS, + // IPHPPartitionScannerConstants.SMARTY, + // IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT }; + // private static PHPPartitionScanner XML_PARTITION_SCANNER = null; + + /* Preference key for temporary problems */ + private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS; + + /** Indicates whether the save has been initialized by this provider */ + private boolean fIsAboutToSave = false; + + /** The save policy used by this provider */ + private ISavePolicy fSavePolicy; + + /** Internal property changed listener */ + private IPropertyChangeListener fPropertyListener; + + /** annotation model listener added to all created CU annotation models */ + private GlobalAnnotationModelListener fGlobalAnnotationModelListener; + + public PHPDocumentProvider() { + // IDocumentProvider provider= new TextFileDocumentProvider(new + // JavaStorageDocumentProvider()); + IDocumentProvider provider = new TextFileDocumentProvider(); + provider = new ForwardingDocumentProvider( + IPHPPartitions.PHP_PARTITIONING, + new JavaDocumentSetupParticipant(), provider); + setParentDocumentProvider(provider); + + fGlobalAnnotationModelListener = new GlobalAnnotationModelListener(); + fPropertyListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty())) + enableHandlingTemporaryProblems(); + } + }; + PHPeclipsePlugin.getDefault().getPreferenceStore() + .addPropertyChangeListener(fPropertyListener); + + } + + /** + * Sets the document provider's save policy. + */ + public void setSavePolicy(ISavePolicy savePolicy) { + fSavePolicy = savePolicy; + } + + /** + * Creates a compilation unit from the given file. + * + * @param file + * the file from which to create the compilation unit + */ + protected ICompilationUnit createCompilationUnit(IFile file) { + Object element = JavaCore.create(file); + if (element instanceof ICompilationUnit) + return (ICompilationUnit) element; + return null; + } + + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo() + */ + protected FileInfo createEmptyFileInfo() { + return new CompilationUnitInfo(); + } + + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile) + */ + protected IAnnotationModel createAnnotationModel(IFile file) { + return new CompilationUnitAnnotationModel(file); + } + + /* + * @see AbstractDocumentProvider#createElementInfo(Object) + */ + // protected ElementInfo createElementInfo(Object element) throws + // CoreException { + // + // if (!(element instanceof IFileEditorInput)) + // return super.createElementInfo(element); + // + // IFileEditorInput input = (IFileEditorInput) element; + // ICompilationUnit original = createCompilationUnit(input.getFile()); + // if (original != null) { + // + // try { + // + // try { + // refreshFile(input.getFile()); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); + // //$NON-NLS-1$ + // } + // + // IAnnotationModel m = createCompilationUnitAnnotationModel(input); + // IProblemRequestor r = m instanceof IProblemRequestor ? + // (IProblemRequestor) m : null; + // ICompilationUnit c = (ICompilationUnit) + // original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r); + // + // DocumentAdapter a = null; + // try { + // a = (DocumentAdapter) c.getBuffer(); + // } catch (ClassCastException x) { + // IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + // PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong + // buffer", x); //$NON-NLS-1$ + // throw new CoreException(status); + // } + // + // _FileSynchronizer f = new _FileSynchronizer(input); + // f.install(); + // + // CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, + // c); + // info.setModificationStamp(computeModificationStamp(input.getFile())); + // info.fStatus = a.getStatus(); + // info.fEncoding = getPersistedEncoding(input); + // + // if (r instanceof IProblemRequestorExtension) { + // IProblemRequestorExtension extension = (IProblemRequestorExtension) r; + // extension.setIsActive(isHandlingTemporaryProblems()); + // } + // m.addAnnotationModelListener(fGlobalAnnotationModelListener); + // + // return info; + // + // } catch (JavaModelException x) { + // throw new CoreException(x.getStatus()); + // } + // } else { + // return super.createElementInfo(element); + // } + // } + /* + * @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo) + */ + // protected void disposeElementInfo(Object element, ElementInfo info) { + // + // if (info instanceof CompilationUnitInfo) { + // CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; + // cuInfo.fCopy.destroy(); + // cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); + // } + // + // super.disposeElementInfo(element, info); + // } + /* + * @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, + * IDocument, boolean) + */ + // protected void doSaveDocument(IProgressMonitor monitor, Object element, + // IDocument document, boolean overwrite) + // throws CoreException { + // + // ElementInfo elementInfo = getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; + // + // // update structure, assumes lock on info.fCopy + // info.fCopy.reconcile(); + // + // ICompilationUnit original = (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource = original.getResource(); + // + // if (resource == null) { + // // underlying resource has been deleted, just recreate file, ignore the + // rest + // super.doSaveDocument(monitor, element, document, overwrite); + // return; + // } + // + // if (resource != null && !overwrite) + // checkSynchronizationState(info.fModificationStamp, resource); + // + // if (fSavePolicy != null) + // fSavePolicy.preSave(info.fCopy); + // + // // inform about the upcoming content change + // fireElementStateChanging(element); + // try { + // fIsAboutToSave = true; + // // commit working copy + // info.fCopy.commit(overwrite, monitor); + // } catch (CoreException x) { + // // inform about the failure + // fireElementStateChangeFailed(element); + // throw x; + // } catch (RuntimeException x) { + // // inform about the failure + // fireElementStateChangeFailed(element); + // throw x; + // } finally { + // fIsAboutToSave = false; + // } + // + // // If here, the dirty state of the editor will change to "not dirty". + // // Thus, the state changing flag will be reset. + // + // AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) + // info.fModel; + // model.updateMarkers(info.fDocument); + // + // if (resource != null) + // info.setModificationStamp(computeModificationStamp(resource)); + // + // if (fSavePolicy != null) { + // ICompilationUnit unit = fSavePolicy.postSave(original); + // if (unit != null) { + // IResource r = unit.getResource(); + // IMarker[] markers = r.findMarkers(IMarker.MARKER, true, + // IResource.DEPTH_ZERO); + // if (markers != null && markers.length > 0) { + // for (int i = 0; i < markers.length; i++) + // model.updateMarker(markers[i], info.fDocument, null); + // } + // } + // } + // + // } else { + // super.doSaveDocument(monitor, element, document, overwrite); + // } + // } + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object) + */ + protected FileInfo createFileInfo(Object element) throws CoreException { + if (!(element instanceof IFileEditorInput)) + return null; + + IFileEditorInput input = (IFileEditorInput) element; + ICompilationUnit original = createCompilationUnit(input.getFile()); + if (original == null) + return null; + + FileInfo info = super.createFileInfo(element); + if (!(info instanceof CompilationUnitInfo)) + return null; + + CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; + setUpSynchronization(cuInfo); + + IProblemRequestor requestor = cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel + : null; + + original.becomeWorkingCopy(requestor, getProgressMonitor()); + cuInfo.fCopy = original; + + if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) { + CompilationUnitAnnotationModel model = (CompilationUnitAnnotationModel) cuInfo.fModel; + model.setCompilationUnit(cuInfo.fCopy); + } + + if (cuInfo.fModel != null) + cuInfo.fModel + .addAnnotationModelListener(fGlobalAnnotationModelListener); + + if (requestor instanceof IProblemRequestorExtension) { + IProblemRequestorExtension extension = (IProblemRequestorExtension) requestor; + extension.setIsActive(isHandlingTemporaryProblems()); + } + + return cuInfo; + } + + private void setUpSynchronization(CompilationUnitInfo cuInfo) { + IDocument document = cuInfo.fTextFileBuffer.getDocument(); + IAnnotationModel model = cuInfo.fModel; + + if (document instanceof ISynchronizable + && model instanceof ISynchronizable) { + Object lock = ((ISynchronizable) document).getLockObject(); + ((ISynchronizable) model).setLockObject(lock); + } + } + + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, + * org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo) + */ + protected void disposeFileInfo(Object element, FileInfo info) { + if (info instanceof CompilationUnitInfo) { + CompilationUnitInfo cuInfo = (CompilationUnitInfo) info; + + try { + cuInfo.fCopy.discardWorkingCopy(); + } catch (JavaModelException x) { + handleCoreException(x, x.getMessage()); + } + + if (cuInfo.fModel != null) + cuInfo.fModel + .removeAnnotationModelListener(fGlobalAnnotationModelListener); + } + super.disposeFileInfo(element, info); + } + + protected void commitWorkingCopy(IProgressMonitor monitor, Object element, + CompilationUnitInfo info, boolean overwrite) throws CoreException { + synchronized (info.fCopy) { + info.fCopy.reconcile(); + } + + IDocument document = info.fTextFileBuffer.getDocument(); + IResource resource = info.fCopy.getResource(); + + Assert.isTrue(resource instanceof IFile); + if (!resource.exists()) { + // underlying resource has been deleted, just recreate file, ignore + // the rest + createFileFromDocument(monitor, (IFile) resource, document); + return; + } + + if (fSavePolicy != null) + fSavePolicy.preSave(info.fCopy); + + try { + + fIsAboutToSave = true; + info.fCopy.commitWorkingCopy(overwrite, monitor); + + } catch (CoreException x) { + // inform about the failure + fireElementStateChangeFailed(element); + throw x; + } catch (RuntimeException x) { + // inform about the failure + fireElementStateChangeFailed(element); + throw x; + } finally { + fIsAboutToSave = false; + } + + // If here, the dirty state of the editor will change to "not dirty". + // Thus, the state changing flag will be reset. + if (info.fModel instanceof AbstractMarkerAnnotationModel) { + AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; + model.updateMarkers(document); + } + + if (fSavePolicy != null) { + ICompilationUnit unit = fSavePolicy.postSave(info.fCopy); + if (unit != null + && info.fModel instanceof AbstractMarkerAnnotationModel) { + IResource r = unit.getResource(); + IMarker[] markers = r.findMarkers(IMarker.MARKER, true, + IResource.DEPTH_ZERO); + if (markers != null && markers.length > 0) { + AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel; + for (int i = 0; i < markers.length; i++) + model.updateMarker(document, markers[i], null); + } + } + } + + } + + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, + * org.eclipse.jface.text.IDocument, boolean) + */ + protected DocumentProviderOperation createSaveOperation( + final Object element, final IDocument document, + final boolean overwrite) throws CoreException { + // final FileInfo info= getFileInfo(element); + // if (info instanceof CompilationUnitInfo) { + // return new DocumentProviderOperation() { + // /* + // * @see + // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) + // */ + // protected void execute(IProgressMonitor monitor) throws CoreException + // { + // commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, + // overwrite); + // } + // /* + // * @see + // org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() + // */ + // public ISchedulingRule getSchedulingRule() { + // if (info.fElement instanceof IFileEditorInput) { + // IFile file= ((IFileEditorInput) info.fElement).getFile(); + // IResourceRuleFactory ruleFactory= + // ResourcesPlugin.getWorkspace().getRuleFactory(); + // if (file == null || !file.exists()) + // return ruleFactory.createRule(file); + // else + // return ruleFactory.modifyRule(file); + // } else + // return null; + // } + // }; + // } + // return null; + final FileInfo info = getFileInfo(element); + if (info instanceof CompilationUnitInfo) { + return new DocumentProviderOperation() { + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor) + */ + protected void execute(IProgressMonitor monitor) + throws CoreException { + commitWorkingCopy(monitor, element, + (CompilationUnitInfo) info, overwrite); + } + + /* + * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule() + */ + public ISchedulingRule getSchedulingRule() { + if (info.fElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) info.fElement) + .getFile(); + return computeSchedulingRule(file); + } else + return null; + } + }; + } + return null; + } + + /* + * (non-Javadoc) Method declared on AbstractDocumentProvider + */ + // protected IDocument createDocument(Object element) throws CoreException { + // if (element instanceof IEditorInput) { + // Document document = new PartiallySynchronizedDocument(); + // if (setDocumentContent(document, (IEditorInput) element, + // getEncoding(element))) { + // initializeDocument(document, (IEditorInput) element); + // + // // + // // IDocument document = super.createDocument(element); + // // if (document != null) { + // // IDocumentPartitioner partitioner = null; + // // if (element instanceof FileEditorInput) { + // // IFile file = (IFile) ((FileEditorInput) + // element).getAdapter(IFile.class); + // // String filename = file.getLocation().toString(); + // // String extension = filename.substring(filename.lastIndexOf("."), + // filename.length()); + // // // System.out.println(extension); + // // if (extension.equalsIgnoreCase(".html") || + // extension.equalsIgnoreCase(".htm")) { + // // // html + // // partitioner = createHTMLPartitioner(); + // // } else if (extension.equalsIgnoreCase(".xml")) { + // // // xml + // // partitioner = createXMLPartitioner(); + // // } else if (extension.equalsIgnoreCase(".js")) { + // // // javascript + // // partitioner = createJavaScriptPartitioner(); + // // } else if (extension.equalsIgnoreCase(".css")) { + // // // cascading style sheets + // // partitioner = createCSSPartitioner(); + // // } else if (extension.equalsIgnoreCase(".tpl")) { + // // // smarty ? + // // partitioner = createSmartyPartitioner(); + // // } else if (extension.equalsIgnoreCase(".inc")) { + // // // php include files ? + // // partitioner = createIncludePartitioner(); + // // } + // // } + // // + // // if (partitioner == null) { + // // partitioner = createPHPPartitioner(); + // // } + // // document.setDocumentPartitioner(partitioner); + // // partitioner.connect(document); + // } + // return document; + // } + // return null; + // } + // /** + // * Return a partitioner for .html files. + // */ + // private IDocumentPartitioner createHTMLPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createIncludePartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createJavaScriptPartitioner() { + // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES); + // } + /** + * Creates a line tracker working with the same line delimiters as the + * document of the given element. Assumes the element to be managed by this + * document provider. + * + * @param element + * the element serving as blue print + * @return a line tracker based on the same line delimiters as the element's + * document + */ + public ILineTracker createLineTracker(Object element) { + return new DefaultLineTracker(); + } + + // /** + // * Return a partitioner for .php files. + // */ + // private IDocumentPartitioner createPHPPartitioner() { + // return new DefaultPartitioner(getPHPPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createSmartyPartitioner() { + // return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES); + // } + // + // private IDocumentPartitioner createXMLPartitioner() { + // return new DefaultPartitioner(getXMLPartitionScanner(), TYPES); + // } + // + // /** + // * Return a scanner for creating html partitions. + // */ + // private PHPPartitionScanner getHTMLPartitionScanner() { + // if (HTML_PARTITION_SCANNER == null) + // HTML_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE); + // return HTML_PARTITION_SCANNER; + // } + // /** + // * Return a scanner for creating php partitions. + // */ + // private PHPPartitionScanner getPHPPartitionScanner() { + // if (PHP_PARTITION_SCANNER == null) + // PHP_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE); + // return PHP_PARTITION_SCANNER; + // } + // + // /** + // * Return a scanner for creating smarty partitions. + // */ + // private PHPPartitionScanner getSmartyPartitionScanner() { + // if (SMARTY_PARTITION_SCANNER == null) + // SMARTY_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE); + // return SMARTY_PARTITION_SCANNER; + // } + // + // /** + // * Return a scanner for creating xml partitions. + // */ + // private PHPPartitionScanner getXMLPartitionScanner() { + // if (XML_PARTITION_SCANNER == null) + // XML_PARTITION_SCANNER = new + // PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE); + // return XML_PARTITION_SCANNER; + // } + + // protected void initializeDocument(IDocument document, IEditorInput + // editorInput) { + // if (document != null) { + // JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + // IDocumentPartitioner partitioner = null; + // if (editorInput != null && editorInput instanceof FileEditorInput) { + // IFile file = (IFile) ((FileEditorInput) + // editorInput).getAdapter(IFile.class); + // String filename = file.getLocation().toString(); + // String extension = filename.substring(filename.lastIndexOf("."), + // filename.length()); + // partitioner = tools.createDocumentPartitioner(extension); + // } else { + // partitioner = tools.createDocumentPartitioner(".php"); + // } + // document.setDocumentPartitioner(partitioner); + // partitioner.connect(document); + // } + // } + + /* + * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, + * org.eclipse.core.runtime.IProgressMonitor) + */ + // protected void doResetDocument(Object element, IProgressMonitor monitor) + // throws CoreException { + // if (element == null) + // return; + // + // ElementInfo elementInfo= getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; + // + // IDocument document; + // IStatus status= null; + // + // try { + // + // ICompilationUnit original= (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource= original.getResource(); + // if (resource instanceof IFile) { + // + // IFile file= (IFile) resource; + // + // try { + // refreshFile(file, monitor); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); + // //$NON-NLS-1$ + // } + // + // IFileEditorInput input= new FileEditorInput(file); + // document= super.createDocument(input); + // + // } else { + // document= createEmptyDocument(); + // } + // + // } catch (CoreException x) { + // document= createEmptyDocument(); + // status= x.getStatus(); + // } + // + // fireElementContentAboutToBeReplaced(element); + // + // removeUnchangedElementListeners(element, info); + // info.fDocument.set(document.get()); + // info.fCanBeSaved= false; + // info.fStatus= status; + // addUnchangedElementListeners(element, info); + // + // fireElementContentReplaced(element); + // fireElementDirtyStateChanged(element, false); + // + // } else { + // super.doResetDocument(element, monitor); + // } + // } + /* + * @see AbstractDocumentProvider#resetDocument(Object) + */ + // public void resetDocument(Object element) throws CoreException { + // if (element == null) + // return; + // + // ElementInfo elementInfo = getElementInfo(element); + // if (elementInfo instanceof CompilationUnitInfo) { + // CompilationUnitInfo info = (CompilationUnitInfo) elementInfo; + // + // IDocument document; + // IStatus status = null; + // + // try { + // + // ICompilationUnit original = (ICompilationUnit) + // info.fCopy.getOriginalElement(); + // IResource resource = original.getResource(); + // if (resource instanceof IFile) { + // + // IFile file = (IFile) resource; + // + // try { + // refreshFile(file); + // } catch (CoreException x) { + // handleCoreException(x, + // PHPEditorMessages.getString("PHPDocumentProvider.error.resetDocument")); + // //$NON-NLS-1$ + // } + // + // IFileEditorInput input = new FileEditorInput(file); + // document = super.createDocument(input); + // + // } else { + // document = new Document(); + // } + // + // } catch (CoreException x) { + // document = new Document(); + // status = x.getStatus(); + // } + // + // fireElementContentAboutToBeReplaced(element); + // + // removeUnchangedElementListeners(element, info); + // info.fDocument.set(document.get()); + // info.fCanBeSaved = false; + // info.fStatus = status; + // addUnchangedElementListeners(element, info); + // + // fireElementContentReplaced(element); + // fireElementDirtyStateChanged(element, false); + // + // } else { + // super.resetDocument(element); + // } + // } + /** + * Saves the content of the given document to the given element. This is + * only performed when this provider initiated the save. + * + * @param monitor + * the progress monitor + * @param element + * the element to which to save + * @param document + * the document to save + * @param overwrite + * true if the save should be enforced + */ + public void saveDocumentContent(IProgressMonitor monitor, Object element, + IDocument document, boolean overwrite) throws CoreException { + if (!fIsAboutToSave) + return; + super.saveDocument(monitor, element, document, overwrite); + // if (!fIsAboutToSave) + // return; + // + // if (element instanceof IFileEditorInput) { + // IFileEditorInput input = (IFileEditorInput) element; + // try { + // String encoding = getEncoding(element); + // if (encoding == null) + // encoding = ResourcesPlugin.getEncoding(); + // InputStream stream = new + // ByteArrayInputStream(document.get().getBytes(encoding)); + // IFile file = input.getFile(); + // file.setContents(stream, overwrite, true, monitor); + // } catch (IOException x) { + // IStatus s = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, + // IStatus.OK, x.getMessage(), x); + // throw new CoreException(s); + // } + // } + } + + /** + * Returns the underlying resource for the given element. + * + * @param the + * element + * @return the underlying resource of the given element + */ + // public IResource getUnderlyingResource(Object element) { + // if (element instanceof IFileEditorInput) { + // IFileEditorInput input = (IFileEditorInput) element; + // return input.getFile(); + // } + // return null; + // } + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object) + */ + public ICompilationUnit getWorkingCopy(Object element) { + FileInfo fileInfo = getFileInfo(element); + if (fileInfo instanceof CompilationUnitInfo) { + CompilationUnitInfo info = (CompilationUnitInfo) fileInfo; + return info.fCopy; + } + return null; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown() + */ + public void shutdown() { + PHPeclipsePlugin.getDefault().getPreferenceStore() + .removePropertyChangeListener(fPropertyListener); + Iterator e = getConnectedElementsIterator(); + while (e.hasNext()) + disconnect(e.next()); + } + + /** + * Returns the preference whether handling temporary problems is enabled. + */ + protected boolean isHandlingTemporaryProblems() { + IPreferenceStore store = PHPeclipsePlugin.getDefault() + .getPreferenceStore(); + return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS); + } + + /** + * Switches the state of problem acceptance according to the value in the + * preference store. + */ + protected void enableHandlingTemporaryProblems() { + boolean enable = isHandlingTemporaryProblems(); + for (Iterator iter = getFileInfosIterator(); iter.hasNext();) { + FileInfo info = (FileInfo) iter.next(); + if (info.fModel instanceof IProblemRequestorExtension) { + IProblemRequestorExtension extension = (IProblemRequestorExtension) info.fModel; + extension.setIsActive(enable); + } + } + } + + /** + * Adds a listener that reports changes from all compilation unit annotation + * models. + */ + public void addGlobalAnnotationModelListener( + IAnnotationModelListener listener) { + fGlobalAnnotationModelListener.addListener(listener); + } + + /** + * Removes the listener. + */ + public void removeGlobalAnnotationModelListener( + IAnnotationModelListener listener) { + fGlobalAnnotationModelListener.removeListener(listener); + } + + /** + * Computes the scheduling rule needed to create or modify a resource. If + * the resource exists, its modify rule is returned. If it does not, the + * resource hierarchy is iterated towards the workspace root to find the + * first parent of toCreateOrModify that exists. Then the + * 'create' rule for the last non-existing resource is returned. + *

+ * XXX This is a workaround for + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=67601 + * IResourceRuleFactory.createRule should iterate the hierarchy itself. + *

+ *

+ * XXX to be replaced by call to + * TextFileDocumentProvider.computeSchedulingRule after 3.0 + *

+ * + * @param toCreateOrModify + * the resource to create or modify + * @return the minimal scheduling rule needed to modify or create a resource + */ + protected ISchedulingRule computeSchedulingRule(IResource toCreateOrModify) { + IResourceRuleFactory factory = ResourcesPlugin.getWorkspace() + .getRuleFactory(); + if (toCreateOrModify.exists()) { + return factory.modifyRule(toCreateOrModify); + } else { + IResource parent = toCreateOrModify; + do { + toCreateOrModify = parent; + parent = toCreateOrModify.getParent(); + } while (parent != null && !parent.exists()); + + return factory.createRule(toCreateOrModify); + } + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java new file mode 100644 index 0000000..cfc3857 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java @@ -0,0 +1,6106 @@ +package net.sourceforge.phpeclipse.phpeditor; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.BreakIterator; +import java.text.CharacterIterator; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.StringTokenizer; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IImportContainer; +import net.sourceforge.phpdt.core.IImportDeclaration; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; +import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; +import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup; +import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter; +import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl; +import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator; +import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder; +import net.sourceforge.phpdt.internal.ui.text.JavaWordIterator; +import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher; +import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter; +import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaExpandHover; +import net.sourceforge.phpdt.internal.ui.viewsupport.ISelectionListenerWithAST; +import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider; +import net.sourceforge.phpdt.internal.ui.viewsupport.SelectionListenerWithASTManager; +import net.sourceforge.phpdt.ui.IContextMenuConstants; +import net.sourceforge.phpdt.ui.JavaUI; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction; +import net.sourceforge.phpdt.ui.actions.OpenEditorActionGroup; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration; +import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.ExternalEditorInput; +import net.sourceforge.phpeclipse.ui.editor.BrowserUtil; +import net.sourceforge.phpeclipse.webbrowser.views.BrowserView; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Preferences; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.GroupMarker; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DefaultInformationControl; +import org.eclipse.jface.text.DocumentEvent; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentExtension4; +import org.eclipse.jface.text.IDocumentListener; +import org.eclipse.jface.text.IInformationControl; +import org.eclipse.jface.text.IInformationControlCreator; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ISelectionValidator; +import org.eclipse.jface.text.ISynchronizable; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextInputListener; +import org.eclipse.jface.text.ITextPresentationListener; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.ITextViewerExtension2; +import org.eclipse.jface.text.ITextViewerExtension4; +import org.eclipse.jface.text.ITextViewerExtension5; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.TextPresentation; +import org.eclipse.jface.text.TextSelection; +import org.eclipse.jface.text.TextUtilities; +import org.eclipse.jface.text.information.IInformationProvider; +import org.eclipse.jface.text.information.InformationPresenter; +import org.eclipse.jface.text.link.LinkedModeModel; +import org.eclipse.jface.text.reconciler.IReconciler; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.AnnotationRulerColumn; +import org.eclipse.jface.text.source.CompositeRuler; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IAnnotationModelExtension; +import org.eclipse.jface.text.source.IOverviewRuler; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.ISourceViewerExtension2; +import org.eclipse.jface.text.source.IVerticalRuler; +import org.eclipse.jface.text.source.IVerticalRulerColumn; +import org.eclipse.jface.text.source.OverviewRuler; +import org.eclipse.jface.text.source.SourceViewerConfiguration; +import org.eclipse.jface.text.source.projection.ProjectionSupport; +import org.eclipse.jface.text.source.projection.ProjectionViewer; +import org.eclipse.jface.util.IPropertyChangeListener; +//incastrix +//import org.eclipse.jface.util.ListenerList; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.DoubleClickEvent; +import org.eclipse.jface.viewers.IDoubleClickListener; +import org.eclipse.jface.viewers.IPostSelectionProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.BidiSegmentEvent; +import org.eclipse.swt.custom.BidiSegmentListener; +import org.eclipse.swt.custom.ST; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.FocusListener; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.KeyListener; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseListener; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Cursor; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IPageLayout; +import org.eclipse.ui.IPartService; +import org.eclipse.ui.ISelectionListener; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWindowListener; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.actions.ActionContext; +import org.eclipse.ui.actions.ActionGroup; +import org.eclipse.ui.editors.text.DefaultEncodingSupport; +import org.eclipse.ui.editors.text.EditorsUI; +import org.eclipse.ui.editors.text.IEncodingSupport; +import org.eclipse.ui.ide.FileStoreEditorInput; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.part.IShowInSource; +import org.eclipse.ui.part.IShowInTargetList; +import org.eclipse.ui.part.ShowInContext; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; +import org.eclipse.ui.texteditor.AnnotationPreference; +import org.eclipse.ui.texteditor.ChainedPreferenceStore; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.IEditorStatusLine; +import org.eclipse.ui.texteditor.ITextEditorActionConstants; +import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; +import org.eclipse.ui.texteditor.IUpdate; +import org.eclipse.ui.texteditor.MarkerAnnotation; +import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; +import org.eclipse.ui.texteditor.TextEditorAction; +import org.eclipse.ui.texteditor.TextNavigationAction; +import org.eclipse.ui.texteditor.TextOperationAction; +import org.eclipse.ui.views.contentoutline.ContentOutline; +import org.eclipse.ui.views.contentoutline.IContentOutlinePage; +import org.eclipse.ui.views.tasklist.TaskList; + +/** + * PHP specific text editor. + */ +public abstract class PHPEditor extends AbstractDecoratedTextEditor implements + IViewPartInputProvider, IShowInTargetList, IShowInSource { + // extends StatusTextEditor implements IViewPartInputProvider { // extends + // TextEditor { + + /** + * Internal implementation class for a change listener. + * + * @since 3.0 + */ + protected abstract class AbstractSelectionChangedListener implements + ISelectionChangedListener { + + /** + * Installs this selection changed listener with the given selection + * provider. If the selection provider is a post selection provider, + * post selection changed events are the preferred choice, otherwise + * normal selection changed events are requested. + * + * @param selectionProvider + */ + public void install(ISelectionProvider selectionProvider) { + if (selectionProvider == null) + return; + + if (selectionProvider instanceof IPostSelectionProvider) { + IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; + provider.addPostSelectionChangedListener(this); + } else { + selectionProvider.addSelectionChangedListener(this); + } + } + + /** + * Removes this selection changed listener from the given selection + * provider. + * + * @param selectionProvider + * the selection provider + */ + public void uninstall(ISelectionProvider selectionProvider) { + if (selectionProvider == null) + return; + + if (selectionProvider instanceof IPostSelectionProvider) { + IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; + provider.removePostSelectionChangedListener(this); + } else { + selectionProvider.removeSelectionChangedListener(this); + } + } + } + + /** + * Updates the Java outline page selection and this editor's range + * indicator. + * + * @since 3.0 + */ + private class EditorSelectionChangedListener extends + AbstractSelectionChangedListener { + + /* + * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent event) { + // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161 + PHPEditor.this.selectionChanged(); + } + } + + /** + * "Smart" runnable for updating the outline page's selection. + */ + // class OutlinePageSelectionUpdater implements Runnable { + // + // /** Has the runnable already been posted? */ + // private boolean fPosted = false; + // + // public OutlinePageSelectionUpdater() { + // } + // + // /* + // * @see Runnable#run() + // */ + // public void run() { + // synchronizeOutlinePageSelection(); + // fPosted = false; + // } + // + // /** + // * Posts this runnable into the event queue. + // */ + // public void post() { + // if (fPosted) + // return; + // + // Shell shell = getSite().getShell(); + // if (shell != null & !shell.isDisposed()) { + // fPosted = true; + // shell.getDisplay().asyncExec(this); + // } + // } + // }; + class SelectionChangedListener implements ISelectionChangedListener { + public void selectionChanged(SelectionChangedEvent event) { + doSelectionChanged(event); + } + }; + + /** + * Adapts an options {@link java.util.Map}to + * {@link org.eclipse.jface.preference.IPreferenceStore}. + *

+ * This preference store is read-only i.e. write access throws an + * {@link java.lang.UnsupportedOperationException}. + *

+ * + * @since 3.0 + */ + private static class OptionsAdapter implements IPreferenceStore { + + /** + * A property change event filter. + */ + public interface IPropertyChangeEventFilter { + + /** + * Should the given event be filtered? + * + * @param event + * The property change event. + * @return true iff the given event should be + * filtered. + */ + public boolean isFiltered(PropertyChangeEvent event); + + } + + /** + * Property change listener. Listens for events in the options Map and + * fires a {@link org.eclipse.jface.util.PropertyChangeEvent}on this + * adapter with arguments from the received event. + */ + private class PropertyChangeListener implements IPropertyChangeListener { + + /** + * {@inheritDoc} + */ + public void propertyChange(PropertyChangeEvent event) { + if (getFilter().isFiltered(event)) + return; + + if (event.getNewValue() == null) + fOptions.remove(event.getProperty()); + else + fOptions.put(event.getProperty(), event.getNewValue()); + + firePropertyChangeEvent(event.getProperty(), event + .getOldValue(), event.getNewValue()); + } + } + + /** Listeners on this adapter */ + private ListenerList fListeners = new ListenerList(); + + /** Listener on the adapted options Map */ + private IPropertyChangeListener fListener = new PropertyChangeListener(); + + /** Adapted options Map */ + private Map fOptions; + + /** Preference store through which events are received. */ + private IPreferenceStore fMockupPreferenceStore; + + /** Property event filter. */ + private IPropertyChangeEventFilter fFilter; + + /** + * Initialize with the given options. + * + * @param options + * The options to wrap + * @param mockupPreferenceStore + * the mock-up preference store + * @param filter + * the property change filter + */ + public OptionsAdapter(Map options, + IPreferenceStore mockupPreferenceStore, + IPropertyChangeEventFilter filter) { + fMockupPreferenceStore = mockupPreferenceStore; + fOptions = options; + setFilter(filter); + } + + /** + * {@inheritDoc} + */ + public void addPropertyChangeListener(IPropertyChangeListener listener) { + if (fListeners.size() == 0) + fMockupPreferenceStore.addPropertyChangeListener(fListener); + fListeners.add(listener); + } + + /** + * {@inheritDoc} + */ + public void removePropertyChangeListener( + IPropertyChangeListener listener) { + fListeners.remove(listener); + if (fListeners.size() == 0) + fMockupPreferenceStore.removePropertyChangeListener(fListener); + } + + /** + * {@inheritDoc} + */ + public boolean contains(String name) { + return fOptions.containsKey(name); + } + + /** + * {@inheritDoc} + */ + public void firePropertyChangeEvent(String name, Object oldValue, + Object newValue) { + PropertyChangeEvent event = new PropertyChangeEvent(this, name, + oldValue, newValue); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) + ((IPropertyChangeListener) listeners[i]).propertyChange(event); + } + + /** + * {@inheritDoc} + */ + public boolean getBoolean(String name) { + boolean value = BOOLEAN_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) + value = s.equals(TRUE); + return value; + } + + /** + * {@inheritDoc} + */ + public boolean getDefaultBoolean(String name) { + return BOOLEAN_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public double getDefaultDouble(String name) { + return DOUBLE_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public float getDefaultFloat(String name) { + return FLOAT_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public int getDefaultInt(String name) { + return INT_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public long getDefaultLong(String name) { + return LONG_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public String getDefaultString(String name) { + return STRING_DEFAULT_DEFAULT; + } + + /** + * {@inheritDoc} + */ + public double getDouble(String name) { + double value = DOUBLE_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Double(s).doubleValue(); + } catch (NumberFormatException e) { + } + } + return value; + } + + /** + * {@inheritDoc} + */ + public float getFloat(String name) { + float value = FLOAT_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Float(s).floatValue(); + } catch (NumberFormatException e) { + } + } + return value; + } + + /** + * {@inheritDoc} + */ + public int getInt(String name) { + int value = INT_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Integer(s).intValue(); + } catch (NumberFormatException e) { + } + } + return value; + } + + /** + * {@inheritDoc} + */ + public long getLong(String name) { + long value = LONG_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Long(s).longValue(); + } catch (NumberFormatException e) { + } + } + return value; + } + + /** + * {@inheritDoc} + */ + public String getString(String name) { + String value = (String) fOptions.get(name); + if (value == null) + value = STRING_DEFAULT_DEFAULT; + return value; + } + + /** + * {@inheritDoc} + */ + public boolean isDefault(String name) { + return false; + } + + /** + * {@inheritDoc} + */ + public boolean needsSaving() { + return !fOptions.isEmpty(); + } + + /** + * {@inheritDoc} + */ + public void putValue(String name, String value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, double value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, float value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, int value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, long value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, String defaultObject) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setDefault(String name, boolean value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setToDefault(String name) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, double value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, float value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, int value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, long value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, String value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, boolean value) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the adapted options Map. + * + * @return Returns the adapted options Map. + */ + public Map getOptions() { + return fOptions; + } + + /** + * Returns the mock-up preference store, events are received through + * this preference store. + * + * @return Returns the mock-up preference store. + */ + public IPreferenceStore getMockupPreferenceStore() { + return fMockupPreferenceStore; + } + + /** + * Set the event filter to the given filter. + * + * @param filter + * The new filter. + */ + public void setFilter(IPropertyChangeEventFilter filter) { + fFilter = filter; + } + + /** + * Returns the event filter. + * + * @return The event filter. + */ + public IPropertyChangeEventFilter getFilter() { + return fFilter; + } + } + + /* + * Link mode. + */ + // class MouseClickListener implements KeyListener, MouseListener, + // MouseMoveListener, FocusListener, PaintListener, + // IPropertyChangeListener, IDocumentListener, ITextInputListener { + // + // /** The session is active. */ + // private boolean fActive; + // + // /** The currently active style range. */ + // private IRegion fActiveRegion; + // + // /** The currently active style range as position. */ + // private Position fRememberedPosition; + // + // /** The hand cursor. */ + // private Cursor fCursor; + // + // /** The link color. */ + // private Color fColor; + // + // /** The key modifier mask. */ + // private int fKeyModifierMask; + // + // public void deactivate() { + // deactivate(false); + // } + // + // public void deactivate(boolean redrawAll) { + // if (!fActive) + // return; + // + // repairRepresentation(redrawAll); + // fActive = false; + // } + // + // public void install() { + // + // ISourceViewer sourceViewer = getSourceViewer(); + // if (sourceViewer == null) + // return; + // + // StyledText text = sourceViewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // + // updateColor(sourceViewer); + // + // sourceViewer.addTextInputListener(this); + // + // IDocument document = sourceViewer.getDocument(); + // if (document != null) + // document.addDocumentListener(this); + // + // text.addKeyListener(this); + // text.addMouseListener(this); + // text.addMouseMoveListener(this); + // text.addFocusListener(this); + // text.addPaintListener(this); + // + // updateKeyModifierMask(); + // + // IPreferenceStore preferenceStore = getPreferenceStore(); + // preferenceStore.addPropertyChangeListener(this); + // } + // + // private void updateKeyModifierMask() { + // String modifiers = + // getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); + // fKeyModifierMask = computeStateMask(modifiers); + // if (fKeyModifierMask == -1) { + // // Fallback to stored state mask + // fKeyModifierMask = + // getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); + // } + // ; + // } + // + // private int computeStateMask(String modifiers) { + // if (modifiers == null) + // return -1; + // + // if (modifiers.length() == 0) + // return SWT.NONE; + // + // int stateMask = 0; + // StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + // ",;.:+-* + // "); //$NON-NLS-1$ + // while (modifierTokenizer.hasMoreTokens()) { + // int modifier = + // EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); + // if (modifier == 0 || (stateMask & modifier) == modifier) + // return -1; + // stateMask = stateMask | modifier; + // } + // return stateMask; + // } + // + // public void uninstall() { + // + // if (fColor != null) { + // fColor.dispose(); + // fColor = null; + // } + // + // if (fCursor != null) { + // fCursor.dispose(); + // fCursor = null; + // } + // + // ISourceViewer sourceViewer = getSourceViewer(); + // if (sourceViewer == null) + // return; + // + // sourceViewer.removeTextInputListener(this); + // + // IDocument document = sourceViewer.getDocument(); + // if (document != null) + // document.removeDocumentListener(this); + // + // IPreferenceStore preferenceStore = getPreferenceStore(); + // if (preferenceStore != null) + // preferenceStore.removePropertyChangeListener(this); + // + // StyledText text = sourceViewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // + // text.removeKeyListener(this); + // text.removeMouseListener(this); + // text.removeMouseMoveListener(this); + // text.removeFocusListener(this); + // text.removePaintListener(this); + // } + // + // /* + // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + // */ + // public void propertyChange(PropertyChangeEvent event) { + // if (event.getProperty().equals(PHPEditor.LINK_COLOR)) { + // ISourceViewer viewer = getSourceViewer(); + // if (viewer != null) + // updateColor(viewer); + // } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { + // updateKeyModifierMask(); + // } + // } + // + // private void updateColor(ISourceViewer viewer) { + // if (fColor != null) + // fColor.dispose(); + // + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // + // Display display = text.getDisplay(); + // fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, + // display); + // } + // + // /** + // * Creates a color from the information stored in the given preference + // store. Returns null if there is no such + // * information available. + // */ + // private Color createColor(IPreferenceStore store, String key, Display + // display) { + // + // RGB rgb = null; + // + // if (store.contains(key)) { + // + // if (store.isDefault(key)) + // rgb = PreferenceConverter.getDefaultColor(store, key); + // else + // rgb = PreferenceConverter.getColor(store, key); + // + // if (rgb != null) + // return new Color(display, rgb); + // } + // + // return null; + // } + // + // private void repairRepresentation() { + // repairRepresentation(false); + // } + // + // private void repairRepresentation(boolean redrawAll) { + // + // if (fActiveRegion == null) + // return; + // + // ISourceViewer viewer = getSourceViewer(); + // if (viewer != null) { + // resetCursor(viewer); + // + // int offset = fActiveRegion.getOffset(); + // int length = fActiveRegion.getLength(); + // + // // remove style + // if (!redrawAll && viewer instanceof ITextViewerExtension2) + // ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, + // length); + // else + // viewer.invalidateTextPresentation(); + // + // // remove underline + // if (viewer instanceof ITextViewerExtension3) { + // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; + // offset = extension.modelOffset2WidgetOffset(offset); + // } else { + // offset -= viewer.getVisibleRegion().getOffset(); + // } + // + // StyledText text = viewer.getTextWidget(); + // try { + // text.redrawRange(offset, length, true); + // } catch (IllegalArgumentException x) { + // PHPeclipsePlugin.log(x); + // } + // } + // + // fActiveRegion = null; + // } + // + // // will eventually be replaced by a method provided by jdt.core + // private IRegion selectWord(IDocument document, int anchor) { + // + // try { + // int offset = anchor; + // char c; + // + // while (offset >= 0) { + // c = document.getChar(offset); + // if (!Scanner.isPHPIdentifierPart(c)) + // break; + // --offset; + // } + // + // int start = offset; + // + // offset = anchor; + // int length = document.getLength(); + // + // while (offset < length) { + // c = document.getChar(offset); + // if (!Scanner.isPHPIdentifierPart(c)) + // break; + // ++offset; + // } + // + // int end = offset; + // + // if (start == end) + // return new Region(start, 0); + // else + // return new Region(start + 1, end - start - 1); + // + // } catch (BadLocationException x) { + // return null; + // } + // } + // + // IRegion getCurrentTextRegion(ISourceViewer viewer) { + // + // int offset = getCurrentTextOffset(viewer); + // if (offset == -1) + // return null; + // + // return null; + // // IJavaElement input= SelectionConverter.getInput(PHPEditor.this); + // // if (input == null) + // // return null; + // // + // // try { + // // + // // IJavaElement[] elements= null; + // // synchronized (input) { + // // elements= ((ICodeAssist) input).codeSelect(offset, 0); + // // } + // // + // // if (elements == null || elements.length == 0) + // // return null; + // // + // // return selectWord(viewer.getDocument(), offset); + // // + // // } catch (JavaModelException e) { + // // return null; + // // } + // } + // + // private int getCurrentTextOffset(ISourceViewer viewer) { + // + // try { + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return -1; + // + // Display display = text.getDisplay(); + // Point absolutePosition = display.getCursorLocation(); + // Point relativePosition = text.toControl(absolutePosition); + // + // int widgetOffset = text.getOffsetAtLocation(relativePosition); + // if (viewer instanceof ITextViewerExtension3) { + // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; + // return extension.widgetOffset2ModelOffset(widgetOffset); + // } else { + // return widgetOffset + viewer.getVisibleRegion().getOffset(); + // } + // + // } catch (IllegalArgumentException e) { + // return -1; + // } + // } + // + // private void highlightRegion(ISourceViewer viewer, IRegion region) { + // + // if (region.equals(fActiveRegion)) + // return; + // + // repairRepresentation(); + // + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // + // // highlight region + // int offset = 0; + // int length = 0; + // + // if (viewer instanceof ITextViewerExtension3) { + // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; + // IRegion widgetRange = extension.modelRange2WidgetRange(region); + // if (widgetRange == null) + // return; + // + // offset = widgetRange.getOffset(); + // length = widgetRange.getLength(); + // + // } else { + // offset = region.getOffset() - viewer.getVisibleRegion().getOffset(); + // length = region.getLength(); + // } + // + // StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset); + // Color foregroundColor = fColor; + // Color backgroundColor = oldStyleRange == null ? text.getBackground() : + // oldStyleRange.background; + // StyleRange styleRange = new StyleRange(offset, length, foregroundColor, + // backgroundColor); + // text.setStyleRange(styleRange); + // + // // underline + // text.redrawRange(offset, length, true); + // + // fActiveRegion = region; + // } + // + // private void activateCursor(ISourceViewer viewer) { + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // Display display = text.getDisplay(); + // if (fCursor == null) + // fCursor = new Cursor(display, SWT.CURSOR_HAND); + // text.setCursor(fCursor); + // } + // + // private void resetCursor(ISourceViewer viewer) { + // StyledText text = viewer.getTextWidget(); + // if (text != null && !text.isDisposed()) + // text.setCursor(null); + // + // if (fCursor != null) { + // fCursor.dispose(); + // fCursor = null; + // } + // } + // + // /* + // * @see + // org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) + // */ + // public void keyPressed(KeyEvent event) { + // + // if (fActive) { + // deactivate(); + // return; + // } + // + // if (event.keyCode != fKeyModifierMask) { + // deactivate(); + // return; + // } + // + // fActive = true; + // + // // removed for #25871 + // // + // // ISourceViewer viewer= getSourceViewer(); + // // if (viewer == null) + // // return; + // // + // // IRegion region= getCurrentTextRegion(viewer); + // // if (region == null) + // // return; + // // + // // highlightRegion(viewer, region); + // // activateCursor(viewer); + // } + // + // /* + // * @see + // org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) + // */ + // public void keyReleased(KeyEvent event) { + // + // if (!fActive) + // return; + // + // deactivate(); + // } + // + // /* + // * @see + // org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) + // */ + // public void mouseDoubleClick(MouseEvent e) { + // } + // + // /* + // * @see + // org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) + // */ + // public void mouseDown(MouseEvent event) { + // + // if (!fActive) + // return; + // + // if (event.stateMask != fKeyModifierMask) { + // deactivate(); + // return; + // } + // + // if (event.button != 1) { + // deactivate(); + // return; + // } + // } + // + // /* + // * @see + // org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) + // */ + // public void mouseUp(MouseEvent e) { + // + // if (!fActive) + // return; + // + // if (e.button != 1) { + // deactivate(); + // return; + // } + // + // boolean wasActive = fCursor != null; + // + // deactivate(); + // + // if (wasActive) { + // IAction action = getAction("OpenEditor"); //$NON-NLS-1$ + // if (action != null) + // action.run(); + // } + // } + // + // /* + // * @see + // org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) + // */ + // public void mouseMove(MouseEvent event) { + // + // if (event.widget instanceof Control && !((Control) + // event.widget).isFocusControl()) { + // deactivate(); + // return; + // } + // + // if (!fActive) { + // if (event.stateMask != fKeyModifierMask) + // return; + // // modifier was already pressed + // fActive = true; + // } + // + // ISourceViewer viewer = getSourceViewer(); + // if (viewer == null) { + // deactivate(); + // return; + // } + // + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) { + // deactivate(); + // return; + // } + // + // if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != + // 0) + // { + // deactivate(); + // return; + // } + // + // IRegion region = getCurrentTextRegion(viewer); + // if (region == null || region.getLength() == 0) { + // repairRepresentation(); + // return; + // } + // + // highlightRegion(viewer, region); + // activateCursor(viewer); + // } + // + // /* + // * @see + // org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) + // */ + // public void focusGained(FocusEvent e) { + // } + // + // /* + // * @see + // org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) + // */ + // public void focusLost(FocusEvent event) { + // deactivate(); + // } + // + // /* + // * @see + // org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) + // */ + // public void documentAboutToBeChanged(DocumentEvent event) { + // if (fActive && fActiveRegion != null) { + // fRememberedPosition = new Position(fActiveRegion.getOffset(), + // fActiveRegion.getLength()); + // try { + // event.getDocument().addPosition(fRememberedPosition); + // } catch (BadLocationException x) { + // fRememberedPosition = null; + // } + // } + // } + // + // /* + // * @see + // org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) + // */ + // public void documentChanged(DocumentEvent event) { + // if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) { + // event.getDocument().removePosition(fRememberedPosition); + // fActiveRegion = new Region(fRememberedPosition.getOffset(), + // fRememberedPosition.getLength()); + // } + // fRememberedPosition = null; + // + // ISourceViewer viewer = getSourceViewer(); + // if (viewer != null) { + // StyledText widget = viewer.getTextWidget(); + // if (widget != null && !widget.isDisposed()) { + // widget.getDisplay().asyncExec(new Runnable() { + // public void run() { + // deactivate(); + // } + // }); + // } + // } + // } + // + // /* + // * @see + // org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, + // * org.eclipse.jface.text.IDocument) + // */ + // public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument + // newInput) { + // if (oldInput == null) + // return; + // deactivate(); + // oldInput.removeDocumentListener(this); + // } + // + // /* + // * @see + // org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, + // * org.eclipse.jface.text.IDocument) + // */ + // public void inputDocumentChanged(IDocument oldInput, IDocument newInput) + // { + // if (newInput == null) + // return; + // newInput.addDocumentListener(this); + // } + // + // /* + // * @see PaintListener#paintControl(PaintEvent) + // */ + // public void paintControl(PaintEvent event) { + // if (fActiveRegion == null) + // return; + // + // ISourceViewer viewer = getSourceViewer(); + // if (viewer == null) + // return; + // + // StyledText text = viewer.getTextWidget(); + // if (text == null || text.isDisposed()) + // return; + // + // int offset = 0; + // int length = 0; + // + // if (viewer instanceof ITextViewerExtension3) { + // + // ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; + // IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset, + // length)); + // if (widgetRange == null) + // return; + // + // offset = widgetRange.getOffset(); + // length = widgetRange.getLength(); + // + // } else { + // + // IRegion region = viewer.getVisibleRegion(); + // if (!includes(region, fActiveRegion)) + // return; + // + // offset = fActiveRegion.getOffset() - region.getOffset(); + // length = fActiveRegion.getLength(); + // } + // + // // support for bidi + // Point minLocation = getMinimumLocation(text, offset, length); + // Point maxLocation = getMaximumLocation(text, offset, length); + // + // int x1 = minLocation.x; + // int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; + // int y = minLocation.y + text.getLineHeight() - 1; + // + // GC gc = event.gc; + // if (fColor != null && !fColor.isDisposed()) + // gc.setForeground(fColor); + // gc.drawLine(x1, y, x2, y); + // } + // + // private boolean includes(IRegion region, IRegion position) { + // return position.getOffset() >= region.getOffset() + // && position.getOffset() + position.getLength() <= region.getOffset() + + // region.getLength(); + // } + // + // private Point getMinimumLocation(StyledText text, int offset, int length) + // { + // Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); + // + // for (int i = 0; i <= length; i++) { + // Point location = text.getLocationAtOffset(offset + i); + // + // if (location.x < minLocation.x) + // minLocation.x = location.x; + // if (location.y < minLocation.y) + // minLocation.y = location.y; + // } + // + // return minLocation; + // } + // + // private Point getMaximumLocation(StyledText text, int offset, int length) + // { + // Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + // + // for (int i = 0; i <= length; i++) { + // Point location = text.getLocationAtOffset(offset + i); + // + // if (location.x > maxLocation.x) + // maxLocation.x = location.x; + // if (location.y > maxLocation.y) + // maxLocation.y = location.y; + // } + // + // return maxLocation; + // } + // }; + /* + * Link mode. + */ + class MouseClickListener implements KeyListener, MouseListener, + MouseMoveListener, FocusListener, PaintListener, + IPropertyChangeListener, IDocumentListener, ITextInputListener, + ITextPresentationListener { + + /** The session is active. */ + private boolean fActive; + + /** The currently active style range. */ + private IRegion fActiveRegion; + + /** The currently active style range as position. */ + private Position fRememberedPosition; + + /** The hand cursor. */ + private Cursor fCursor; + + /** The link color. */ + private Color fColor; + + /** The key modifier mask. */ + private int fKeyModifierMask; + + public void deactivate() { + deactivate(false); + } + + public void deactivate(boolean redrawAll) { + if (!fActive) + return; + + repairRepresentation(redrawAll); + fActive = false; + } + + public void install() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) + return; + + StyledText text = sourceViewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + updateColor(sourceViewer); + + sourceViewer.addTextInputListener(this); + + IDocument document = sourceViewer.getDocument(); + if (document != null) + document.addDocumentListener(this); + + text.addKeyListener(this); + text.addMouseListener(this); + text.addMouseMoveListener(this); + text.addFocusListener(this); + text.addPaintListener(this); + + ((ITextViewerExtension4) sourceViewer) + .addTextPresentationListener(this); + + updateKeyModifierMask(); + + IPreferenceStore preferenceStore = getPreferenceStore(); + preferenceStore.addPropertyChangeListener(this); + } + + private void updateKeyModifierMask() { + String modifiers = getPreferenceStore().getString( + BROWSER_LIKE_LINKS_KEY_MODIFIER); + fKeyModifierMask = computeStateMask(modifiers); + if (fKeyModifierMask == -1) { + // Fall back to stored state mask + fKeyModifierMask = getPreferenceStore().getInt( + BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); + } + } + + private int computeStateMask(String modifiers) { + if (modifiers == null) + return -1; + + if (modifiers.length() == 0) + return SWT.NONE; + + int stateMask = 0; + StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, + ",;.:+-* "); //$NON-NLS-1$ + while (modifierTokenizer.hasMoreTokens()) { + int modifier = EditorUtility + .findLocalizedModifier(modifierTokenizer.nextToken()); + if (modifier == 0 || (stateMask & modifier) == modifier) + return -1; + stateMask = stateMask | modifier; + } + return stateMask; + } + + public void uninstall() { + + if (fColor != null) { + fColor.dispose(); + fColor = null; + } + + if (fCursor != null) { + fCursor.dispose(); + fCursor = null; + } + + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer != null) + sourceViewer.removeTextInputListener(this); + + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider != null) { + IDocument document = documentProvider + .getDocument(getEditorInput()); + if (document != null) + document.removeDocumentListener(this); + } + + IPreferenceStore preferenceStore = getPreferenceStore(); + if (preferenceStore != null) + preferenceStore.removePropertyChangeListener(this); + + if (sourceViewer == null) + return; + + StyledText text = sourceViewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + text.removeKeyListener(this); + text.removeMouseListener(this); + text.removeMouseMoveListener(this); + text.removeFocusListener(this); + text.removePaintListener(this); + + ((ITextViewerExtension4) sourceViewer) + .removeTextPresentationListener(this); + } + + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty().equals(PHPEditor.LINK_COLOR)) { + ISourceViewer viewer = getSourceViewer(); + if (viewer != null) + updateColor(viewer); + } else if (event.getProperty().equals( + BROWSER_LIKE_LINKS_KEY_MODIFIER)) { + updateKeyModifierMask(); + } + } + + private void updateColor(ISourceViewer viewer) { + if (fColor != null) + fColor.dispose(); + + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + Display display = text.getDisplay(); + fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, + display); + } + + /** + * Creates a color from the information stored in the given preference + * store. + * + * @param store + * the preference store + * @param key + * the key + * @param display + * the display + * @return the color or null if there is no such + * information available + */ + private Color createColor(IPreferenceStore store, String key, + Display display) { + + RGB rgb = null; + + if (store.contains(key)) { + + if (store.isDefault(key)) + rgb = PreferenceConverter.getDefaultColor(store, key); + else + rgb = PreferenceConverter.getColor(store, key); + + if (rgb != null) + return new Color(display, rgb); + } + + return null; + } + + private void repairRepresentation() { + repairRepresentation(false); + } + + private void repairRepresentation(boolean redrawAll) { + + if (fActiveRegion == null) + return; + + int offset = fActiveRegion.getOffset(); + int length = fActiveRegion.getLength(); + fActiveRegion = null; + + ISourceViewer viewer = getSourceViewer(); + if (viewer != null) { + + resetCursor(viewer); + + // Invalidate ==> remove applied text presentation + if (!redrawAll && viewer instanceof ITextViewerExtension2) + ((ITextViewerExtension2) viewer) + .invalidateTextPresentation(offset, length); + else + viewer.invalidateTextPresentation(); + + // Remove underline + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + offset = extension.modelOffset2WidgetOffset(offset); + } else { + offset -= viewer.getVisibleRegion().getOffset(); + } + try { + StyledText text = viewer.getTextWidget(); + + text.redrawRange(offset, length, false); + } catch (IllegalArgumentException x) { + // JavaPlugin.log(x); + } + } + } + + // will eventually be replaced by a method provided by jdt.core + private IRegion selectWord(IDocument document, int anchor) { + + try { + int offset = anchor; + char c; + + while (offset >= 0) { + c = document.getChar(offset); + if (!Scanner.isPHPIdentifierPart(c) && c != '$') + break; + --offset; + } + + int start = offset; + + offset = anchor; + int length = document.getLength(); + + while (offset < length) { + c = document.getChar(offset); + if (!Scanner.isPHPIdentifierPart(c) && c != '$') + break; + ++offset; + } + + int end = offset; + + if (start == end) + return new Region(start, 0); + else + return new Region(start + 1, end - start - 1); + + } catch (BadLocationException x) { + return null; + } + } + + IRegion getCurrentTextRegion(ISourceViewer viewer) { + + int offset = getCurrentTextOffset(viewer); + if (offset == -1) + return null; + + IJavaElement input = SelectionConverter.getInput(PHPEditor.this); + if (input == null) + return null; + + // try { + + // IJavaElement[] elements= null; + // synchronized (input) { + // elements= ((ICodeAssist) input).codeSelect(offset, 0); + // } + // + // if (elements == null || elements.length == 0) + // return null; + + return selectWord(viewer.getDocument(), offset); + + // } catch (JavaModelException e) { + // return null; + // } + } + + private int getCurrentTextOffset(ISourceViewer viewer) { + + try { + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) + return -1; + + Display display = text.getDisplay(); + Point absolutePosition = display.getCursorLocation(); + Point relativePosition = text.toControl(absolutePosition); + + int widgetOffset = text.getOffsetAtLocation(relativePosition); + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + return extension.widgetOffset2ModelOffset(widgetOffset); + } else { + return widgetOffset + viewer.getVisibleRegion().getOffset(); + } + + } catch (IllegalArgumentException e) { + return -1; + } + } + + public void applyTextPresentation(TextPresentation textPresentation) { + if (fActiveRegion == null) + return; + IRegion region = textPresentation.getExtent(); + if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region + .getOffset() + && region.getOffset() + region.getLength() > fActiveRegion + .getOffset()) + textPresentation.mergeStyleRange(new StyleRange(fActiveRegion + .getOffset(), fActiveRegion.getLength(), fColor, null)); + } + + private void highlightRegion(ISourceViewer viewer, IRegion region) { + + if (region.equals(fActiveRegion)) + return; + + repairRepresentation(); + + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + // Underline + int offset = 0; + int length = 0; + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + IRegion widgetRange = extension.modelRange2WidgetRange(region); + if (widgetRange == null) + return; + + offset = widgetRange.getOffset(); + length = widgetRange.getLength(); + + } else { + offset = region.getOffset() + - viewer.getVisibleRegion().getOffset(); + length = region.getLength(); + } + text.redrawRange(offset, length, false); + + // Invalidate region ==> apply text presentation + fActiveRegion = region; + if (viewer instanceof ITextViewerExtension2) + ((ITextViewerExtension2) viewer).invalidateTextPresentation( + region.getOffset(), region.getLength()); + else + viewer.invalidateTextPresentation(); + } + + private void activateCursor(ISourceViewer viewer) { + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + Display display = text.getDisplay(); + if (fCursor == null) + fCursor = new Cursor(display, SWT.CURSOR_HAND); + text.setCursor(fCursor); + } + + private void resetCursor(ISourceViewer viewer) { + StyledText text = viewer.getTextWidget(); + if (text != null && !text.isDisposed()) + text.setCursor(null); + + if (fCursor != null) { + fCursor.dispose(); + fCursor = null; + } + } + + /* + * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) + */ + public void keyPressed(KeyEvent event) { + + if (fActive) { + deactivate(); + return; + } + + if (event.keyCode != fKeyModifierMask) { + deactivate(); + return; + } + + fActive = true; + + // removed for #25871 + // + // ISourceViewer viewer= getSourceViewer(); + // if (viewer == null) + // return; + // + // IRegion region= getCurrentTextRegion(viewer); + // if (region == null) + // return; + // + // highlightRegion(viewer, region); + // activateCursor(viewer); + } + + /* + * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) + */ + public void keyReleased(KeyEvent event) { + + if (!fActive) + return; + + deactivate(); + } + + /* + * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) + */ + public void mouseDoubleClick(MouseEvent e) { + } + + /* + * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) + */ + public void mouseDown(MouseEvent event) { + + if (!fActive) + return; + + if (event.stateMask != fKeyModifierMask) { + deactivate(); + return; + } + + if (event.button != 1) { + deactivate(); + return; + } + } + + /* + * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) + */ + public void mouseUp(MouseEvent e) { + + if (!fActive) + return; + + if (e.button != 1) { + deactivate(); + return; + } + + boolean wasActive = fCursor != null; + + deactivate(); + + if (wasActive) { + IAction action = getAction("OpenEditor"); //$NON-NLS-1$ + if (action != null) + action.run(); + } + } + + /* + * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) + */ + public void mouseMove(MouseEvent event) { + + if (event.widget instanceof Control + && !((Control) event.widget).isFocusControl()) { + deactivate(); + return; + } + + if (!fActive) { + if (event.stateMask != fKeyModifierMask) + return; + // modifier was already pressed + fActive = true; + } + + ISourceViewer viewer = getSourceViewer(); + if (viewer == null) { + deactivate(); + return; + } + + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) { + deactivate(); + return; + } + + if ((event.stateMask & SWT.BUTTON1) != 0 + && text.getSelectionCount() != 0) { + deactivate(); + return; + } + + IRegion region = getCurrentTextRegion(viewer); + if (region == null || region.getLength() == 0) { + repairRepresentation(); + return; + } + + highlightRegion(viewer, region); + activateCursor(viewer); + } + + /* + * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) + */ + public void focusGained(FocusEvent e) { + } + + /* + * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) + */ + public void focusLost(FocusEvent event) { + deactivate(); + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + if (fActive && fActiveRegion != null) { + fRememberedPosition = new Position(fActiveRegion.getOffset(), + fActiveRegion.getLength()); + try { + event.getDocument().addPosition(fRememberedPosition); + } catch (BadLocationException x) { + fRememberedPosition = null; + } + } + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentChanged(DocumentEvent event) { + if (fRememberedPosition != null) { + if (!fRememberedPosition.isDeleted()) { + + event.getDocument().removePosition(fRememberedPosition); + fActiveRegion = new Region(fRememberedPosition.getOffset(), + fRememberedPosition.getLength()); + fRememberedPosition = null; + + ISourceViewer viewer = getSourceViewer(); + if (viewer != null) { + StyledText widget = viewer.getTextWidget(); + if (widget != null && !widget.isDisposed()) { + widget.getDisplay().asyncExec(new Runnable() { + public void run() { + deactivate(); + } + }); + } + } + + } else { + fActiveRegion = null; + fRememberedPosition = null; + deactivate(); + } + } + } + + /* + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) + */ + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { + if (oldInput == null) + return; + deactivate(); + oldInput.removeDocumentListener(this); + } + + /* + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) + */ + public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { + if (newInput == null) + return; + newInput.addDocumentListener(this); + } + + /* + * @see PaintListener#paintControl(PaintEvent) + */ + public void paintControl(PaintEvent event) { + if (fActiveRegion == null) + return; + + ISourceViewer viewer = getSourceViewer(); + if (viewer == null) + return; + + StyledText text = viewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + int offset = 0; + int length = 0; + + if (viewer instanceof ITextViewerExtension5) { + + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + IRegion widgetRange = extension + .modelRange2WidgetRange(fActiveRegion); + if (widgetRange == null) + return; + + offset = widgetRange.getOffset(); + length = widgetRange.getLength(); + + } else { + + IRegion region = viewer.getVisibleRegion(); + if (!includes(region, fActiveRegion)) + return; + + offset = fActiveRegion.getOffset() - region.getOffset(); + length = fActiveRegion.getLength(); + } + + // support for bidi + Point minLocation = getMinimumLocation(text, offset, length); + Point maxLocation = getMaximumLocation(text, offset, length); + + int x1 = minLocation.x; + int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; + int y = minLocation.y + text.getLineHeight() - 1; + + GC gc = event.gc; + if (fColor != null && !fColor.isDisposed()) + gc.setForeground(fColor); + gc.drawLine(x1, y, x2, y); + } + + private boolean includes(IRegion region, IRegion position) { + return position.getOffset() >= region.getOffset() + && position.getOffset() + position.getLength() <= region + .getOffset() + + region.getLength(); + } + + private Point getMinimumLocation(StyledText text, int offset, int length) { + Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); + + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); + + if (location.x < minLocation.x) + minLocation.x = location.x; + if (location.y < minLocation.y) + minLocation.y = location.y; + } + + return minLocation; + } + + private Point getMaximumLocation(StyledText text, int offset, int length) { + Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); + + for (int i = 0; i <= length; i++) { + Point location = text.getLocationAtOffset(offset + i); + + if (location.x > maxLocation.x) + maxLocation.x = location.x; + if (location.y > maxLocation.y) + maxLocation.y = location.y; + } + + return maxLocation; + } + } + + /** + * This action dispatches into two behaviours: If there is no current text + * hover, the javadoc is displayed using information presenter. If there is + * a current text hover, it is converted into a information presenter in + * order to make it sticky. + */ + class InformationDispatchAction extends TextEditorAction { + + /** The wrapped text operation action. */ + private final TextOperationAction fTextOperationAction; + + /** + * Creates a dispatch action. + */ + public InformationDispatchAction(ResourceBundle resourceBundle, + String prefix, final TextOperationAction textOperationAction) { + super(resourceBundle, prefix, PHPEditor.this); + if (textOperationAction == null) + throw new IllegalArgumentException(); + fTextOperationAction = textOperationAction; + } + + /* + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) { + fTextOperationAction.run(); + return; + } + + if (!(sourceViewer instanceof ITextViewerExtension2)) { + fTextOperationAction.run(); + return; + } + + ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer; + + // does a text hover exist? + ITextHover textHover = textViewerExtension2.getCurrentTextHover(); + if (textHover == null) { + fTextOperationAction.run(); + return; + } + + Point hoverEventLocation = textViewerExtension2 + .getHoverEventLocation(); + int offset = computeOffsetAtLocation(sourceViewer, + hoverEventLocation.x, hoverEventLocation.y); + if (offset == -1) { + fTextOperationAction.run(); + return; + } + + try { + // get the text hover content + IDocument document = sourceViewer.getDocument(); + String contentType = document.getContentType(offset); + + final IRegion hoverRegion = textHover.getHoverRegion( + sourceViewer, offset); + if (hoverRegion == null) + return; + + final String hoverInfo = textHover.getHoverInfo(sourceViewer, + hoverRegion); + + // with information provider + IInformationProvider informationProvider = new IInformationProvider() { + /* + * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, + * int) + */ + public IRegion getSubject(ITextViewer textViewer, int offset) { + return hoverRegion; + } + + /* + * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, + * org.eclipse.jface.text.IRegion) + */ + public String getInformation(ITextViewer textViewer, + IRegion subject) { + return hoverInfo; + } + }; + + fInformationPresenter.setOffset(offset); + fInformationPresenter.setInformationProvider( + informationProvider, contentType); + fInformationPresenter.showInformation(); + + } catch (BadLocationException e) { + } + } + + // modified version from TextViewer + private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { + + StyledText styledText = textViewer.getTextWidget(); + IDocument document = textViewer.getDocument(); + + if (document == null) + return -1; + + try { + int widgetLocation = styledText.getOffsetAtLocation(new Point( + x, y)); + if (textViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer; + return extension.widgetOffset2ModelOffset(widgetLocation); + } else { + IRegion visibleRegion = textViewer.getVisibleRegion(); + return widgetLocation + visibleRegion.getOffset(); + } + } catch (IllegalArgumentException e) { + return -1; + } + + } + }; + + /** + * This action implements smart home. + * + * Instead of going to the start of a line it does the following: - if smart + * home/end is enabled and the caret is after the line's first + * non-whitespace then the caret is moved directly before it, taking JavaDoc + * and multi-line comments into account. - if the caret is before the line's + * first non-whitespace the caret is moved to the beginning of the line - if + * the caret is at the beginning of the line see first case. + * + * @since 3.0 + */ + protected class SmartLineStartAction extends LineStartAction { + + /** + * Creates a new smart line start action + * + * @param textWidget + * the styled text widget + * @param doSelect + * a boolean flag which tells if the text up to the beginning + * of the line should be selected + */ + public SmartLineStartAction(final StyledText textWidget, + final boolean doSelect) { + super(textWidget, doSelect); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, + * int, java.lang.String) + */ + protected int getLineStartPosition(final IDocument document, + final String line, final int length, final int offset) { + + String type = IDocument.DEFAULT_CONTENT_TYPE; + try { + type = TextUtilities.getContentType(document, + IPHPPartitions.PHP_PARTITIONING, offset, true); + } catch (BadLocationException exception) { + // Should not happen + } + + int index = super.getLineStartPosition(document, line, length, + offset); + if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) + || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) { + if (index < length - 1 && line.charAt(index) == '*' + && line.charAt(index + 1) != '/') { + do { + ++index; + } while (index < length + && Character.isWhitespace(line.charAt(index))); + } + } else { + if (index < length - 1 && line.charAt(index) == '/' + && line.charAt(index + 1) == '/') { + index++; + do { + ++index; + } while (index < length + && Character.isWhitespace(line.charAt(index))); + } + } + return index; + } + } + + /** + * Text navigation action to navigate to the next sub-word. + * + * @since 3.0 + */ + protected abstract class NextSubWordAction extends TextNavigationAction { + + protected JavaWordIterator fIterator = new JavaWordIterator(); + + /** + * Creates a new next sub-word action. + * + * @param code + * Action code for the default operation. Must be an action + * code from + * @see org.eclipse.swt.custom.ST. + */ + protected NextSubWordAction(int code) { + super(getSourceViewer().getTextWidget(), code); + } + + /* + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + // Check whether we are in a java code partition and the preference + // is + // enabled + final IPreferenceStore store = getPreferenceStore(); + if (!store + .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { + super.run(); + return; + } + + final ISourceViewer viewer = getSourceViewer(); + final IDocument document = viewer.getDocument(); + fIterator + .setText((CharacterIterator) new DocumentCharacterIterator( + document)); + int position = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); + if (position == -1) + return; + + int next = findNextPosition(position); + if (next != BreakIterator.DONE) { + setCaretPosition(next); + getTextWidget().showSelection(); + fireSelectionChanged(); + } + + } + + /** + * Finds the next position after the given position. + * + * @param position + * the current position + * @return the next position + */ + protected int findNextPosition(int position) { + ISourceViewer viewer = getSourceViewer(); + int widget = -1; + while (position != BreakIterator.DONE && widget == -1) { // TODO: + // optimize + position = fIterator.following(position); + if (position != BreakIterator.DONE) + widget = modelOffset2WidgetOffset(viewer, position); + } + return position; + } + + /** + * Sets the caret position to the sub-word boundary given with + * position. + * + * @param position + * Position where the action should move the caret + */ + protected abstract void setCaretPosition(int position); + } + + /** + * Text navigation action to navigate to the next sub-word. + * + * @since 3.0 + */ + protected class NavigateNextSubWordAction extends NextSubWordAction { + + /** + * Creates a new navigate next sub-word action. + */ + public NavigateNextSubWordAction() { + super(ST.WORD_NEXT); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + getTextWidget().setCaretOffset( + modelOffset2WidgetOffset(getSourceViewer(), position)); + } + } + + /** + * Text operation action to delete the next sub-word. + * + * @since 3.0 + */ + protected class DeleteNextSubWordAction extends NextSubWordAction implements + IUpdate { + + /** + * Creates a new delete next sub-word action. + */ + public DeleteNextSubWordAction() { + super(ST.DELETE_WORD_NEXT); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + if (!validateEditorInputState()) + return; + + final ISourceViewer viewer = getSourceViewer(); + final int caret = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); + + try { + viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ + } catch (BadLocationException exception) { + // Should not happen + } + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int) + */ + protected int findNextPosition(int position) { + return fIterator.following(position); + } + + /* + * @see org.eclipse.ui.texteditor.IUpdate#update() + */ + public void update() { + setEnabled(isEditorInputModifiable()); + } + } + + /** + * Text operation action to select the next sub-word. + * + * @since 3.0 + */ + protected class SelectNextSubWordAction extends NextSubWordAction { + + /** + * Creates a new select next sub-word action. + */ + public SelectNextSubWordAction() { + super(ST.SELECT_WORD_NEXT); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + final ISourceViewer viewer = getSourceViewer(); + + final StyledText text = viewer.getTextWidget(); + if (text != null && !text.isDisposed()) { + + final Point selection = text.getSelection(); + final int caret = text.getCaretOffset(); + final int offset = modelOffset2WidgetOffset(viewer, position); + + if (caret == selection.x) + text.setSelectionRange(selection.y, offset - selection.y); + else + text.setSelectionRange(selection.x, offset - selection.x); + } + } + } + + /** + * Text navigation action to navigate to the previous sub-word. + * + * @since 3.0 + */ + protected abstract class PreviousSubWordAction extends TextNavigationAction { + + protected JavaWordIterator fIterator = new JavaWordIterator(); + + /** + * Creates a new previous sub-word action. + * + * @param code + * Action code for the default operation. Must be an action + * code from + * @see org.eclipse.swt.custom.ST. + */ + protected PreviousSubWordAction(final int code) { + super(getSourceViewer().getTextWidget(), code); + } + + /* + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + // Check whether we are in a java code partition and the preference + // is + // enabled + final IPreferenceStore store = getPreferenceStore(); + if (!store + .getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { + super.run(); + return; + } + + final ISourceViewer viewer = getSourceViewer(); + final IDocument document = viewer.getDocument(); + fIterator + .setText((CharacterIterator) new DocumentCharacterIterator( + document)); + int position = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); + if (position == -1) + return; + + int previous = findPreviousPosition(position); + if (previous != BreakIterator.DONE) { + setCaretPosition(previous); + getTextWidget().showSelection(); + fireSelectionChanged(); + } + + } + + /** + * Finds the previous position before the given position. + * + * @param position + * the current position + * @return the previous position + */ + protected int findPreviousPosition(int position) { + ISourceViewer viewer = getSourceViewer(); + int widget = -1; + while (position != BreakIterator.DONE && widget == -1) { // TODO: + // optimize + position = fIterator.preceding(position); + if (position != BreakIterator.DONE) + widget = modelOffset2WidgetOffset(viewer, position); + } + return position; + } + + /** + * Sets the caret position to the sub-word boundary given with + * position. + * + * @param position + * Position where the action should move the caret + */ + protected abstract void setCaretPosition(int position); + } + + /** + * Text navigation action to navigate to the previous sub-word. + * + * @since 3.0 + */ + protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { + + /** + * Creates a new navigate previous sub-word action. + */ + public NavigatePreviousSubWordAction() { + super(ST.WORD_PREVIOUS); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + getTextWidget().setCaretOffset( + modelOffset2WidgetOffset(getSourceViewer(), position)); + } + } + + /** + * Text operation action to delete the previous sub-word. + * + * @since 3.0 + */ + protected class DeletePreviousSubWordAction extends PreviousSubWordAction + implements IUpdate { + + /** + * Creates a new delete previous sub-word action. + */ + public DeletePreviousSubWordAction() { + super(ST.DELETE_WORD_PREVIOUS); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + if (!validateEditorInputState()) + return; + + final ISourceViewer viewer = getSourceViewer(); + final int caret = widgetOffset2ModelOffset(viewer, viewer + .getTextWidget().getCaretOffset()); + + try { + viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ + } catch (BadLocationException exception) { + // Should not happen + } + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int) + */ + protected int findPreviousPosition(int position) { + return fIterator.preceding(position); + } + + /* + * @see org.eclipse.ui.texteditor.IUpdate#update() + */ + public void update() { + setEnabled(isEditorInputModifiable()); + } + } + + /** + * Text operation action to select the previous sub-word. + * + * @since 3.0 + */ + protected class SelectPreviousSubWordAction extends PreviousSubWordAction { + + /** + * Creates a new select previous sub-word action. + */ + public SelectPreviousSubWordAction() { + super(ST.SELECT_WORD_PREVIOUS); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) + */ + protected void setCaretPosition(final int position) { + final ISourceViewer viewer = getSourceViewer(); + + final StyledText text = viewer.getTextWidget(); + if (text != null && !text.isDisposed()) { + + final Point selection = text.getSelection(); + final int caret = text.getCaretOffset(); + final int offset = modelOffset2WidgetOffset(viewer, position); + + if (caret == selection.x) + text.setSelectionRange(selection.y, offset - selection.y); + else + text.setSelectionRange(selection.x, offset - selection.x); + } + } + } + + // static protected class AnnotationAccess implements IAnnotationAccess { + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation) + // */ + // public Object getType(Annotation annotation) { + // if (annotation instanceof IJavaAnnotation) { + // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; + // // if (javaAnnotation.isRelevant()) + // // return javaAnnotation.getAnnotationType(); + // } + // return null; + // } + // + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation) + // */ + // public boolean isMultiLine(Annotation annotation) { + // return true; + // } + // + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation) + // */ + // public boolean isTemporary(Annotation annotation) { + // if (annotation instanceof IJavaAnnotation) { + // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; + // if (javaAnnotation.isRelevant()) + // return javaAnnotation.isTemporary(); + // } + // return false; + // } + // }; + + private class PropertyChangeListener implements + org.eclipse.core.runtime.Preferences.IPropertyChangeListener { + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + handlePreferencePropertyChanged(event); + } + }; + + /** + * Finds and marks occurrence annotations. + * + * @since 3.0 + */ + class OccurrencesFinderJob extends Job { + + private IDocument fDocument; + + private ISelection fSelection; + + private ISelectionValidator fPostSelectionValidator; + + private boolean fCanceled = false; + + private IProgressMonitor fProgressMonitor; + + private Position[] fPositions; + + public OccurrencesFinderJob(IDocument document, Position[] positions, + ISelection selection) { + super(PHPEditorMessages.JavaEditor_markOccurrences_job_name); + fDocument = document; + fSelection = selection; + fPositions = positions; + + if (getSelectionProvider() instanceof ISelectionValidator) + fPostSelectionValidator = (ISelectionValidator) getSelectionProvider(); + } + + // cannot use cancel() because it is declared final + void doCancel() { + fCanceled = true; + cancel(); + } + + private boolean isCanceled() { + return fCanceled + || fProgressMonitor.isCanceled() + || fPostSelectionValidator != null + && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection) + || LinkedModeModel.hasInstalledModel(fDocument); + } + + /* + * @see Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + public IStatus run(IProgressMonitor progressMonitor) { + + fProgressMonitor = progressMonitor; + + if (isCanceled()) + return Status.CANCEL_STATUS; + + ITextViewer textViewer = getViewer(); + if (textViewer == null) + return Status.CANCEL_STATUS; + + IDocument document = textViewer.getDocument(); + if (document == null) + return Status.CANCEL_STATUS; + + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider == null) + return Status.CANCEL_STATUS; + + IAnnotationModel annotationModel = documentProvider + .getAnnotationModel(getEditorInput()); + if (annotationModel == null) + return Status.CANCEL_STATUS; + + // Add occurrence annotations + int length = fPositions.length; + Map annotationMap = new HashMap(length); + for (int i = 0; i < length; i++) { + + if (isCanceled()) + return Status.CANCEL_STATUS; + + String message; + Position position = fPositions[i]; + + // Create & add annotation + try { + message = document.get(position.offset, position.length); + } catch (BadLocationException ex) { + // Skip this match + continue; + } + annotationMap + .put( + new Annotation( + "net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ + position); + } + + if (isCanceled()) + return Status.CANCEL_STATUS; + + synchronized (getLockObject(annotationModel)) { + if (annotationModel instanceof IAnnotationModelExtension) { + ((IAnnotationModelExtension) annotationModel) + .replaceAnnotations(fOccurrenceAnnotations, + annotationMap); + } else { + removeOccurrenceAnnotations(); + Iterator iter = annotationMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry mapEntry = (Map.Entry) iter.next(); + annotationModel.addAnnotation((Annotation) mapEntry + .getKey(), (Position) mapEntry.getValue()); + } + } + fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet() + .toArray(new Annotation[annotationMap.keySet().size()]); + } + + return Status.OK_STATUS; + } + } + + /** + * Cancels the occurrences finder job upon document changes. + * + * @since 3.0 + */ + class OccurrencesFinderJobCanceler implements IDocumentListener, + ITextInputListener { + + public void install() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) + return; + + StyledText text = sourceViewer.getTextWidget(); + if (text == null || text.isDisposed()) + return; + + sourceViewer.addTextInputListener(this); + + IDocument document = sourceViewer.getDocument(); + if (document != null) + document.addDocumentListener(this); + } + + public void uninstall() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer != null) + sourceViewer.removeTextInputListener(this); + + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider != null) { + IDocument document = documentProvider + .getDocument(getEditorInput()); + if (document != null) + document.removeDocumentListener(this); + } + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + if (fOccurrencesFinderJob != null) + fOccurrencesFinderJob.doCancel(); + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentChanged(DocumentEvent event) { + } + + /* + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) + */ + public void inputDocumentAboutToBeChanged(IDocument oldInput, + IDocument newInput) { + if (oldInput == null) + return; + + oldInput.removeDocumentListener(this); + } + + /* + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) + */ + public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { + if (newInput == null) + return; + newInput.addDocumentListener(this); + } + } + + /** + * Internal activation listener. + * + * @since 3.0 + */ + private class ActivationListener implements IWindowListener { + + /* + * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow) + * @since 3.1 + */ + public void windowActivated(IWorkbenchWindow window) { + if (window == getEditorSite().getWorkbenchWindow() + && fMarkOccurrenceAnnotations && isActivePart()) { + fForcedMarkOccurrencesSelection = getSelectionProvider() + .getSelection(); + SelectionListenerWithASTManager + .getDefault() + .forceSelectionChange( + PHPEditor.this, + (ITextSelection) fForcedMarkOccurrencesSelection); + } + } + + /* + * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow) + * @since 3.1 + */ + public void windowDeactivated(IWorkbenchWindow window) { + if (window == getEditorSite().getWorkbenchWindow() + && fMarkOccurrenceAnnotations && isActivePart()) + removeOccurrenceAnnotations(); + } + + /* + * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow) + * @since 3.1 + */ + public void windowClosed(IWorkbenchWindow window) { + } + + /* + * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow) + * @since 3.1 + */ + public void windowOpened(IWorkbenchWindow window) { + } + } + + /** + * Updates the selection in the editor's widget with the selection of the + * outline page. + */ + class OutlineSelectionChangedListener extends + AbstractSelectionChangedListener { + public void selectionChanged(SelectionChangedEvent event) { + doSelectionChanged(event); + } + } + + /** + * The internal shell activation listener for updating occurrences. + * + * @since 3.0 + */ + private ActivationListener fActivationListener = new ActivationListener(); + + private ISelectionListenerWithAST fPostSelectionListenerWithAST; + + private OccurrencesFinderJob fOccurrencesFinderJob; + + /** The occurrences finder job canceler */ + private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler; + + /** + * Holds the current occurrence annotations. + * + * @since 3.0 + */ + private Annotation[] fOccurrenceAnnotations = null; + + /** + * Tells whether all occurrences of the element at the current caret + * location are automatically marked in this editor. + * + * @since 3.0 + */ + private boolean fMarkOccurrenceAnnotations; + + /** + * The selection used when forcing occurrence marking through code. + * + * @since 3.0 + */ + private ISelection fForcedMarkOccurrencesSelection; + + /** + * The document modification stamp at the time when the last occurrence + * marking took place. + * + * @since 3.1 + */ + private long fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; + + /** + * The region of the word under the caret used to when computing the current + * occurrence markings. + * + * @since 3.1 + */ + private IRegion fMarkOccurrenceTargetRegion; + + /** + * Tells whether the occurrence annotations are sticky i.e. whether they + * stay even if there's no valid Java element at the current caret position. + * Only valid if {@link #fMarkOccurrenceAnnotations} is true. + * + * @since 3.0 + */ + private boolean fStickyOccurrenceAnnotations; + + /** Preference key for the link color */ + private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR; + + /** Preference key for compiler task tags */ + private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; + + // protected PHPActionGroup fActionGroups; + // /** The outline page */ + // private AbstractContentOutlinePage fOutlinePage; + /** The outline page */ + protected JavaOutlinePage fOutlinePage; + + /** Outliner context menu Id */ + protected String fOutlinerContextMenuId; + + /** + * Indicates whether this editor should react on outline page selection + * changes + */ + private int fIgnoreOutlinePageSelection; + + /** The outline page selection updater */ + // private OutlinePageSelectionUpdater fUpdater; + // protected PHPSyntaxParserThread fValidationThread = null; + // private IPreferenceStore fPHPPrefStore; + /** The selection changed listener */ + // protected ISelectionChangedListener fSelectionChangedListener = new + // SelectionChangedListener(); + /** + * The editor selection changed listener. + * + * @since 3.0 + */ + private EditorSelectionChangedListener fEditorSelectionChangedListener; + + /** The selection changed listener */ + protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener(); + + /** The editor's bracket matcher */ + private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS); + + /** The line number ruler column */ + // private LineNumberRulerColumn fLineNumberRulerColumn; + /** This editor's encoding support */ + private DefaultEncodingSupport fEncodingSupport; + + /** The mouse listener */ + private MouseClickListener fMouseListener; + + /** + * Indicates whether this editor is about to update any annotation views. + * + * @since 3.0 + */ + private boolean fIsUpdatingAnnotationViews = false; + + /** + * The marker that served as last target for a goto marker request. + * + * @since 3.0 + */ + private IMarker fLastMarkerTarget = null; + + protected CompositeActionGroup fActionGroups; + + protected CompositeActionGroup fContextMenuGroup; + + /** + * This editor's projection support + * + * @since 3.0 + */ + private ProjectionSupport fProjectionSupport; + + /** + * This editor's projection model updater + * + * @since 3.0 + */ + private IJavaFoldingStructureProvider fProjectionModelUpdater; + + /** + * The override and implements indicator manager for this editor. + * + * @since 3.0 + */ + // protected OverrideIndicatorManager fOverrideIndicatorManager; + /** + * The action group for folding. + * + * @since 3.0 + */ + private FoldingActionGroup fFoldingGroup; + + /** The information presenter. */ + private InformationPresenter fInformationPresenter; + + /** The annotation access */ + // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess(); + /** The overview ruler */ + protected OverviewRuler isOverviewRulerVisible; + + /** The source viewer decoration support */ + // protected SourceViewerDecorationSupport fSourceViewerDecorationSupport; + /** The overview ruler */ + // protected OverviewRuler fOverviewRuler; + /** The preference property change listener for java core. */ + private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener(); + + /** + * Returns the most narrow java element including the given offset + * + * @param offset + * the offset inside of the requested element + */ + abstract protected IJavaElement getElementAt(int offset); + + /** + * Returns the java element of this editor's input corresponding to the + * given IJavaElement + */ + abstract protected IJavaElement getCorrespondingElement(IJavaElement element); + + /** + * Sets the input of the editor's outline page. + */ + abstract protected void setOutlinePageInput(JavaOutlinePage page, + IEditorInput input); + + /** + * Default constructor. + */ + public PHPEditor() { + super(); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes() + */ + protected void initializeKeyBindingScopes() { + setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor() + */ + protected void initializeEditor() { + // jsurfer old code + // JavaTextTools textTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // setSourceViewerConfiguration(new + // PHPSourceViewerConfiguration(textTools, + // this, IPHPPartitions.PHP_PARTITIONING)); //, + // IJavaPartitions.JAVA_PARTITIONING)); + IPreferenceStore store = createCombinedPreferenceStore(null); + setPreferenceStore(store); + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools + .getColorManager(), store, this, + IPHPPartitions.PHP_PARTITIONING)); + + // TODO changed in 3.x ? + // setRangeIndicator(new DefaultRangeIndicator()); + // if + // (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) + // fUpdater = new OutlinePageSelectionUpdater(); + // jsurfer end + + // IPreferenceStore store= createCombinedPreferenceStore(null); + // setPreferenceStore(store); + // JavaTextTools textTools= + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // setSourceViewerConfiguration(new + // JavaSourceViewerConfiguration(textTools.getColorManager(), store, + // this, IJavaPartitions.JAVA_PARTITIONING)); + fMarkOccurrenceAnnotations = store + .getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); + fStickyOccurrenceAnnotations = store + .getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); + // fMarkTypeOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES); + // fMarkMethodOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES); + // fMarkConstantOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES); + // fMarkFieldOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES); + // fMarkLocalVariableypeOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES); + // fMarkExceptions= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES); + // fMarkImplementors= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_IMPLEMENTORS); + // fMarkMethodExitPoints= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS); + + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() + */ + protected void updatePropertyDependentActions() { + super.updatePropertyDependentActions(); + if (fEncodingSupport != null) + fEncodingSupport.reset(); + } + + /* + * Update the hovering behavior depending on the preferences. + */ + private void updateHoverBehavior() { + SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + String[] types = configuration + .getConfiguredContentTypes(getSourceViewer()); + + for (int i = 0; i < types.length; i++) { + + String t = types[i]; + + int[] stateMasks = configuration.getConfiguredTextHoverStateMasks( + getSourceViewer(), t); + + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer instanceof ITextViewerExtension2) { + if (stateMasks != null) { + for (int j = 0; j < stateMasks.length; j++) { + int stateMask = stateMasks[j]; + ITextHover textHover = configuration.getTextHover( + sourceViewer, t, stateMask); + ((ITextViewerExtension2) sourceViewer).setTextHover( + textHover, t, stateMask); + } + } else { + ITextHover textHover = configuration.getTextHover( + sourceViewer, t); + ((ITextViewerExtension2) sourceViewer).setTextHover( + textHover, t, + ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); + } + } else + sourceViewer.setTextHover(configuration.getTextHover( + sourceViewer, t), t); + } + } + + public void updatedTitleImage(Image image) { + setTitleImage(image); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() + */ + public Object getViewPartInput() { + return getEditorInput().getAdapter(IResource.class); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) + */ + protected void doSetSelection(ISelection selection) { + super.doSetSelection(selection); + synchronizeOutlinePageSelection(); + } + + boolean isFoldingEnabled() { + return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_FOLDING_ENABLED); + } + + /* + * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. + * widgets.Composite) + */ + public void createPartControl(Composite parent) { + super.createPartControl(parent); + + // fSourceViewerDecorationSupport.install(getPreferenceStore()); + + ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); + + fProjectionSupport = new ProjectionSupport(projectionViewer, + getAnnotationAccess(), getSharedColors()); + fProjectionSupport + .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ + fProjectionSupport + .addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ + fProjectionSupport + .setHoverControlCreator(new IInformationControlCreator() { + public IInformationControl createInformationControl( + Shell shell) { + return new CustomSourceInformationControl(shell, + IDocument.DEFAULT_CONTENT_TYPE); + } + }); + fProjectionSupport.install(); + + fProjectionModelUpdater = PHPeclipsePlugin.getDefault() + .getFoldingStructureProviderRegistry() + .getCurrentFoldingProvider(); + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.install(this, projectionViewer); + + if (isFoldingEnabled()) + projectionViewer.doOperation(ProjectionViewer.TOGGLE); + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + preferences.addPropertyChangeListener(fPropertyChangeListener); + IInformationControlCreator informationControlCreator = new IInformationControlCreator() { + public IInformationControl createInformationControl(Shell parent) { + boolean cutDown = false; + int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); + return new DefaultInformationControl(parent, SWT.RESIZE, style, + new HTMLTextPresenter(cutDown)); + } + }; + + fInformationPresenter = new InformationPresenter( + informationControlCreator); + fInformationPresenter.setSizeConstraints(60, 10, true, true); + fInformationPresenter.install(getSourceViewer()); + + fEditorSelectionChangedListener = new EditorSelectionChangedListener(); + fEditorSelectionChangedListener.install(getSelectionProvider()); + + if (isBrowserLikeLinks()) + enableBrowserLikeLinks(); + + if (PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) + enableOverwriteMode(false); + + if (fMarkOccurrenceAnnotations) + installOccurrencesFinder(); + + PlatformUI.getWorkbench().addWindowListener(fActivationListener); + + /* + * start of EDITOR_SAVE_ON_BLUR + * ed_mann + */ + final PHPEditor editor = this; + FocusListener focusListener = new FocusListener() { + + public void focusGained(FocusEvent e) { + return; + } + + public void focusLost(FocusEvent e) { + //viewer.get + if(editor.isDirty() && PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean(PreferenceConstants.EDITOR_SAVE_ON_BLUR)){ + editor.doSave(null); + } + } + }; + projectionViewer.getTextWidget().addFocusListener(focusListener); + /* + * end of EDITOR_SAVE_ON_BLUR + * ed_mann + */ + + setWordWrap(); + } + + private void setWordWrap() { + if (getSourceViewer() != null) { + getSourceViewer().getTextWidget().setWordWrap( + PHPeclipsePlugin.getDefault().getPreferenceStore() + .getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS)); + } + } + + protected void configureSourceViewerDecorationSupport( + SourceViewerDecorationSupport support) { + + support.setCharacterPairMatcher(fBracketMatcher); + support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, + MATCHING_BRACKETS_COLOR); + + super.configureSourceViewerDecorationSupport(support); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker) + */ + public void gotoMarker(IMarker marker) { + fLastMarkerTarget = marker; + if (!fIsUpdatingAnnotationViews) { + super.gotoMarker(marker); + } + } + + /** + * Jumps to the next enabled annotation according to the given direction. An + * annotation type is enabled if it is configured to be in the Next/Previous + * tool bar drop down menu and if it is checked. + * + * @param forward + * true if search direction is forward, + * false if backward + */ + public Annotation gotoAnnotation(boolean forward) { + ITextSelection selection = (ITextSelection) getSelectionProvider() + .getSelection(); + Position position = new Position(0, 0); + Annotation annotation = null; + if (false /* delayed - see bug 18316 */) { + annotation = getNextAnnotation(selection.getOffset(), selection + .getLength(), forward, position); + selectAndReveal(position.getOffset(), position.getLength()); + } else /* no delay - see bug 18316 */{ + annotation = getNextAnnotation(selection.getOffset(), selection + .getLength(), forward, position); + setStatusLineErrorMessage(null); + setStatusLineMessage(null); + if (annotation != null) { + updateAnnotationViews(annotation); + selectAndReveal(position.getOffset(), position.getLength()); + setStatusLineMessage(annotation.getText()); + } + } + return annotation; + } + + /** + * Returns the lock object for the given annotation model. + * + * @param annotationModel + * the annotation model + * @return the annotation model's lock object + * @since 3.0 + */ + private Object getLockObject(IAnnotationModel annotationModel) { + if (annotationModel instanceof ISynchronizable) + return ((ISynchronizable) annotationModel).getLockObject(); + else + return annotationModel; + } + + /** + * Updates the annotation views that show the given annotation. + * + * @param annotation + * the annotation + */ + private void updateAnnotationViews(Annotation annotation) { + IMarker marker = null; + if (annotation instanceof MarkerAnnotation) + marker = ((MarkerAnnotation) annotation).getMarker(); + else if (annotation instanceof IJavaAnnotation) { + Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator(); + if (e != null) { + while (e.hasNext()) { + Object o = e.next(); + if (o instanceof MarkerAnnotation) { + marker = ((MarkerAnnotation) o).getMarker(); + break; + } + } + } + } + + if (marker != null && !marker.equals(fLastMarkerTarget)) { + try { + boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM); + IWorkbenchPage page = getSite().getPage(); + IViewPart view = page + .findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW + : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ + if (view != null) { + Method method = view + .getClass() + .getMethod( + "setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$ + method.invoke(view, new Object[] { + new StructuredSelection(marker), Boolean.TRUE }); + } + } catch (CoreException x) { + } catch (NoSuchMethodException x) { + } catch (IllegalAccessException x) { + } catch (InvocationTargetException x) { + } + // ignore exceptions, don't update any of the lists, just set status + // line + } + } + + /** + * Returns this document's complete text. + * + * @return the document's complete text + */ + public String get() { + IDocument doc = this.getDocumentProvider().getDocument( + this.getEditorInput()); + return doc.get(); + } + + /** + * Sets the outliner's context menu ID. + */ + protected void setOutlinerContextMenuId(String menuId) { + fOutlinerContextMenuId = menuId; + } + + /** + * Returns the standard action group of this editor. + */ + protected ActionGroup getActionGroup() { + return fActionGroups; + } + + // public JavaOutlinePage getfOutlinePage() { + // return fOutlinePage; + // } + + /** + * The PHPEditor implementation of this + * AbstractTextEditor method extend the actions to add those + * specific to the receiver + */ + protected void createActions() { + super.createActions(); + + ActionGroup oeg/*, ovg, jsg, sg*/; + fActionGroups = new CompositeActionGroup( + new ActionGroup[] { oeg = new OpenEditorActionGroup(this), + // sg= new ShowActionGroup(this), + // ovg= new OpenViewActionGroup(this), + // jsg= new JavaSearchActionGroup(this) + }); + fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg }); + // , ovg, sg, jsg}); + + fFoldingGroup = new FoldingActionGroup(this, getViewer()); + + // ResourceAction resAction = new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ + // resAction = new + // InformationDispatchAction(PHPEditorMessages.getResourceBundle(), + // "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ + // resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); + // setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ + + // WorkbenchHelp.setHelp(resAction, + // IJavaHelpContextIds.SHOW_JAVADOC_ACTION); + + Action action = new GotoMatchingBracketAction(this); + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); + setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); + + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.", + // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action); + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.SHOW_OUTLINE_ACTION); + // + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.", + // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE, + // action); + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); + // + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.", + // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY, + // action); + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); + + fEncodingSupport = new DefaultEncodingSupport(); + fEncodingSupport.initialize(this); + + // fSelectionHistory= new SelectionHistory(this); + // + // action= new StructureSelectEnclosingAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); + // setAction(StructureSelectionAction.ENCLOSING, action); + // + // action= new StructureSelectNextAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); + // setAction(StructureSelectionAction.NEXT, action); + // + // action= new StructureSelectPreviousAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); + // setAction(StructureSelectionAction.PREVIOUS, action); + // + // StructureSelectHistoryAction historyAction= new + // StructureSelectHistoryAction(this, fSelectionHistory); + // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); + // setAction(StructureSelectionAction.HISTORY, historyAction); + // fSelectionHistory.setHistoryAction(historyAction); + // + // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); + // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); + // + // action= + // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); + // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); + // + // action= new QuickFormatAction(); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT); + // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); + // + // action= new RemoveOccurrenceAnnotations(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); + // setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$ + + // add annotation actions + action = new JavaSelectMarkerRulerAction2(PHPEditorMessages + .getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ + setAction("AnnotationAction", action); //$NON-NLS-1$ + } + + private void internalDoSetInput(IEditorInput input) throws CoreException { + super.doSetInput(input); + + if (getSourceViewer() instanceof JavaSourceViewer) { + JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer(); + if (viewer.getReconciler() == null) { + IReconciler reconciler = getSourceViewerConfiguration() + .getReconciler(viewer); + if (reconciler != null) { + reconciler.install(viewer); + viewer.setReconciler(reconciler); + } + } + } + + if (fEncodingSupport != null) + fEncodingSupport.reset(); + + setOutlinePageInput(fOutlinePage, input); + + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.initialize(); + + // if (isShowingOverrideIndicators()) + // installOverrideIndicator(false); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) + * @since 3.0 + */ + protected void setPreferenceStore(IPreferenceStore store) { + super.setPreferenceStore(store); + if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) { + JavaTextTools textTools = PHPeclipsePlugin.getDefault() + .getJavaTextTools(); + setSourceViewerConfiguration(new PHPSourceViewerConfiguration( + textTools.getColorManager(), store, this, + IPHPPartitions.PHP_PARTITIONING)); + } + if (getSourceViewer() instanceof JavaSourceViewer) + ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store); + } + + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs any extra disposal + * actions required by the php editor. + */ + public void dispose() { + if (fProjectionModelUpdater != null) { + fProjectionModelUpdater.uninstall(); + fProjectionModelUpdater = null; + } + + if (fProjectionSupport != null) { + fProjectionSupport.dispose(); + fProjectionSupport = null; + } + // PHPEditorEnvironment.disconnect(this); + if (fOutlinePage != null) + fOutlinePage.setInput(null); + + if (fActionGroups != null) + fActionGroups.dispose(); + + if (isBrowserLikeLinks()) + disableBrowserLikeLinks(); + + // cancel possible running computation + fMarkOccurrenceAnnotations = false; + uninstallOccurrencesFinder(); + + uninstallOverrideIndicator(); + + if (fActivationListener != null) { + PlatformUI.getWorkbench().removeWindowListener(fActivationListener); + fActivationListener = null; + } + + if (fEncodingSupport != null) { + fEncodingSupport.dispose(); + fEncodingSupport = null; + } + + if (fPropertyChangeListener != null) { + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + preferences.removePropertyChangeListener(fPropertyChangeListener); + fPropertyChangeListener = null; + } + + // if (fSourceViewerDecorationSupport != null) { + // fSourceViewerDecorationSupport.dispose(); + // fSourceViewerDecorationSupport = null; + // } + + if (fBracketMatcher != null) { + fBracketMatcher.dispose(); + fBracketMatcher = null; + } + + if (fEditorSelectionChangedListener != null) { + fEditorSelectionChangedListener.uninstall(getSelectionProvider()); + fEditorSelectionChangedListener = null; + } + + super.dispose(); + } + + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs any extra revert + * behavior required by the php editor. + */ + // public void doRevertToSaved() { + // super.doRevertToSaved(); + // if (fOutlinePage != null) + // fOutlinePage.update(); + // } + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs any extra save behavior + * required by the php editor. + */ + // public void doSave(IProgressMonitor monitor) { + // super.doSave(monitor); + // compile or not, according to the user preferences + // IPreferenceStore store = getPreferenceStore(); + // the parse on save was changed to the eclipse "builders" concept + // if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) { + // IAction a = PHPParserAction.getInstance(); + // if (a != null) + // a.run(); + // } + // if (SWT.getPlatform().equals("win32")) { + // IAction a = ShowExternalPreviewAction.getInstance(); + // if (a != null) + // a.run(); + // } + // if (fOutlinePage != null) + // fOutlinePage.update(); + // } + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs any extra save as + * behavior required by the php editor. + */ + // public void doSaveAs() { + // super.doSaveAs(); + // if (fOutlinePage != null) + // fOutlinePage.update(); + // } + /* + * @see StatusTextEditor#getStatusHeader(IStatus) + */ + protected String getStatusHeader(IStatus status) { + if (fEncodingSupport != null) { + String message = fEncodingSupport.getStatusHeader(status); + if (message != null) + return message; + } + return super.getStatusHeader(status); + } + + /* + * @see StatusTextEditor#getStatusBanner(IStatus) + */ + protected String getStatusBanner(IStatus status) { + if (fEncodingSupport != null) { + String message = fEncodingSupport.getStatusBanner(status); + if (message != null) + return message; + } + return super.getStatusBanner(status); + } + + /* + * @see StatusTextEditor#getStatusMessage(IStatus) + */ + protected String getStatusMessage(IStatus status) { + if (fEncodingSupport != null) { + String message = fEncodingSupport.getStatusMessage(status); + if (message != null) + return message; + } + return super.getStatusMessage(status); + } + + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs sets the input of the + * outline page after AbstractTextEditor has set input. + */ + // protected void doSetInput(IEditorInput input) throws CoreException { + // super.doSetInput(input); + // if (fEncodingSupport != null) + // fEncodingSupport.reset(); + // setOutlinePageInput(fOutlinePage, input); + // } + /* + * @see AbstractTextEditor#doSetInput + */ + protected void doSetInput(IEditorInput input) throws CoreException { + ISourceViewer sourceViewer = getSourceViewer(); + if (!(sourceViewer instanceof ISourceViewerExtension2)) { + setPreferenceStore(createCombinedPreferenceStore(input)); + internalDoSetInput(input); + return; + } + + // uninstall & unregister preference store listener + if (isBrowserLikeLinks()) + disableBrowserLikeLinks(); + getSourceViewerDecorationSupport(sourceViewer).uninstall(); + ((ISourceViewerExtension2) sourceViewer).unconfigure(); + + setPreferenceStore(createCombinedPreferenceStore(input)); + + // install & register preference store listener + sourceViewer.configure(getSourceViewerConfiguration()); + getSourceViewerDecorationSupport(sourceViewer).install( + getPreferenceStore()); + if (isBrowserLikeLinks()) + enableBrowserLikeLinks(); + + internalDoSetInput(input); + } + + /* + * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() + */ + // public Object getViewPartInput() { + // return getEditorInput().getAdapter(IFile.class); + // } + /** + * The PHPEditor implementation of this + * AbstractTextEditor method adds any PHPEditor specific + * entries. + */ + public void editorContextMenuAboutToShow(MenuManager menu) { + super.editorContextMenuAboutToShow(menu); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, + new Separator(IContextMenuConstants.GROUP_OPEN)); + menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker( + IContextMenuConstants.GROUP_SHOW)); + + ActionContext context = new ActionContext(getSelectionProvider() + .getSelection()); + fContextMenuGroup.setContext(context); + fContextMenuGroup.fillContextMenu(menu); + fContextMenuGroup.setContext(null); + // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); + // //$NON-NLS-1$ + // + // ActionContext context = + // new ActionContext(getSelectionProvider().getSelection()); + // fContextMenuGroup.setContext(context); + // fContextMenuGroup.fillContextMenu(menu); + // fContextMenuGroup.setContext(null); + } + + /** + * Creates the outline page used with this editor. + */ + protected JavaOutlinePage createOutlinePage() { + JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this); + fOutlineSelectionChangedListener.install(page); + setOutlinePageInput(page, getEditorInput()); + return page; + } + + /** + * Informs the editor that its outliner has been closed. + */ + public void outlinePageClosed() { + if (fOutlinePage != null) { + fOutlineSelectionChangedListener.uninstall(fOutlinePage); + fOutlinePage = null; + resetHighlightRange(); + } + } + + /** + * Synchronizes the outliner selection with the given element position in + * the editor. + * + * @param element + * the java element to select + */ + protected void synchronizeOutlinePage(ISourceReference element) { + synchronizeOutlinePage(element, true); + } + + /** + * Synchronizes the outliner selection with the given element position in + * the editor. + * + * @param element + * the java element to select + * @param checkIfOutlinePageActive + * true if check for active outline page needs to + * be done + */ + protected void synchronizeOutlinePage(ISourceReference element, + boolean checkIfOutlinePageActive) { + if (fOutlinePage != null && element != null + && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { + fOutlineSelectionChangedListener.uninstall(fOutlinePage); + fOutlinePage.select(element); + fOutlineSelectionChangedListener.install(fOutlinePage); + } + } + + /** + * Synchronizes the outliner selection with the actual cursor position in + * the editor. + */ + public void synchronizeOutlinePageSelection() { + synchronizeOutlinePage(computeHighlightRangeSourceReference()); + + // ISourceViewer sourceViewer = getSourceViewer(); + // if (sourceViewer == null || fOutlinePage == null) + // return; + // + // StyledText styledText = sourceViewer.getTextWidget(); + // if (styledText == null) + // return; + // + // int caret = 0; + // if (sourceViewer instanceof ITextViewerExtension3) { + // ITextViewerExtension3 extension = (ITextViewerExtension3) + // sourceViewer; + // caret = + // extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); + // } else { + // int offset = sourceViewer.getVisibleRegion().getOffset(); + // caret = offset + styledText.getCaretOffset(); + // } + // + // IJavaElement element = getElementAt(caret); + // if (element instanceof ISourceReference) { + // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); + // fOutlinePage.select((ISourceReference) element); + // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); + // } + } + + protected void setSelection(ISourceReference reference, boolean moveCursor) { + + ISelection selection = getSelectionProvider().getSelection(); + if (selection instanceof TextSelection) { + TextSelection textSelection = (TextSelection) selection; + if (textSelection.getOffset() != 0 + || textSelection.getLength() != 0) + markInNavigationHistory(); + } + + if (reference != null) { + + StyledText textWidget = null; + + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer != null) + textWidget = sourceViewer.getTextWidget(); + + if (textWidget == null) + return; + + try { + + ISourceRange range = reference.getSourceRange(); + if (range == null) + return; + + int offset = range.getOffset(); + int length = range.getLength(); + + if (offset < 0 || length < 0) + return; + + textWidget.setRedraw(false); + + setHighlightRange(offset, length, moveCursor); + + if (!moveCursor) + return; + + offset = -1; + length = -1; + + if (reference instanceof IMember) { + range = ((IMember) reference).getNameRange(); + if (range != null) { + offset = range.getOffset(); + length = range.getLength(); + } + } + // else if (reference instanceof IImportDeclaration) { + // String name= ((IImportDeclaration) + // reference).getElementName(); + // if (name != null && name.length() > 0) { + // String content= reference.getSource(); + // if (content != null) { + // offset= range.getOffset() + content.indexOf(name); + // length= name.length(); + // } + // } + // } else if (reference instanceof IPackageDeclaration) { + // String name= ((IPackageDeclaration) + // reference).getElementName(); + // if (name != null && name.length() > 0) { + // String content= reference.getSource(); + // if (content != null) { + // offset= range.getOffset() + content.indexOf(name); + // length= name.length(); + // } + // } + // } + + if (offset > -1 && length > 0) { + sourceViewer.revealRange(offset, length); + sourceViewer.setSelectedRange(offset, length); + } + + } catch (JavaModelException x) { + } catch (IllegalArgumentException x) { + } finally { + if (textWidget != null) + textWidget.setRedraw(true); + } + + } else if (moveCursor) { + resetHighlightRange(); + } + + markInNavigationHistory(); + } + + public void setSelection(IJavaElement element) { + if (element == null || element instanceof ICompilationUnit) { // || + // element + // instanceof + // IClassFile) + // { + /* + * If the element is an ICompilationUnit this unit is either the + * input of this editor or not being displayed. In both cases, + * nothing should happened. + * (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) + */ + return; + } + + IJavaElement corresponding = getCorrespondingElement(element); + if (corresponding instanceof ISourceReference) { + ISourceReference reference = (ISourceReference) corresponding; + // set highlight range + setSelection(reference, true); + // set outliner selection + if (fOutlinePage != null) { + fOutlineSelectionChangedListener.uninstall(fOutlinePage); + fOutlinePage.select(reference); + fOutlineSelectionChangedListener.install(fOutlinePage); + } + } + } + + public synchronized void editingScriptStarted() { + ++fIgnoreOutlinePageSelection; + } + + public synchronized void editingScriptEnded() { + --fIgnoreOutlinePageSelection; + } + + public synchronized boolean isEditingScriptRunning() { + return (fIgnoreOutlinePageSelection > 0); + } + + /** + * The PHPEditor implementation of this + * AbstractTextEditor method performs gets the java content + * outline page if request is for a an outline page. + */ + public Object getAdapter(Class required) { + + if (IContentOutlinePage.class.equals(required)) { + if (fOutlinePage == null) + fOutlinePage = createOutlinePage(); + return fOutlinePage; + } + + if (IEncodingSupport.class.equals(required)) + return fEncodingSupport; + + if (required == IShowInTargetList.class) { + return new IShowInTargetList() { + public String[] getShowInTargetIds() { + return new String[] { JavaUI.ID_PACKAGES, + IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; + } + + }; + } + if (fProjectionSupport != null) { + Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), + required); + if (adapter != null) + return adapter; + } + + return super.getAdapter(required); + } + + // public Object getAdapter(Class required) { + // if (IContentOutlinePage.class.equals(required)) { + // if (fOutlinePage == null) { + // fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this); + // if (getEditorInput() != null) + // fOutlinePage.setInput(getEditorInput()); + // } + // return fOutlinePage; + // } + // + // if (IEncodingSupport.class.equals(required)) + // return fEncodingSupport; + // + // return super.getAdapter(required); + // } + + protected void doSelectionChanged(SelectionChangedEvent event) { + ISourceReference reference = null; + + ISelection selection = event.getSelection(); + Iterator iter = ((IStructuredSelection) selection).iterator(); + while (iter.hasNext()) { + Object o = iter.next(); + if (o instanceof ISourceReference) { + reference = (ISourceReference) o; + break; + } + } + + if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null) + PHPeclipsePlugin.getActivePage().bringToTop(this); + + try { + editingScriptStarted(); + setSelection(reference, !isActivePart()); + } finally { + editingScriptEnded(); + } + } + + /* + * @see AbstractTextEditor#adjustHighlightRange(int, int) + */ + protected void adjustHighlightRange(int offset, int length) { + + try { + + IJavaElement element = getElementAt(offset); + while (element instanceof ISourceReference) { + ISourceRange range = ((ISourceReference) element) + .getSourceRange(); + if (offset < range.getOffset() + range.getLength() + && range.getOffset() < offset + length) { + + ISourceViewer viewer = getSourceViewer(); + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + extension.exposeModelRange(new Region( + range.getOffset(), range.getLength())); + } + + setHighlightRange(range.getOffset(), range.getLength(), + true); + if (fOutlinePage != null) { + fOutlineSelectionChangedListener + .uninstall(fOutlinePage); + fOutlinePage.select((ISourceReference) element); + fOutlineSelectionChangedListener.install(fOutlinePage); + } + + return; + } + element = element.getParent(); + } + + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + } + + ISourceViewer viewer = getSourceViewer(); + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + extension.exposeModelRange(new Region(offset, length)); + } else { + resetHighlightRange(); + } + + } + + protected boolean isActivePart() { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + IPartService service = window.getPartService(); + IWorkbenchPart part = service.getActivePart(); + return part != null && part.equals(this); + } + + // public void openContextHelp() { + // IDocument doc = + // this.getDocumentProvider().getDocument(this.getEditorInput()); + // ITextSelection selection = (ITextSelection) + // this.getSelectionProvider().getSelection(); + // int pos = selection.getOffset(); + // String word = getFunctionName(doc, pos); + // openContextHelp(word); + // } + // + // private void openContextHelp(String word) { + // open(word); + // } + // + // public static void open(String word) { + // IHelp help = WorkbenchHelp.getHelpSupport(); + // if (help != null) { + // IHelpResource helpResource = new PHPFunctionHelpResource(word); + // WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource); + // } else { + // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help + // not available"), false); //$NON-NLS-1$ + // } + // } + + // private String getFunctionName(IDocument doc, int pos) { + // Point word = PHPWordExtractor.findWord(doc, pos); + // if (word != null) { + // try { + // return doc.get(word.x, word.y).replace('_', '-'); + // } catch (BadLocationException e) { + // } + // } + // return ""; + // } + + /* + * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) + */ + protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { + + try { + + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) + return; + + String property = event.getProperty(); + + if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) { + Object value = event.getNewValue(); + if (value instanceof Integer) { + sourceViewer.getTextWidget().setTabs( + ((Integer) value).intValue()); + } else if (value instanceof String) { + try { + sourceViewer.getTextWidget().setTabs( + Integer.parseInt((String) value)); + } catch (NumberFormatException e) { + // bug #1038071 - set default tab: + sourceViewer.getTextWidget().setTabs(80); + } + } + return; + } + + // if (OVERVIEW_RULER.equals(property)) { + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // else + // hideOverviewRuler(); + // return; + // } + + // if (LINE_NUMBER_RULER.equals(property)) { + // if (isLineNumberRulerVisible()) + // showLineNumberRuler(); + // else + // hideLineNumberRuler(); + // return; + // } + + // if (fLineNumberRulerColumn != null + // && (LINE_NUMBER_COLOR.equals(property) || + // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || + // PREFERENCE_COLOR_BACKGROUND.equals(property))) { + // + // initializeLineNumberRulerColumn(fLineNumberRulerColumn); + // } + + if (isJavaEditorHoverProperty(property)) + updateHoverBehavior(); + + if (BROWSER_LIKE_LINKS.equals(property)) { + if (isBrowserLikeLinks()) + enableBrowserLikeLinks(); + else + disableBrowserLikeLinks(); + return; + } + + if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE + .equals(property)) { + if (event.getNewValue() instanceof Boolean) { + Boolean disable = (Boolean) event.getNewValue(); + enableOverwriteMode(!disable.booleanValue()); + } + return; + } + + boolean newBooleanValue = false; + Object newValue = event.getNewValue(); + if (newValue != null) + newBooleanValue = Boolean.valueOf(newValue.toString()) + .booleanValue(); + + if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE + .equals(property)) { + if (newBooleanValue) + selectionChanged(); + return; + } + + if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) { + if (newBooleanValue != fMarkOccurrenceAnnotations) { + fMarkOccurrenceAnnotations = newBooleanValue; + if (!fMarkOccurrenceAnnotations) + uninstallOccurrencesFinder(); + else + installOccurrencesFinder(); + } + return; + } + + if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) { + fStickyOccurrenceAnnotations = newBooleanValue; + return; + } + // } + // } + // if + // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) + // { + // if (event.getNewValue() instanceof Boolean) { + // boolean stickyOccurrenceAnnotations= + // ((Boolean)event.getNewValue()).booleanValue(); + // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) + // { + + ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) + .handlePropertyChangeEvent(event); + + // if (affectsOverrideIndicatorAnnotations(event)) { + // if (isShowingOverrideIndicators()) { + // if (fOverrideIndicatorManager == null) + // installOverrideIndicator(true); + // } else { + // if (fOverrideIndicatorManager != null) + // uninstallOverrideIndicator(); + // } + // return; + // } + + if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) { + if (sourceViewer instanceof ProjectionViewer) { + ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer; + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.uninstall(); + // either freshly enabled or provider changed + fProjectionModelUpdater = PHPeclipsePlugin.getDefault() + .getFoldingStructureProviderRegistry() + .getCurrentFoldingProvider(); + if (fProjectionModelUpdater != null) { + fProjectionModelUpdater.install(this, projectionViewer); + } + } + return; + } + } finally { + super.handlePreferenceStoreChanged(event); + } + } + + // /* + // * @see + // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) + // */ + // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { + // + // try { + // + // ISourceViewer sourceViewer = getSourceViewer(); + // if (sourceViewer == null) + // return; + // + // String property = event.getProperty(); + // + // // if + // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) { + // // Object value= event.getNewValue(); + // // if (value instanceof Integer) { + // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); + // // } else if (value instanceof String) { + // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) + // value)); + // // } + // // return; + // // } + // + // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) { + // if (isLineNumberRulerVisible()) + // showLineNumberRuler(); + // else + // hideLineNumberRuler(); + // return; + // } + // + // if (fLineNumberRulerColumn != null + // && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property) + // || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) + // || PREFERENCE_COLOR_BACKGROUND.equals(property))) { + // + // initializeLineNumberRulerColumn(fLineNumberRulerColumn); + // } + // + // } finally { + // super.handlePreferenceStoreChanged(event); + // } + // } + + // private boolean isJavaEditorHoverProperty(String property) { + // return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property) + // || PreferenceConstants.EDITOR_NONE_HOVER.equals(property) + // || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property) + // || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property) + // || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property) + // || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property) + // || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property) + // || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property); + // } + + /** + * Shows the line number ruler column. + */ + // private void showLineNumberRuler() { + // IVerticalRuler v = getVerticalRuler(); + // if (v instanceof CompositeRuler) { + // CompositeRuler c = (CompositeRuler) v; + // c.addDecorator(1, createLineNumberRulerColumn()); + // } + // } + private boolean isJavaEditorHoverProperty(String property) { + return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property); + } + + /** + * Return whether the browser like links should be enabled according to the + * preference store settings. + * + * @return true if the browser like links should be enabled + */ + private boolean isBrowserLikeLinks() { + IPreferenceStore store = getPreferenceStore(); + return store.getBoolean(BROWSER_LIKE_LINKS); + } + + /** + * Enables browser like links. + */ + private void enableBrowserLikeLinks() { + if (fMouseListener == null) { + fMouseListener = new MouseClickListener(); + fMouseListener.install(); + } + } + + /** + * Disables browser like links. + */ + private void disableBrowserLikeLinks() { + if (fMouseListener != null) { + fMouseListener.uninstall(); + fMouseListener = null; + } + } + + /** + * Handles a property change event describing a change of the java core's + * preferences and updates the preference related editor properties. + * + * @param event + * the property change event + */ + protected void handlePreferencePropertyChanged( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + if (COMPILER_TASK_TAGS.equals(event.getProperty())) { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer != null + && affectsTextPresentation(new PropertyChangeEvent(event + .getSource(), event.getProperty(), event + .getOldValue(), event.getNewValue()))) + sourceViewer.invalidateTextPresentation(); + } + if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) { + setWordWrap(); + } + } + + /** + * Return whether the line number ruler column should be visible according + * to the preference store settings. + * + * @return true if the line numbers should be visible + */ + // protected boolean isLineNumberRulerVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(LINE_NUMBER_RULER); + // } + /** + * Hides the line number ruler column. + */ + // private void hideLineNumberRuler() { + // IVerticalRuler v = getVerticalRuler(); + // if (v instanceof CompositeRuler) { + // CompositeRuler c = (CompositeRuler) v; + // try { + // c.removeDecorator(1); + // } catch (Throwable e) { + // } + // } + // } + /* + * @see AbstractTextEditor#handleCursorPositionChanged() + */ + // protected void handleCursorPositionChanged() { + // super.handleCursorPositionChanged(); + // if (!isEditingScriptRunning() && fUpdater != null) + // fUpdater.post(); + // } + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced() + */ + protected void handleElementContentReplaced() { + super.handleElementContentReplaced(); + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.initialize(); + } + + /** + * Initializes the given line number ruler column from the preference store. + * + * @param rulerColumn + * the ruler column to be initialized + */ + // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn + // rulerColumn) { + // JavaTextTools textTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // IColorManager manager = textTools.getColorManager(); + // + // IPreferenceStore store = getPreferenceStore(); + // if (store != null) { + // + // RGB rgb = null; + // // foreground color + // if (store.contains(LINE_NUMBER_COLOR)) { + // if (store.isDefault(LINE_NUMBER_COLOR)) + // rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); + // else + // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); + // } + // rulerColumn.setForeground(manager.getColor(rgb)); + // + // rgb = null; + // // background color + // if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { + // if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { + // if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) + // rgb = PreferenceConverter.getDefaultColor(store, + // PREFERENCE_COLOR_BACKGROUND); + // else + // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); + // } + // } + // rulerColumn.setBackground(manager.getColor(rgb)); + // } + // } + /** + * Creates a new line number ruler column that is appropriately initialized. + */ + // protected IVerticalRulerColumn createLineNumberRulerColumn() { + // fLineNumberRulerColumn = new LineNumberRulerColumn(); + // initializeLineNumberRulerColumn(fLineNumberRulerColumn); + // return fLineNumberRulerColumn; + // } + /* + * @see AbstractTextEditor#createVerticalRuler() + */ + // protected IVerticalRuler createVerticalRuler() { + // CompositeRuler ruler = new CompositeRuler(); + // ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); + // if (isLineNumberRulerVisible()) + // ruler.addDecorator(1, createLineNumberRulerColumn()); + // return ruler; + // } + // private static IRegion getSignedSelection(ITextViewer viewer) { + // + // StyledText text = viewer.getTextWidget(); + // int caretOffset = text.getCaretOffset(); + // Point selection = text.getSelection(); + // + // // caret left + // int offset, length; + // if (caretOffset == selection.x) { + // offset = selection.y; + // length = selection.x - selection.y; + // + // // caret right + // } else { + // offset = selection.x; + // length = selection.y - selection.x; + // } + // + // return new Region(offset, length); + // } + protected IRegion getSignedSelection(ISourceViewer sourceViewer) { + StyledText text = sourceViewer.getTextWidget(); + Point selection = text.getSelectionRange(); + + if (text.getCaretOffset() == selection.x) { + selection.x = selection.x + selection.y; + selection.y = -selection.y; + } + + selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x); + + return new Region(selection.x, selection.y); + } + + /** Preference key for matching brackets */ + protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS; + + /** Preference key for matching brackets color */ + protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; + + /** Preference key for highlighting current line */ + // protected final static String CURRENT_LINE = + // PreferenceConstants.EDITOR_CURRENT_LINE; + /** Preference key for highlight color of current line */ + // protected final static String CURRENT_LINE_COLOR = + // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; + /** Preference key for showing print marging ruler */ + // protected final static String PRINT_MARGIN = + // PreferenceConstants.EDITOR_PRINT_MARGIN; + /** Preference key for print margin ruler color */ + // protected final static String PRINT_MARGIN_COLOR = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; + /** Preference key for print margin ruler column */ + // protected final static String PRINT_MARGIN_COLUMN = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; + /** Preference key for error indication */ + // protected final static String ERROR_INDICATION = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION; + /** Preference key for error color */ + // protected final static String ERROR_INDICATION_COLOR = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; + /** Preference key for warning indication */ + // protected final static String WARNING_INDICATION = + // PreferenceConstants.EDITOR_WARNING_INDICATION; + /** Preference key for warning color */ + // protected final static String WARNING_INDICATION_COLOR = + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; + /** Preference key for task indication */ + protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; + + /** Preference key for task color */ + protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; + + /** Preference key for bookmark indication */ + protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; + + /** Preference key for bookmark color */ + protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; + + /** Preference key for search result indication */ + protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; + + /** Preference key for search result color */ + protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; + + /** Preference key for unknown annotation indication */ + protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; + + /** Preference key for unknown annotation color */ + protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; + + /** Preference key for shwoing the overview ruler */ + protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; + + /** Preference key for error indication in overview ruler */ + protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for warning indication in overview ruler */ + protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for task indication in overview ruler */ + protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for bookmark indication in overview ruler */ + protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for search result indication in overview ruler */ + protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for unknown annotation indication in overview ruler */ + protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + + // /** Preference key for compiler task tags */ + // private final static String COMPILER_TASK_TAGS= + // JavaCore.COMPILER_TASK_TAGS; + /** Preference key for browser like links */ + private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS; + + /** Preference key for key modifier of browser like links */ + private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER; + + /** + * Preference key for key modifier mask of browser like links. The value is + * only used if the value of EDITOR_BROWSER_LIKE_LINKS cannot + * be resolved to valid SWT modifier bits. + * + * @since 2.1.1 + */ + private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK; + + private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' }; + + private static boolean isBracket(char character) { + for (int i = 0; i != BRACKETS.length; ++i) + if (character == BRACKETS[i]) + return true; + return false; + } + + private static boolean isSurroundedByBrackets(IDocument document, int offset) { + if (offset == 0 || offset == document.getLength()) + return false; + + try { + return isBracket(document.getChar(offset - 1)) + && isBracket(document.getChar(offset)); + + } catch (BadLocationException e) { + return false; + } + } + + // protected void configureSourceViewerDecorationSupport() { + // + // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher); + // + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.UNKNOWN, + // UNKNOWN_INDICATION_COLOR, + // UNKNOWN_INDICATION, + // UNKNOWN_INDICATION_IN_OVERVIEW_RULER, + // 0); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.BOOKMARK, + // BOOKMARK_INDICATION_COLOR, + // BOOKMARK_INDICATION, + // BOOKMARK_INDICATION_IN_OVERVIEW_RULER, + // 1); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.TASK, + // TASK_INDICATION_COLOR, + // TASK_INDICATION, + // TASK_INDICATION_IN_OVERVIEW_RULER, + // 2); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.SEARCH, + // SEARCH_RESULT_INDICATION_COLOR, + // SEARCH_RESULT_INDICATION, + // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, + // 3); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.WARNING, + // WARNING_INDICATION_COLOR, + // WARNING_INDICATION, + // WARNING_INDICATION_IN_OVERVIEW_RULER, + // 4); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.ERROR, + // ERROR_INDICATION_COLOR, + // ERROR_INDICATION, + // ERROR_INDICATION_IN_OVERVIEW_RULER, + // 5); + // + // fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, + // CURRENT_LINE_COLOR); + // fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, + // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN); + // fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, + // MATCHING_BRACKETS_COLOR); + // + // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey()); + // + // } + /** + * Returns the Java element wrapped by this editors input. + * + * @return the Java element wrapped by this editors input. + * @since 3.0 + */ + abstract protected IJavaElement getInputJavaElement(); + + protected void updateStatusLine() { + ITextSelection selection = (ITextSelection) getSelectionProvider() + .getSelection(); + Annotation annotation = getAnnotation(selection.getOffset(), selection + .getLength()); + setStatusLineErrorMessage(null); + setStatusLineMessage(null); + if (annotation != null) { + try { + fIsUpdatingAnnotationViews = true; + updateAnnotationViews(annotation); + } finally { + fIsUpdatingAnnotationViews = false; + } + if (annotation instanceof IJavaAnnotation + && ((IJavaAnnotation) annotation).isProblem()) + setStatusLineMessage(annotation.getText()); + } + } + + /** + * Jumps to the matching bracket. + */ + public void gotoMatchingBracket() { + + ISourceViewer sourceViewer = getSourceViewer(); + IDocument document = sourceViewer.getDocument(); + if (document == null) + return; + + IRegion selection = getSignedSelection(sourceViewer); + + int selectionLength = Math.abs(selection.getLength()); + if (selectionLength > 1) { + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ + sourceViewer.getTextWidget().getDisplay().beep(); + return; + } + + // #26314 + int sourceCaretOffset = selection.getOffset() + selection.getLength(); + if (isSurroundedByBrackets(document, sourceCaretOffset)) + sourceCaretOffset -= selection.getLength(); + + IRegion region = fBracketMatcher.match(document, sourceCaretOffset); + if (region == null) { + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ + sourceViewer.getTextWidget().getDisplay().beep(); + return; + } + + int offset = region.getOffset(); + int length = region.getLength(); + + if (length < 1) + return; + + int anchor = fBracketMatcher.getAnchor(); + int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + + length - 1; + + boolean visible = false; + if (sourceViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; + visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1); + } else { + IRegion visibleRegion = sourceViewer.getVisibleRegion(); + visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion + .getOffset() + + visibleRegion.getLength()); + } + + if (!visible) { + setStatusLineErrorMessage(PHPEditorMessages + .getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ + sourceViewer.getTextWidget().getDisplay().beep(); + return; + } + + if (selection.getLength() < 0) + targetOffset -= selection.getLength(); + + sourceViewer.setSelectedRange(targetOffset, selection.getLength()); + sourceViewer.revealRange(targetOffset, selection.getLength()); + } + + /** + * Ses the given message as error message to this editor's status line. + * + * @param msg + * message to be set + */ + protected void setStatusLineErrorMessage(String msg) { + IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); + if (statusLine != null) + statusLine.setMessage(true, msg, null); + } + + /** + * Sets the given message as message to this editor's status line. + * + * @param msg + * message to be set + * @since 3.0 + */ + protected void setStatusLineMessage(String msg) { + IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); + if (statusLine != null) + statusLine.setMessage(false, msg, null); + } + + /** + * Returns the annotation closest to the given range respecting the given + * direction. If an annotation is found, the annotations current position is + * copied into the provided annotation position. + * + * @param offset + * the region offset + * @param length + * the region length + * @param forward + * true for forwards, false for + * backward + * @param annotationPosition + * the position of the found annotation + * @return the found annotation + */ + private Annotation getNextAnnotation(final int offset, final int length, + boolean forward, Position annotationPosition) { + + Annotation nextAnnotation = null; + Position nextAnnotationPosition = null; + Annotation containingAnnotation = null; + Position containingAnnotationPosition = null; + boolean currentAnnotation = false; + + IDocument document = getDocumentProvider() + .getDocument(getEditorInput()); + int endOfDocument = document.getLength(); + int distance = Integer.MAX_VALUE; + + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); + Iterator e = new JavaAnnotationIterator(model, true, true); + while (e.hasNext()) { + Annotation a = (Annotation) e.next(); + if ((a instanceof IJavaAnnotation) + && ((IJavaAnnotation) a).hasOverlay() + || !isNavigationTarget(a)) + continue; + + Position p = model.getPosition(a); + if (p == null) + continue; + + if (forward && p.offset == offset || !forward + && p.offset + p.getLength() == offset + length) {// || + // p.includes(offset)) + // { + if (containingAnnotation == null + || (forward + && p.length >= containingAnnotationPosition.length || !forward + && p.length >= containingAnnotationPosition.length)) { + containingAnnotation = a; + containingAnnotationPosition = p; + currentAnnotation = p.length == length; + } + } else { + int currentDistance = 0; + + if (forward) { + currentDistance = p.getOffset() - offset; + if (currentDistance < 0) + currentDistance = endOfDocument + currentDistance; + + if (currentDistance < distance + || currentDistance == distance + && p.length < nextAnnotationPosition.length) { + distance = currentDistance; + nextAnnotation = a; + nextAnnotationPosition = p; + } + } else { + currentDistance = offset + length + - (p.getOffset() + p.length); + if (currentDistance < 0) + currentDistance = endOfDocument + currentDistance; + + if (currentDistance < distance + || currentDistance == distance + && p.length < nextAnnotationPosition.length) { + distance = currentDistance; + nextAnnotation = a; + nextAnnotationPosition = p; + } + } + } + } + if (containingAnnotationPosition != null + && (!currentAnnotation || nextAnnotation == null)) { + annotationPosition.setOffset(containingAnnotationPosition + .getOffset()); + annotationPosition.setLength(containingAnnotationPosition + .getLength()); + return containingAnnotation; + } + if (nextAnnotationPosition != null) { + annotationPosition.setOffset(nextAnnotationPosition.getOffset()); + annotationPosition.setLength(nextAnnotationPosition.getLength()); + } + + return nextAnnotation; + } + + /** + * Returns the annotation overlapping with the given range or + * null. + * + * @param offset + * the region offset + * @param length + * the region length + * @return the found annotation or null + * @since 3.0 + */ + private Annotation getAnnotation(int offset, int length) { + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); + Iterator e = new JavaAnnotationIterator(model, true, true); + while (e.hasNext()) { + Annotation a = (Annotation) e.next(); + if (!isNavigationTarget(a)) + continue; + + Position p = model.getPosition(a); + if (p != null && p.overlapsWith(offset, length)) + return a; + } + + return null; + } + + /** + * Returns whether the given annotation is configured as a target for the + * "Go to Next/Previous Annotation" actions + * + * @param annotation + * the annotation + * @return true if this is a target, false + * otherwise + * @since 3.0 + */ + protected boolean isNavigationTarget(Annotation annotation) { + Preferences preferences = EditorsUI.getPluginPreferences(); + AnnotationPreference preference = getAnnotationPreferenceLookup() + .getAnnotationPreference(annotation); + // See bug 41689 + // String key= forward ? preference.getIsGoToNextNavigationTargetKey() : + // preference.getIsGoToPreviousNavigationTargetKey(); + String key = preference == null ? null : preference + .getIsGoToNextNavigationTargetKey(); + return (key != null && preferences.getBoolean(key)); + } + + /** + * Returns a segmentation of the line of the given document appropriate for + * bidi rendering. The default implementation returns only the string + * literals of a php code line as segments. + * + * @param document + * the document + * @param lineOffset + * the offset of the line + * @return the line's bidi segmentation + * @throws BadLocationException + * in case lineOffset is not valid in document + */ + public static int[] getBidiLineSegments(IDocument document, int lineOffset) + throws BadLocationException { + + IRegion line = document.getLineInformationOfOffset(lineOffset); + ITypedRegion[] linePartitioning = document.computePartitioning( + lineOffset, line.getLength()); + + List segmentation = new ArrayList(); + for (int i = 0; i < linePartitioning.length; i++) { + if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i] + .getType())) { + segmentation.add(linePartitioning[i]); + } else if (IPHPPartitions.PHP_STRING_HEREDOC + .equals(linePartitioning[i].getType())) { + segmentation.add(linePartitioning[i]); + } + } + + if (segmentation.size() == 0) + return null; + + int size = segmentation.size(); + int[] segments = new int[size * 2 + 1]; + + int j = 0; + for (int i = 0; i < size; i++) { + ITypedRegion segment = (ITypedRegion) segmentation.get(i); + + if (i == 0) + segments[j++] = 0; + + int offset = segment.getOffset() - lineOffset; + if (offset > segments[j - 1]) + segments[j++] = offset; + + if (offset + segment.getLength() >= line.getLength()) + break; + + segments[j++] = offset + segment.getLength(); + } + + if (j < segments.length) { + int[] result = new int[j]; + System.arraycopy(segments, 0, result, 0, j); + segments = result; + } + + return segments; + } + + /** + * Returns a segmentation of the given line appropriate for bidi rendering. + * The default implementation returns only the string literals of a php code + * line as segments. + * + * @param lineOffset + * the offset of the line + * @param line + * the content of the line + * @return the line's bidi segmentation + */ + protected int[] getBidiLineSegments(int lineOffset, String line) { + IDocumentProvider provider = getDocumentProvider(); + if (provider != null && line != null && line.length() > 0) { + IDocument document = provider.getDocument(getEditorInput()); + if (document != null) + try { + return getBidiLineSegments(document, lineOffset); + } catch (BadLocationException x) { + // ignore + } + } + return null; + } + + /* + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) + */ + // protected final ISourceViewer createSourceViewer( + // Composite parent, + // IVerticalRuler ruler, + // int styles) { + // ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles); + // StyledText text = viewer.getTextWidget(); + // text.addBidiSegmentListener(new BidiSegmentListener() { + // public void lineGetSegments(BidiSegmentEvent event) { + // event.segments = getBidiLineSegments(event.lineOffset, event.lineText); + // } + // }); + // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); + // return viewer; + // } + public final ISourceViewer getViewer() { + return getSourceViewer(); + } + + // protected void showOverviewRuler() { + // if (fOverviewRuler != null) { + // if (getSourceViewer() instanceof ISourceViewerExtension) { + // ((ISourceViewerExtension) + // getSourceViewer()).showAnnotationsOverview(true); + // fSourceViewerDecorationSupport.updateOverviewDecorations(); + // } + // } + // } + // + // protected void hideOverviewRuler() { + // if (getSourceViewer() instanceof ISourceViewerExtension) { + // fSourceViewerDecorationSupport.hideAnnotationOverview(); + // ((ISourceViewerExtension) + // getSourceViewer()).showAnnotationsOverview(false); + // } + // } + + // protected boolean isOverviewRulerVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(OVERVIEW_RULER); + // } + /* + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) + */ + // protected ISourceViewer createJavaSourceViewer( + // Composite parent, + // IVerticalRuler ruler, + // IOverviewRuler overviewRuler, + // boolean isOverviewRulerVisible, + // int styles) { + // return new SourceViewer(parent, ruler, overviewRuler, + // isOverviewRulerVisible(), styles); + // } + /* + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) + */ + protected ISourceViewer createJavaSourceViewer(Composite parent, + IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { + return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), + isOverviewRulerVisible(), styles, store); + } + + /* + * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, + * int) + */ + protected final ISourceViewer createSourceViewer(Composite parent, + IVerticalRuler verticalRuler, int styles) { + + ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, + getOverviewRuler(), isOverviewRulerVisible(), styles, + getPreferenceStore()); + + StyledText text = viewer.getTextWidget(); + text.addBidiSegmentListener(new BidiSegmentListener() { + public void lineGetSegments(BidiSegmentEvent event) { + event.segments = getBidiLineSegments(event.lineOffset, + event.lineText); + } + }); + + // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); + + // ensure source viewer decoration support has been created and + // configured + getSourceViewerDecorationSupport(viewer); + + return viewer; + } + + /* + * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) + */ + protected boolean affectsTextPresentation(PropertyChangeEvent event) { + return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()) + .affectsTextPresentation(event) + || super.affectsTextPresentation(event); + } + + // + // protected boolean affectsTextPresentation(PropertyChangeEvent event) { + // JavaTextTools textTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // return textTools.affectsBehavior(event); + // } + /** + * Creates and returns the preference store for this Java editor with the + * given input. + * + * @param input + * The editor input for which to create the preference store + * @return the preference store for this editor + * + * @since 3.0 + */ + private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) { + List stores = new ArrayList(3); + + IJavaProject project = EditorUtility.getJavaProject(input); + if (project != null) + stores.add(new OptionsAdapter(project.getOptions(false), + PHPeclipsePlugin.getDefault().getMockupPreferenceStore(), + new OptionsAdapter.IPropertyChangeEventFilter() { + + public boolean isFiltered(PropertyChangeEvent event) { + IJavaElement inputJavaElement = getInputJavaElement(); + IJavaProject javaProject = inputJavaElement != null ? inputJavaElement + .getJavaProject() + : null; + if (javaProject == null) + return true; + + return !javaProject.getProject().equals( + event.getSource()); + } + + })); + + stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore()); + stores.add(new PreferencesAdapter(JavaCore.getPlugin() + .getPluginPreferences())); + stores.add(EditorsUI.getPreferenceStore()); + + return new ChainedPreferenceStore((IPreferenceStore[]) stores + .toArray(new IPreferenceStore[stores.size()])); + } + + /** + * Jumps to the error next according to the given direction. + */ + public void gotoError(boolean forward) { + + ISelectionProvider provider = getSelectionProvider(); + + ITextSelection s = (ITextSelection) provider.getSelection(); + Position errorPosition = new Position(0, 0); + IJavaAnnotation nextError = getNextError(s.getOffset(), forward, + errorPosition); + + if (nextError != null) { + + IMarker marker = null; + if (nextError instanceof MarkerAnnotation) + marker = ((MarkerAnnotation) nextError).getMarker(); + else { + Iterator e = nextError.getOverlaidIterator(); + if (e != null) { + while (e.hasNext()) { + Object o = e.next(); + if (o instanceof MarkerAnnotation) { + marker = ((MarkerAnnotation) o).getMarker(); + break; + } + } + } + } + + if (marker != null) { + IWorkbenchPage page = getSite().getPage(); + IViewPart view = view = page + .findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$ + if (view instanceof TaskList) { + StructuredSelection ss = new StructuredSelection(marker); + ((TaskList) view).setSelection(ss, true); + } + } + + selectAndReveal(errorPosition.getOffset(), errorPosition + .getLength()); + // setStatusLineErrorMessage(nextError.getMessage()); + + } else { + + setStatusLineErrorMessage(null); + + } + } + + private IJavaAnnotation getNextError(int offset, boolean forward, + Position errorPosition) { + + IJavaAnnotation nextError = null; + Position nextErrorPosition = null; + + IDocument document = getDocumentProvider() + .getDocument(getEditorInput()); + int endOfDocument = document.getLength(); + int distance = 0; + + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); + Iterator e = new JavaAnnotationIterator(model, false); + while (e.hasNext()) { + + IJavaAnnotation a = (IJavaAnnotation) e.next(); + if (a.hasOverlay() || !a.isProblem()) + continue; + + Position p = model.getPosition((Annotation) a); + if (!p.includes(offset)) { + + int currentDistance = 0; + + if (forward) { + currentDistance = p.getOffset() - offset; + if (currentDistance < 0) + currentDistance = endOfDocument - offset + + p.getOffset(); + } else { + currentDistance = offset - p.getOffset(); + if (currentDistance < 0) + currentDistance = offset + endOfDocument + - p.getOffset(); + } + + if (nextError == null || currentDistance < distance) { + distance = currentDistance; + nextError = a; + nextErrorPosition = p; + } + } + } + + if (nextErrorPosition != null) { + errorPosition.setOffset(nextErrorPosition.getOffset()); + errorPosition.setLength(nextErrorPosition.getLength()); + } + + return nextError; + } + + protected void uninstallOverrideIndicator() { + // if (fOverrideIndicatorManager != null) { + // fOverrideIndicatorManager.removeAnnotations(); + // fOverrideIndicatorManager= null; + // } + } + + protected void installOverrideIndicator(boolean waitForReconcilation) { + uninstallOverrideIndicator(); + IAnnotationModel model = getDocumentProvider().getAnnotationModel( + getEditorInput()); + final IJavaElement inputElement = getInputJavaElement(); + + if (model == null || inputElement == null) + return; + + // fOverrideIndicatorManager= new OverrideIndicatorManager(model, + // inputElement, null); + // + // if (provideAST) { + // Job job= new + // Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) + // { + // //$NON-NLS-1$ + // /* + // * @see + // org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + // * @since 3.0 + // */ + // protected IStatus run(IProgressMonitor monitor) { + // CompilationUnit ast= + // JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, + // null); + // if (fOverrideIndicatorManager != null) // editor might have been + // closed + // in the meanwhile + // fOverrideIndicatorManager.reconciled(ast, true, monitor); + // return Status.OK_STATUS; + // } + // }; + // job.setPriority(Job.DECORATE); + // job.setSystem(true); + // job.schedule(); + // } + } + + /** + * Tells whether override indicators are shown. + * + * @return true if the override indicators are shown + * @since 3.0 + */ + // protected boolean isShowingOverrideIndicators() { + // AnnotationPreference preference= + // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE); + // IPreferenceStore store= getPreferenceStore(); + // return getBoolean(store, preference.getHighlightPreferenceKey()) + // || getBoolean(store, preference.getVerticalRulerPreferenceKey()) + // || getBoolean(store, preference.getOverviewRulerPreferenceKey()) + // || getBoolean(store, preference.getTextPreferenceKey()); + // } + /** + * Returns the boolean preference for the given key. + * + * @param store + * the preference store + * @param key + * the preference key + * @return true if the key exists in the store and its value + * is true + * @since 3.0 + */ +// private boolean getBoolean(IPreferenceStore store, String key) { +// return key != null && store.getBoolean(key); +// } + + protected boolean isPrefQuickDiffAlwaysOn() { + return false; // never show change ruler for the non-editable java + // editor. + // Overridden in subclasses like PHPUnitEditor + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() + */ + protected void createNavigationActions() { + super.createNavigationActions(); + + final StyledText textWidget = getSourceViewer().getTextWidget(); + + IAction action = new SmartLineStartAction(textWidget, false); + action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); + setAction(ITextEditorActionDefinitionIds.LINE_START, action); + + action = new SmartLineStartAction(textWidget, true); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); + setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); + + action = new NavigatePreviousSubWordAction(); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); + setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); + textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); + + action = new NavigateNextSubWordAction(); + action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); + setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); + textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); + + action = new SelectPreviousSubWordAction(); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); + setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); + textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, + SWT.NULL); + + action = new SelectNextSubWordAction(); + action + .setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); + setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); + textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, + SWT.NULL); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler() + */ + // protected CompositeRuler createCompositeRuler() { + // if + // (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) + // return super.createCompositeRuler(); + // + // CompositeRuler ruler = new CompositeRuler(); + // AnnotationRulerColumn column = new + // AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess()); + // column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new + // IDoubleClickListener() { + // + // public void doubleClick(DoubleClickEvent event) { + // // for now: just invoke ruler double click action + // triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); + // } + // + // private void triggerAction(String actionID) { + // IAction action = getAction(actionID); + // if (action != null) { + // if (action instanceof IUpdate) + // ((IUpdate) action).update(); + // // hack to propagate line change + // if (action instanceof ISelectionListener) { + // ((ISelectionListener) action).selectionChanged(null, null); + // } + // if (action.isEnabled()) + // action.run(); + // } + // } + // + // })); + // ruler.addDecorator(0, column); + // + // if (isLineNumberRulerVisible()) + // ruler.addDecorator(1, createLineNumberRulerColumn()); + // else if (isPrefQuickDiffAlwaysOn()) + // ruler.addDecorator(1, createChangeRulerColumn()); + // + // return ruler; + // } + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createAnnotationRulerColumn(org.eclipse.jface.text.source.CompositeRuler) + * @since 3.2 + */ + protected IVerticalRulerColumn createAnnotationRulerColumn( + CompositeRuler ruler) { + if (!getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER)) + return super.createAnnotationRulerColumn(ruler); + + AnnotationRulerColumn column = new AnnotationRulerColumn( + VERTICAL_RULER_WIDTH, getAnnotationAccess()); + column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), + new IDoubleClickListener() { + + public void doubleClick(DoubleClickEvent event) { + // for now: just invoke ruler double click action + triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); + } + + private void triggerAction(String actionID) { + IAction action = getAction(actionID); + if (action != null) { + if (action instanceof IUpdate) + ((IUpdate) action).update(); + // hack to propagate line change + if (action instanceof ISelectionListener) { + ((ISelectionListener) action).selectionChanged( + null, null); + } + if (action.isEnabled()) + action.run(); + } + } + + })); + + return column; + } + + /** + * Returns the folding action group, or null if there is + * none. + * + * @return the folding action group, or null if there is none + * @since 3.0 + */ + protected FoldingActionGroup getFoldingActionGroup() { + return fFoldingGroup; + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert() + */ + protected void performRevert() { + ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); + projectionViewer.setRedraw(false); + try { + + boolean projectionMode = projectionViewer.isProjectionMode(); + if (projectionMode) { + projectionViewer.disableProjection(); + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.uninstall(); + } + + super.performRevert(); + + if (projectionMode) { + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.install(this, projectionViewer); + projectionViewer.enableProjection(); + } + + } finally { + projectionViewer.setRedraw(true); + } + } + + /** + * React to changed selection. + * + * @since 3.0 + */ + protected void selectionChanged() { + if (getSelectionProvider() == null) + return; + ISourceReference element = computeHighlightRangeSourceReference(); + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) + synchronizeOutlinePage(element); + setSelection(element, false); + updateStatusLine(); + } + + private boolean isJavaOutlinePageActive() { + IWorkbenchPart part = getActivePart(); + return part instanceof ContentOutline + && ((ContentOutline) part).getCurrentPage() == fOutlinePage; + } + + private IWorkbenchPart getActivePart() { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + IPartService service = window.getPartService(); + IWorkbenchPart part = service.getActivePart(); + return part; + } + + /** + * Computes and returns the source reference that includes the caret and + * serves as provider for the outline page selection and the editor range + * indication. + * + * @return the computed source reference + * @since 3.0 + */ + protected ISourceReference computeHighlightRangeSourceReference() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) + return null; + + StyledText styledText = sourceViewer.getTextWidget(); + if (styledText == null) + return null; + + int caret = 0; + if (sourceViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; + caret = extension.widgetOffset2ModelOffset(styledText + .getCaretOffset()); + } else { + int offset = sourceViewer.getVisibleRegion().getOffset(); + caret = offset + styledText.getCaretOffset(); + } + + IJavaElement element = getElementAt(caret, false); + + if (!(element instanceof ISourceReference)) + return null; + + if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { + + IImportDeclaration declaration = (IImportDeclaration) element; + IImportContainer container = (IImportContainer) declaration + .getParent(); + ISourceRange srcRange = null; + + try { + srcRange = container.getSourceRange(); + } catch (JavaModelException e) { + } + + if (srcRange != null && srcRange.getOffset() == caret) + return container; + } + + return (ISourceReference) element; + } + + /** + * Returns the most narrow java element including the given offset. + * + * @param offset + * the offset inside of the requested element + * @param reconcile + * true if editor input should be reconciled in + * advance + * @return the most narrow java element + * @since 3.0 + */ + protected IJavaElement getElementAt(int offset, boolean reconcile) { + return getElementAt(offset); + } + + public ShowInContext getShowInContext() { + IFile file = null; + if(getEditorInput() instanceof FileStoreEditorInput){ + FileStoreEditorInput fei = (FileStoreEditorInput) getEditorInput(); + file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getURI().getPath())); + } else if (getEditorInput() instanceof FileEditorInput) { + FileEditorInput fei = (FileEditorInput) getEditorInput(); + // added to fix ticket 637 + file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getURI().getPath())); + } else if (getEditorInput() instanceof ExternalEditorInput) { + ExternalEditorInput fei = (ExternalEditorInput) getEditorInput(); + file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fei.getFullPath()/* .getURI().getPath()*/)); + } + + ShowInContext context = BrowserUtil.getShowInContext(file, + false, ""); + if (context != null) { + return context; + } + return new ShowInContext(file, null); + } + + public String[] getShowInTargetIds() { + return new String[] { BrowserView.ID_BROWSER }; + } + + /** + * Updates the occurrences annotations based on the current selection. + * + * @param selection + * the text selection + * @param astRoot + * the compilation unit AST + * @since 3.0 + */ + protected void updateOccurrenceAnnotations(ITextSelection selection) {// , + // CompilationUnit + // astRoot) + // { + + if (fOccurrencesFinderJob != null) + fOccurrencesFinderJob.cancel(); + + if (!fMarkOccurrenceAnnotations) + return; + + // if (astRoot == null || selection == null) + if (selection == null) + return; + + IDocument document = getSourceViewer().getDocument(); + if (document == null) + return; + + fMarkOccurrenceTargetRegion = null; + if (document instanceof IDocumentExtension4) { + int offset = selection.getOffset(); + long currentModificationStamp = ((IDocumentExtension4) document) + .getModificationStamp(); + if (fMarkOccurrenceTargetRegion != null + && currentModificationStamp == fMarkOccurrenceModificationStamp) { + if (fMarkOccurrenceTargetRegion.getOffset() <= offset + && offset <= fMarkOccurrenceTargetRegion.getOffset() + + fMarkOccurrenceTargetRegion.getLength()) + return; + } + fMarkOccurrenceTargetRegion = JavaWordFinder.findWord(document, + offset); + fMarkOccurrenceModificationStamp = currentModificationStamp; + } + + if (fMarkOccurrenceTargetRegion == null + || fMarkOccurrenceTargetRegion.getLength() == 0) { + return; + } + + List matches = null; + + if (matches == null) { + try { + matches = new ArrayList(); + + Scanner fScanner = new Scanner(); + fScanner.setSource(document.get().toCharArray()); + fScanner.setPHPMode(false); + String wordStr; + char[] word; + + wordStr = document.get(fMarkOccurrenceTargetRegion.getOffset(), + fMarkOccurrenceTargetRegion.getLength()); + if (wordStr != null) { + word = wordStr.toCharArray(); + TokenName fToken = ITerminalSymbols.TokenName.EOF; + try { + fToken = fScanner.getNextToken(); + while (fToken != ITerminalSymbols.TokenName.EOF) { // && + // fToken + // != + // TokenName.ERROR) { + if (fToken == ITerminalSymbols.TokenName.VARIABLE + || fToken == ITerminalSymbols.TokenName.IDENTIFIER) { + // global variable + if (fScanner.equalsCurrentTokenSource(word)) { + matches + .add(new Region( + fScanner + .getCurrentTokenStartPosition(), + fScanner + .getCurrentTokenEndPosition() + - fScanner + .getCurrentTokenStartPosition() + + 1)); + } + } + fToken = fScanner.getNextToken(); + } + } catch (InvalidInputException e) { + // ignore errors + } catch (SyntaxError e) { + // ignore errors + } + } + } catch (BadLocationException e1) { + // ignore errors + } catch (Exception e) { + e.printStackTrace(); + // ignore errors + } + + } + + if (matches == null || matches.size() == 0) { + if (!fStickyOccurrenceAnnotations) + removeOccurrenceAnnotations(); + return; + } + + Position[] positions = new Position[matches.size()]; + int i = 0; + for (Iterator each = matches.iterator(); each.hasNext();) { + IRegion currentNode = (IRegion) each.next(); + positions[i++] = new Position(currentNode.getOffset(), currentNode + .getLength()); + } + + fOccurrencesFinderJob = new OccurrencesFinderJob(document, positions, + selection); + // fOccurrencesFinderJob.setPriority(Job.DECORATE); + // fOccurrencesFinderJob.setSystem(true); + // fOccurrencesFinderJob.schedule(); + fOccurrencesFinderJob.run(new NullProgressMonitor()); + } + + protected void installOccurrencesFinder() { + fMarkOccurrenceAnnotations = true; + + fPostSelectionListenerWithAST = new ISelectionListenerWithAST() { + public void selectionChanged(IEditorPart part, + ITextSelection selection) { // , + // CompilationUnit + // astRoot) + // { + updateOccurrenceAnnotations(selection);// , astRoot); + } + }; + SelectionListenerWithASTManager.getDefault().addListener(this, + fPostSelectionListenerWithAST); + if (getSelectionProvider() != null) { + fForcedMarkOccurrencesSelection = getSelectionProvider() + .getSelection(); + SelectionListenerWithASTManager.getDefault().forceSelectionChange( + this, (ITextSelection) fForcedMarkOccurrencesSelection); + } + + if (fOccurrencesFinderJobCanceler == null) { + fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler(); + fOccurrencesFinderJobCanceler.install(); + } + } + + protected void uninstallOccurrencesFinder() { + fMarkOccurrenceAnnotations = false; + + if (fOccurrencesFinderJob != null) { + fOccurrencesFinderJob.cancel(); + fOccurrencesFinderJob = null; + } + + if (fOccurrencesFinderJobCanceler != null) { + fOccurrencesFinderJobCanceler.uninstall(); + fOccurrencesFinderJobCanceler = null; + } + + if (fPostSelectionListenerWithAST != null) { + SelectionListenerWithASTManager.getDefault().removeListener(this, + fPostSelectionListenerWithAST); + fPostSelectionListenerWithAST = null; + } + + removeOccurrenceAnnotations(); + } + + protected boolean isMarkingOccurrences() { + return fMarkOccurrenceAnnotations; + } + + void removeOccurrenceAnnotations() { + fMarkOccurrenceModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; + fMarkOccurrenceTargetRegion = null; + + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider == null) + return; + + IAnnotationModel annotationModel = documentProvider + .getAnnotationModel(getEditorInput()); + if (annotationModel == null || fOccurrenceAnnotations == null) + return; + + synchronized (getLockObject(annotationModel)) { + if (annotationModel instanceof IAnnotationModelExtension) { + ((IAnnotationModelExtension) annotationModel) + .replaceAnnotations(fOccurrenceAnnotations, null); + } else { + for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++) + annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); + } + fOccurrenceAnnotations = null; + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorActionDefinitionIds.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditorMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java new file mode 100644 index 0000000..110aeb3 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java @@ -0,0 +1,348 @@ +package net.sourceforge.phpeclipse.phpeditor; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; +import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword; +import net.sourceforge.phpeclipse.phpeditor.php.PHPType; + +import org.eclipse.core.runtime.CoreException; +//import org.eclipse.core.runtime.IPath; +import org.eclipse.jface.preference.IPreferenceStore; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * PHPSyntaxRdr reads PHP specifics from an XML file (eg. + * keywords) + */ + +public class PHPSyntaxRdr { + // private static final String PHPDEFAULT_FILE = "default-syntax.xml"; + // //$NON-NLS-1$ + private static final String PHPSYNTAX_FILE = "syntax.xml"; //$NON-NLS-1$ + // private static final String USERSYNTAX_FILE = "usersyntax.xml"; + // //$NON-NLS-1$ + // private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; + // //$NON-NLS-1$ + + private static final String PHPSYNTAX_TAG = "s"; //$NON-NLS-1$ + + private static final String KEYWORD_ATTR = "k"; //$NON-NLS-1$ + + private static final String TYPE_ATTR = "t"; //$NON-NLS-1$ + + private static final String CONSTANT_ATTR = "c"; //$NON-NLS-1$ + + private static final String FN_ATTR = "f"; //$NON-NLS-1$ + + private static final String USAGE_ATTR = "u"; //$NON-NLS-1$ + // private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ + + private static IPreferenceStore store; + + //private static boolean hasXMLFileBeenRead = true; + + // The following variable is used to hold the syntax from + // the suers custom file - if that file should be changed, + // then all entries in this variable should be removed from + // the word list, reread from the file and then reinserted. + private static ArrayList userdefsyntaxdata; + + private static ArrayList syntaxdata; + + public PHPSyntaxRdr() { + // see getSyntaxData() + syntaxdata = null; + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + public static void readInSyntax() { + try { +// hasXMLFileBeenRead = true; + /* + * Attempt to read the syntax file from the metadata if this does + * not work, create metadata from default + */ + /*File syntaxFile = getSyntaxFile(); + if (syntaxFile.exists()) { + readFromFile(syntaxFile); + } else {*/ + readFromStream(PHPSyntaxRdr.class + .getResourceAsStream(PHPSYNTAX_FILE)); + //saveToFile(syntaxFile); + /*}*/ + /* Read the user-defined syntax file if it exists */ + // String buffer = new + // String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE)); + /*if (store == null) + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + String buffer = new String(store + .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!(buffer.equals("") || buffer == null)) { + readFromFile(buffer); + }*/ + } catch (CoreException ce) { + ce.printStackTrace(); + } + } + + public static void readFromFile(String filename) { + try { + readFromFile(new File(filename)); + } catch (CoreException e) { + } + } + + public static void readFromFile(File file) throws CoreException { + InputStream stream = null; + + if (file.exists()) { + try { + stream = new FileInputStream(file); + readFromStream(stream); + } catch (IOException e) { + throwReadException(e); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + } + + public static void readFromStream(InputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + Document document = parser.parse(new InputSource(stream)); + // Read in the Standard PHPSyntax "stuff" + NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG); + + int count = elements.getLength(); + for (int i = 0; i != count; i++) { + Node node = elements.item(i); + NamedNodeMap attributes = node.getAttributes(); + + if (attributes == null) + continue; + + String Keyword = getAttributeValue(attributes, KEYWORD_ATTR); + String Type = getAttributeValue(attributes, TYPE_ATTR); + String Function = getAttributeValue(attributes, FN_ATTR); + String Constant = getAttributeValue(attributes, CONSTANT_ATTR); + String usage = getAttributeValue(attributes, USAGE_ATTR); + // String Tokenval = getAttributeValue(attributes, + // TOKENVAL_ATTR); + + StringBuffer buffer = new StringBuffer(); + NodeList children = node.getChildNodes(); + for (int j = 0; j != children.getLength(); j++) { + String value = children.item(j).getNodeValue(); + if (value != null) + buffer.append(value); + } + String description = buffer.toString().trim(); + + if (Keyword == null && Type == null && Function == null + && Constant == null) { + // ignore as it is not a valid phpsyntax tag + } else { + if (Keyword != null) { + // syntaxdata.add(new PHPKeyword(Keyword, usage, + // Tokenval)); + syntaxdata.add(new PHPKeyword(Keyword, usage)); + } else if (Type != null) { + syntaxdata.add(new PHPType(Type, usage)); + } else if (Function != null) { + syntaxdata.add(new PHPFunction(Function, usage, + description)); + } else if (Constant != null) { + syntaxdata.add(new PHPConstant(Constant, null, + description)); + } + } + } + } catch (ParserConfigurationException e) { + throwReadException(e); + } catch (IOException e) { + throwReadException(e); + } catch (SAXParseException e) { + System.out.println("SAXParseException in line:" + e.getLineNumber() + + " column:" + e.getColumnNumber()); + throwReadException(e); + } catch (SAXException e) { + throwReadException(e); + } + } + + public static ArrayList getSyntaxData() { + if (syntaxdata == null) { + syntaxdata = new ArrayList(); + readInSyntax(); + } + return syntaxdata; + } + + public static void replaceUserDefFile() { + /* Replace the user-defined syntax file if it exists */ + String buffer = new String(store + .getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!buffer.equals("") || buffer == null) { + readFromFile(buffer); + } + } + + public static ArrayList getUserSyntaxData() { + return userdefsyntaxdata; + } + +// private static File getSyntaxFile() { +// IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); +// path = path.append(PHPSYNTAX_FILE); +// return path.toFile(); +// } + + private static String getAttributeValue(NamedNodeMap attributes, String name) { + Node node = attributes.getNamedItem(name); + return node == null ? null : node.getNodeValue(); + } + + public static void saveToFile(File file) throws CoreException { + OutputStream stream = null; + try { + stream = new FileOutputStream(file); + saveToStream(stream); + } catch (IOException e) { + throwWriteException(e); + } finally { + try { + if (stream != null) + stream.close(); + } catch (IOException e) { + } + } + } + + public static void saveToStream(OutputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ + // //$NON-NLS-1$ + document.appendChild(root); + for (int i = 0; i != syntaxdata.size(); i++) { + Object bufferobj = (Object) syntaxdata.get(i); + Attr name = null; + Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ + // //$NON-NLS-1$ + root.appendChild(node); + NamedNodeMap attributes = node.getAttributes(); + if (bufferobj instanceof PHPType) + name = document.createAttribute(TYPE_ATTR); + if (bufferobj instanceof PHPKeyword) + name = document.createAttribute(KEYWORD_ATTR); + if (bufferobj instanceof PHPFunction) + name = document.createAttribute(FN_ATTR); + if (bufferobj instanceof PHPConstant) + name = document.createAttribute(CONSTANT_ATTR); + name.setValue(((PHPElement) bufferobj).getName()); + attributes.setNamedItem(name); + Attr description = document.createAttribute(USAGE_ATTR); + description.setValue(((PHPElement) bufferobj).getUsage()); + attributes.setNamedItem(description); + // if (bufferobj instanceof PHPKeyword) { + // Attr tokenval = document.createAttribute(TOKENVAL_ATTR); + // tokenval.setValue((new Integer(((PHPKeyword) + // bufferobj).gettokenval())).toString()); + // attributes.setNamedItem(tokenval); + // } + if (bufferobj instanceof PHPFunction) { + // Attr usage = document.createAttribute(USAGE_ATTR); + Text usage = document + .createTextNode(((PHPFunction) bufferobj) + .getDescription()); + node.appendChild(usage); + } + if (bufferobj instanceof PHPConstant) { + // Attr usage = document.createAttribute(USAGE_ATTR); + Text usage = document + .createTextNode(((PHPConstant) bufferobj) + .getDescription()); + node.appendChild(usage); + } + } + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$ + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(stream); + + transformer.transform(source, result); + + } catch (ParserConfigurationException e) { + throwWriteException(e); + } catch (TransformerException e) { + throwWriteException(e); + } + // OutputFormat format = new OutputFormat(); + // format.setPreserveSpace(true); + // try { + // Serializer serializer = + // SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, + // format); + // serializer.asDOMSerializer().serialize(document); + // } catch (UnsupportedEncodingException e) { + // } catch (IOException e) { + // } //$NON-NLS-1$ + // // Serializer serializer = + // SerializerFactory.getSerializer().makeSerializer(stream, format); + // //$NON-NLS-1$ + // } catch (ParserConfigurationException e) { + // throwWriteException(e); + // } + } + + private static void throwReadException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + } + + private static void throwWriteException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java new file mode 100644 index 0000000..dac1795 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java @@ -0,0 +1,151 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import net.sourceforge.phpdt.internal.corext.phpdoc.PHPDocUtil; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; +import net.sourceforge.phpeclipse.builder.PHPIdentifierLocation; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; +import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; + +import org.eclipse.core.resources.IProject; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextHover; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.swt.graphics.Point; + +/** + * Implementation for an ITextHover which hovers over PHP code. + */ +public class PHPTextHover implements ITextHover { + private static HashMap functionDescriptions = null; + + private static HashMap identDescriptions = null; + + /** + * The current project; maybe null for preference pages + */ + private IProject fProject; + + public PHPTextHover(IProject project) { + fProject = project; + } + + /* + * (non-Javadoc) Method declared on ITextHover + */ + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + if (hoverRegion != null) { + try { + if (hoverRegion.getLength() > -1) { + String word = textViewer.getDocument().get( + hoverRegion.getOffset(), hoverRegion.getLength()); + if (functionDescriptions == null) { + functionDescriptions = new HashMap(); + identDescriptions = new HashMap(); + ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData(); + PHPElement elbuffer = null; + if (syntaxbuffer != null) { + for (int i = 0; i < syntaxbuffer.size(); i++) { + elbuffer = (PHPElement) syntaxbuffer.get(i); + if (elbuffer instanceof PHPFunction) { + functionDescriptions.put( + elbuffer.getName(), elbuffer + .getHoverText()); + } else { + identDescriptions.put(elbuffer.getName(), + elbuffer.getHoverText()); + } + } + } + // + // while ((syntaxbuffer != null) + // && (!syntaxbuffer.isEmpty() && ((elbuffer = + // (PHPElement) + // syntaxbuffer.remove(0)) != null))) { + // functionDescriptions.put(elbuffer.getName(), + // elbuffer.getHoverText()); + // } + } + String hoverInfo = (String) identDescriptions.get(word); + if (hoverInfo == null & word.length() > 0) { + hoverInfo = (String) functionDescriptions.get(word + .toLowerCase()); + } + if (hoverInfo == null && fProject != null) { + // get the possible PHPDoc information from the index + // file + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(fProject); + List list = indexManager.getLocations(word); + if (list.size() > 0) { + try { + PHPIdentifierLocation location; + String filename; + StringBuffer hoverInfoBuffer = new StringBuffer(); + String workspaceLocation; + if (fProject != null) { + workspaceLocation = fProject.getLocation() + .toString() + '/'; + } else { + // should never happen? + workspaceLocation = PHPeclipsePlugin + .getWorkspace().getRoot() + .getLocation().toString(); + } + // boolean foundPHPdoc = false; + for (int i = 0; i < list.size(); i++) { + location = (PHPIdentifierLocation) list + .get(i); + filename = workspaceLocation + + location.getFilename(); + PHPDocUtil.appendPHPDoc(hoverInfoBuffer, + filename, location); + } + hoverInfo = hoverInfoBuffer.toString(); + } catch (Throwable e) { + // ignore exceptions + e.printStackTrace(); + } + } + } + return hoverInfo; + } + // } catch (BadLocationException x) { + } catch (Exception x) { + } + } + return null; + // don't show this annoying text + // return "empty selection"; + } + + /* + * (non-Javadoc) Method declared on ITextHover + */ + public IRegion getHoverRegion(ITextViewer textViewer, int offset) { + Point selection = PHPWordExtractor.findWord(textViewer.getDocument(), + offset); + // show the extracted word as a tooltip + if (selection != null && selection.x <= offset + && offset < selection.x + selection.y) + return new Region(selection.x, selection.y); + return new Region(offset, 0); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java new file mode 100644 index 0000000..f56b6d9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java @@ -0,0 +1,2780 @@ +package net.sourceforge.phpeclipse.phpeditor; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaProject; +import net.sourceforge.phpdt.core.IMember; +import net.sourceforge.phpdt.core.ISourceRange; +import net.sourceforge.phpdt.core.ISourceReference; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.dom.CompilationUnit; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +import net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction; +import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; +import net.sourceforge.phpdt.internal.ui.actions.IndentAction; +import net.sourceforge.phpdt.internal.ui.actions.RemoveBlockCommentAction; +import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner; +import net.sourceforge.phpdt.internal.ui.text.JavaIndenter; +//import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher; +import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager; +import net.sourceforge.phpdt.internal.ui.text.SmartSemicolonAutoEditStrategy; +import net.sourceforge.phpdt.internal.ui.text.comment.CommentFormattingContext; +import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; +import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.actions.GenerateActionGroup; +//import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.actions.RTrimAction; +import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Preferences; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.dialogs.ErrorDialog; +import org.eclipse.jface.dialogs.IMessageProvider; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +//import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.DocumentCommand; +import org.eclipse.jface.text.IAutoEditStrategy; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ILineTracker; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextOperationTarget; +import org.eclipse.jface.text.ITextViewerExtension; +import org.eclipse.jface.text.ITypedRegion; +import org.eclipse.jface.text.IWidgetTokenKeeper; +import org.eclipse.jface.text.contentassist.ContentAssistant; +import org.eclipse.jface.text.contentassist.IContentAssistant; +import org.eclipse.jface.text.formatter.FormattingContextProperties; +import org.eclipse.jface.text.formatter.IFormattingContext; +import org.eclipse.jface.text.source.IOverviewRuler; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.jface.text.source.IVerticalRuler; +import org.eclipse.jface.text.source.SourceViewerConfiguration; +//incastrix +//import org.eclipse.jface.util.ListenerList; +import org.eclipse.core.runtime.ListenerList; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.VerifyKeyListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Point; +//import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.actions.ActionContext; +import org.eclipse.ui.actions.ActionGroup; +import org.eclipse.ui.dialogs.SaveAsDialog; +import org.eclipse.ui.editors.text.IStorageDocumentProvider; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; +import org.eclipse.ui.texteditor.ContentAssistAction; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditorActionConstants; +import org.eclipse.ui.texteditor.TextOperationAction; + +/******************************************************************************* + * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This + * program and the accompanying materials are made available under the terms of + * the Common Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: IBM Corporation - Initial implementation + * www.phpeclipse.de + ******************************************************************************/ +/** + * PHP specific text editor. + */ +public class PHPUnitEditor extends PHPEditor { // implements + // IJavaReconcilingListener { + interface ITextConverter { + void customizeDocumentCommand(IDocument document, + DocumentCommand command); + }; + + // class AdaptedSourceViewer extends JavaSourceViewer { + // private List fTextConverters; + // + // private boolean fIgnoreTextConverters = false; + // + // // private JavaCorrectionAssistant fCorrectionAssistant; + // public AdaptedSourceViewer(Composite parent, IVerticalRuler + // verticalRuler, + // IOverviewRuler overviewRuler, boolean showAnnotationsOverview, + // int styles, IPreferenceStore store) { + // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, + // styles, store); + // } + // + // // public AdaptedSourceViewer(Composite parent, + // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + // // boolean showAnnotationsOverview, int styles) { + // // super(parent, verticalRuler, overviewRuler, + // // showAnnotationsOverview, styles); + // // } + // public IContentAssistant getContentAssistant() { + // return fContentAssistant; + // } + // + // /* + // * @see ITextOperationTarget#doOperation(int) + // */ + // public void doOperation(int operation) { + // if (getTextWidget() == null) + // return; + // switch (operation) { + // case CONTENTASSIST_PROPOSALS: + // String msg = fContentAssistant.showPossibleCompletions(); + // setStatusLineErrorMessage(msg); + // return; + // // case CORRECTIONASSIST_PROPOSALS: + // // fCorrectionAssistant.showPossibleCompletions(); + // // return; + // case UNDO: + // fIgnoreTextConverters = true; + // break; + // case REDO: + // fIgnoreTextConverters = true; + // break; + // } + // super.doOperation(operation); + // } + // + // /* + // * @see ITextOperationTarget#canDoOperation(int) + // */ + // public boolean canDoOperation(int operation) { + // // if (operation == CORRECTIONASSIST_PROPOSALS) + // // return isEditable(); + // return super.canDoOperation(operation); + // } + // + // /* + // * @see TextViewer#handleDispose() + // */ + // protected void handleDispose() { + // // if (fCorrectionAssistant != null) { + // // fCorrectionAssistant.uninstall(); + // // fCorrectionAssistant= null; + // // } + // super.handleDispose(); + // } + // + // public void insertTextConverter(ITextConverter textConverter, int index) + // { + // throw new UnsupportedOperationException(); + // } + // + // public void addTextConverter(ITextConverter textConverter) { + // if (fTextConverters == null) { + // fTextConverters = new ArrayList(1); + // fTextConverters.add(textConverter); + // } else if (!fTextConverters.contains(textConverter)) + // fTextConverters.add(textConverter); + // } + // + // public void removeTextConverter(ITextConverter textConverter) { + // if (fTextConverters != null) { + // fTextConverters.remove(textConverter); + // if (fTextConverters.size() == 0) + // fTextConverters = null; + // } + // } + // + // /* + // * @see TextViewer#customizeDocumentCommand(DocumentCommand) + // */ + // protected void customizeDocumentCommand(DocumentCommand command) { + // super.customizeDocumentCommand(command); + // if (!fIgnoreTextConverters && fTextConverters != null) { + // for (Iterator e = fTextConverters.iterator(); e.hasNext();) + // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), + // command); + // } + // fIgnoreTextConverters = false; + // } + // + // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + // public void updateIndentationPrefixes() { + // SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + // String[] types = configuration.getConfiguredContentTypes(this); + // for (int i = 0; i < types.length; i++) { + // String[] prefixes = configuration.getIndentPrefixes(this, types[i]); + // if (prefixes != null && prefixes.length > 0) + // setIndentPrefixes(prefixes, types[i]); + // } + // } + // + // /* + // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) + // */ + // public boolean requestWidgetToken(IWidgetTokenKeeper requester) { + // if (WorkbenchHelp.isContextHelpDisplayed()) + // return false; + // return super.requestWidgetToken(requester); + // } + // + // // /* + // // * @see + // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) + // // */ + // // public void configure(SourceViewerConfiguration configuration) { + // // super.configure(configuration); + // // // fCorrectionAssistant= new + // // // JavaCorrectionAssistant(CompilationUnitEditor.this); + // // // fCorrectionAssistant.install(this); + // // //TODO install SmartBracesAutoEditStrategy + // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), + // // // IDocument.DEFAULT_CONTENT_TYPE); + // // } + // public void configure(SourceViewerConfiguration configuration) { + // super.configure(configuration); + // // fCorrectionAssistant= new + // JavaCorrectionAssistant(CompilationUnitEditor.this); + // // fCorrectionAssistant.install(this); + // IAutoEditStrategy smartSemi= new + // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING); + // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); + // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); + // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); + // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER); + // } + // }; + class AdaptedSourceViewer extends JavaSourceViewer { + + private List fTextConverters; + + private boolean fIgnoreTextConverters = false; + + // private JavaCorrectionAssistant fCorrectionAssistant; + + public AdaptedSourceViewer(Composite parent, + IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + boolean showAnnotationsOverview, int styles, + IPreferenceStore store) { + super(parent, verticalRuler, overviewRuler, + showAnnotationsOverview, styles, store); + } + + public IContentAssistant getContentAssistant() { + return fContentAssistant; + } + + /* + * @see ITextOperationTarget#doOperation(int) + */ + public void doOperation(int operation) { + + if (getTextWidget() == null) + return; + + switch (operation) { + case CONTENTASSIST_PROPOSALS: + String msg = fContentAssistant.showPossibleCompletions(); + setStatusLineErrorMessage(msg); + return; + // case CORRECTIONASSIST_PROPOSALS: + // msg = fCorrectionAssistant.showPossibleCompletions(); + // setStatusLineErrorMessage(msg); + // return; + case UNDO: + fIgnoreTextConverters = true; + super.doOperation(operation); + fIgnoreTextConverters = false; + return; + case REDO: + fIgnoreTextConverters = true; + super.doOperation(operation); + fIgnoreTextConverters = false; + return; + } + + super.doOperation(operation); + } + + /* + * @see ITextOperationTarget#canDoOperation(int) + */ + public boolean canDoOperation(int operation) { + // if (operation == CORRECTIONASSIST_PROPOSALS) + // return isEditable(); + + return super.canDoOperation(operation); + } + + /* + * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure() + * @since 3.0 + */ + public void unconfigure() { + // if (fCorrectionAssistant != null) { + // fCorrectionAssistant.uninstall(); + // fCorrectionAssistant = null; + // } + super.unconfigure(); + } + + public void insertTextConverter(ITextConverter textConverter, int index) { + throw new UnsupportedOperationException(); + } + + public void addTextConverter(ITextConverter textConverter) { + if (fTextConverters == null) { + fTextConverters = new ArrayList(1); + fTextConverters.add(textConverter); + } else if (!fTextConverters.contains(textConverter)) + fTextConverters.add(textConverter); + } + + public void removeTextConverter(ITextConverter textConverter) { + if (fTextConverters != null) { + fTextConverters.remove(textConverter); + if (fTextConverters.size() == 0) + fTextConverters = null; + } + } + + /* + * @see TextViewer#customizeDocumentCommand(DocumentCommand) + */ + protected void customizeDocumentCommand(DocumentCommand command) { + super.customizeDocumentCommand(command); + if (!fIgnoreTextConverters && fTextConverters != null) { + for (Iterator e = fTextConverters.iterator(); e.hasNext();) + ((ITextConverter) e.next()).customizeDocumentCommand( + getDocument(), command); + } + } + + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + public void updateIndentationPrefixes() { + SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + String[] types = configuration.getConfiguredContentTypes(this); + for (int i = 0; i < types.length; i++) { + String[] prefixes = configuration.getIndentPrefixes(this, + types[i]); + if (prefixes != null && prefixes.length > 0) + setIndentPrefixes(prefixes, types[i]); + } + } + + /* + * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) + */ + public boolean requestWidgetToken(IWidgetTokenKeeper requester) { + if (PlatformUI.getWorkbench().getHelpSystem() + .isContextHelpDisplayed()) + return false; + return super.requestWidgetToken(requester); + } + + /* + * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, + * int) + * @since 3.0 + */ + public boolean requestWidgetToken(IWidgetTokenKeeper requester, + int priority) { + if (PlatformUI.getWorkbench().getHelpSystem() + .isContextHelpDisplayed()) + return false; + return super.requestWidgetToken(requester, priority); + } + + /* + * Get the global 'Undo history size' setting + * + */ + protected int getUndoHistorySize () { + IPreferenceStore store= getPreferenceStore (); + + return store != null ? store.getInt("undoHistorySize") : 1000; + } + + + /* + * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) + */ + public void configure(SourceViewerConfiguration configuration) { + super.configure(configuration); + // fCorrectionAssistant = new + // JavaCorrectionAssistant(CompilationUnitEditor.this); + // fCorrectionAssistant.install(this); + IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy( + IPHPPartitions.PHP_PARTITIONING); + prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); + prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ); + prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ); + prependAutoEditStrategy(smartSemi, + IPHPPartitions.PHP_STRING_HEREDOC); + + fUndoManager.setMaximalUndoLevel (this.getUndoHistorySize ()); // Set every editor to the global 'Undo history size' + } + + /* + * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext() + * @since 3.0 + */ + public IFormattingContext createFormattingContext() { + IFormattingContext context = new CommentFormattingContext(); + + Map preferences; + IJavaElement inputJavaElement = getInputJavaElement(); + IJavaProject javaProject = inputJavaElement != null ? inputJavaElement + .getJavaProject() + : null; + if (javaProject == null) + preferences = new HashMap(JavaCore.getOptions()); + else + preferences = new HashMap(javaProject.getOptions(true)); + + context.storeToMap(PreferenceConstants.getPreferenceStore(), + preferences, false); + context.setProperty( + FormattingContextProperties.CONTEXT_PREFERENCES, + preferences); + + return context; + } + } + + /** + * Remembers data related to the current selection to be able to restore it + * later. + * + * @since 3.0 + */ + private class RememberedSelection { + /** The remembered selection start. */ + private RememberedOffset fStartOffset = new RememberedOffset(); + + /** The remembered selection end. */ + private RememberedOffset fEndOffset = new RememberedOffset(); + + /** + * Remember current selection. + */ + public void remember() { + /* + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method + * may be called inside an async call posted to the UI thread, so + * protect against intermediate disposal of the editor. + */ + ISourceViewer viewer = getSourceViewer(); + if (viewer != null) { + IRegion selection = getSignedSelection(viewer); + int startOffset = selection.getOffset(); + int endOffset = startOffset + selection.getLength(); + + fStartOffset.setOffset(startOffset); + fEndOffset.setOffset(endOffset); + } + } + + /** + * Restore remembered selection. + */ + public void restore() { + /* + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method + * may be called inside an async call posted to the UI thread, so + * protect against intermediate disposal of the editor. + */ + if (getSourceViewer() == null) + return; + + try { + + int startOffset, endOffset; + int revealStartOffset, revealEndOffset; + if (showsHighlightRangeOnly()) { + IJavaElement newStartElement = fStartOffset.getElement(); + startOffset = fStartOffset + .getRememberedOffset(newStartElement); + revealStartOffset = fStartOffset.getRevealOffset( + newStartElement, startOffset); + if (revealStartOffset == -1) + startOffset = -1; + + IJavaElement newEndElement = fEndOffset.getElement(); + endOffset = fEndOffset.getRememberedOffset(newEndElement); + revealEndOffset = fEndOffset.getRevealOffset(newEndElement, + endOffset); + if (revealEndOffset == -1) + endOffset = -1; + } else { + startOffset = fStartOffset.getOffset(); + revealStartOffset = startOffset; + endOffset = fEndOffset.getOffset(); + revealEndOffset = endOffset; + } + + if (startOffset == -1) { + startOffset = endOffset; // fallback to caret offset + revealStartOffset = revealEndOffset; + } + + if (endOffset == -1) { + endOffset = startOffset; // fallback to other offset + revealEndOffset = revealStartOffset; + } + + IJavaElement element; + if (endOffset == -1) { + // fallback to element selection + element = fEndOffset.getElement(); + if (element == null) + element = fStartOffset.getElement(); + if (element != null) + setSelection(element); + return; + } + + if (isValidSelection(revealStartOffset, revealEndOffset + - revealStartOffset) + && isValidSelection(startOffset, endOffset + - startOffset)) + selectAndReveal(startOffset, endOffset - startOffset, + revealStartOffset, revealEndOffset + - revealStartOffset); + } finally { + fStartOffset.clear(); + fEndOffset.clear(); + } + } + + private boolean isValidSelection(int offset, int length) { + IDocumentProvider provider = getDocumentProvider(); + if (provider != null) { + IDocument document = provider.getDocument(getEditorInput()); + if (document != null) { + int end = offset + length; + int documentLength = document.getLength(); + return 0 <= offset && offset <= documentLength && 0 <= end + && end <= documentLength; + } + } + return false; + } + + } + + /** + * Remembers additional data for a given offset to be able restore it later. + * + * @since 3.0 + */ + private class RememberedOffset { + /** Remembered line for the given offset */ + private int fLine; + + /** Remembered column for the given offset */ + private int fColumn; + + /** Remembered Java element for the given offset */ + private IJavaElement fElement; + + /** Remembered Java element line for the given offset */ + private int fElementLine; + + /** + * Store visual properties of the given offset. + * + * @param offset + * Offset in the document + */ + public void setOffset(int offset) { + try { + IDocument document = getSourceViewer().getDocument(); + fLine = document.getLineOfOffset(offset); + fColumn = offset - document.getLineOffset(fLine); + fElement = getElementAt(offset, true); + + fElementLine = -1; + if (fElement instanceof IMember) { + ISourceRange range = ((IMember) fElement).getNameRange(); + if (range != null) + fElementLine = document.getLineOfOffset(range + .getOffset()); + } + if (fElementLine == -1) + fElementLine = document + .getLineOfOffset(getOffset(fElement)); + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + clear(); + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + clear(); + } + } + + /** + * Return offset recomputed from stored visual properties. + * + * @return Offset in the document + */ + public int getOffset() { + IJavaElement newElement = getElement(); + + int offset = getRememberedOffset(newElement); + + if (offset != -1 && !containsOffset(newElement, offset) + && (offset == 0 || !containsOffset(newElement, offset - 1))) + return -1; + + return offset; + } + + /** + * Return offset recomputed from stored visual properties. + * + * @param newElement + * Enclosing element + * @return Offset in the document + */ + public int getRememberedOffset(IJavaElement newElement) { + try { + if (newElement == null) + return -1; + + IDocument document = getSourceViewer().getDocument(); + int newElementLine = -1; + if (newElement instanceof IMember) { + ISourceRange range = ((IMember) newElement).getNameRange(); + if (range != null) + newElementLine = document.getLineOfOffset(range + .getOffset()); + } + if (newElementLine == -1) + newElementLine = document + .getLineOfOffset(getOffset(newElement)); + if (newElementLine == -1) + return -1; + + int newLine = fLine + newElementLine - fElementLine; + if (newLine < 0 || newLine >= document.getNumberOfLines()) + return -1; + int maxColumn = document.getLineLength(newLine); + String lineDelimiter = document.getLineDelimiter(newLine); + if (lineDelimiter != null) + maxColumn = maxColumn - lineDelimiter.length(); + int offset; + if (fColumn > maxColumn) + offset = document.getLineOffset(newLine) + maxColumn; + else + offset = document.getLineOffset(newLine) + fColumn; + + return offset; + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + return -1; + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + return -1; + } + } + + /** + * Returns the offset used to reveal the given element based on the + * given selection offset. + * + * @param element + * the element + * @param offset + * the selection offset + * @return the offset to reveal the given element based on the given + * selection offset + */ + public int getRevealOffset(IJavaElement element, int offset) { + if (element == null || offset == -1) + return -1; + + if (containsOffset(element, offset)) { + if (offset > 0) { + IJavaElement alternateElement = getElementAt(offset, false); + if (element.getHandleIdentifier().equals( + alternateElement.getParent().getHandleIdentifier())) + return offset - 1; // Solves test case 2 from + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + } + return offset; + } else if (offset > 0 && containsOffset(element, offset - 1)) + return offset - 1; // Solves test case 1 from + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + + return -1; + } + + /** + * Return Java element recomputed from stored visual properties. + * + * @return Java element + */ + public IJavaElement getElement() { + if (fElement == null) + return null; + + return findElement(fElement); + } + + /** + * Clears the stored position + */ + public void clear() { + fLine = -1; + fColumn = -1; + fElement = null; + fElementLine = -1; + } + + /** + * Does the given Java element contain the given offset? + * + * @param element + * Java element + * @param offset + * Offset + * @return true iff the Java element contains the offset + */ + private boolean containsOffset(IJavaElement element, int offset) { + int elementOffset = getOffset(element); + int elementLength = getLength(element); + return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + + elementLength) + : false; + } + + /** + * Returns the offset of the given Java element. + * + * @param element + * Java element + * @return Offset of the given Java element + */ + private int getOffset(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr = (ISourceReference) element; + try { + ISourceRange srcRange = sr.getSourceRange(); + if (srcRange != null) + return srcRange.getOffset(); + } catch (JavaModelException e) { + } + } + return -1; + } + + /** + * Returns the length of the given Java element. + * + * @param element + * Java element + * @return Length of the given Java element + */ + private int getLength(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr = (ISourceReference) element; + try { + ISourceRange srcRange = sr.getSourceRange(); + if (srcRange != null) + return srcRange.getLength(); + } catch (JavaModelException e) { + } + } + return -1; + } + + /** + * Returns the updated java element for the old java element. + * + * @param element + * Old Java element + * @return Updated Java element + */ + private IJavaElement findElement(IJavaElement element) { + + if (element == null) + return null; + + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + + if (unit != null) { + try { + + synchronized (unit) { + // unit.reconcile(ICompilationUnit.NO_AST, false, null, + // null); + unit.reconcile(); + } + IJavaElement[] findings = unit.findElements(element); + if (findings != null && findings.length > 0) + return findings[0]; + + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + } + + return null; + } + + } + + static class TabConverter implements ITextConverter { + private int fTabRatio; + + private ILineTracker fLineTracker; + + public TabConverter() { + } + + public void setNumberOfSpacesPerTab(int ratio) { + fTabRatio = ratio; + } + + public void setLineTracker(ILineTracker lineTracker) { + fLineTracker = lineTracker; + } + + private int insertTabString(StringBuffer buffer, int offsetInLine) { + if (fTabRatio == 0) + return 0; + int remainder = offsetInLine % fTabRatio; + remainder = fTabRatio - remainder; + for (int i = 0; i < remainder; i++) + buffer.append(' '); + return remainder; + } + + public void customizeDocumentCommand(IDocument document, + DocumentCommand command) { + String text = command.text; + if (text == null) + return; + int index = text.indexOf('\t'); + if (index > -1) { + StringBuffer buffer = new StringBuffer(); + fLineTracker.set(command.text); + int lines = fLineTracker.getNumberOfLines(); + try { + for (int i = 0; i < lines; i++) { + int offset = fLineTracker.getLineOffset(i); + int endOffset = offset + fLineTracker.getLineLength(i); + String line = text.substring(offset, endOffset); + int position = 0; + if (i == 0) { + IRegion firstLine = document + .getLineInformationOfOffset(command.offset); + position = command.offset - firstLine.getOffset(); + } + int length = line.length(); + for (int j = 0; j < length; j++) { + char c = line.charAt(j); + if (c == '\t') { + position += insertTabString(buffer, position); + } else { + buffer.append(c); + ++position; + } + } + } + command.text = buffer.toString(); + } catch (BadLocationException x) { + } + } + } + }; + + private static class ExitPolicy implements LinkedPositionUI.ExitPolicy { + final char fExitCharacter; + + public ExitPolicy(char exitCharacter) { + fExitCharacter = exitCharacter; + } + + /* + * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager, + * org.eclipse.swt.events.VerifyEvent, int, int) + */ + public ExitFlags doExit(LinkedPositionManager manager, + VerifyEvent event, int offset, int length) { + if (event.character == fExitCharacter) { + if (manager.anyPositionIncludes(offset, length)) + return new ExitFlags(LinkedPositionUI.COMMIT + | LinkedPositionUI.UPDATE_CARET, false); + else + return new ExitFlags(LinkedPositionUI.COMMIT, true); + } + // Fix for #1380415 (toshihiro) start + switch (event.keyCode) { + case SWT.ARROW_UP: + case SWT.ARROW_DOWN: + return new ExitFlags(LinkedPositionUI.COMMIT, true); + case SWT.ARROW_LEFT: + case SWT.ARROW_RIGHT: + if (!manager.anyPositionIncludes(offset, length)) + return new ExitFlags(LinkedPositionUI.COMMIT, true); + break; + } + // #1380415 end + switch (event.character) { + case '\b': + if (manager.getFirstPosition().length == 0) + return new ExitFlags(0, false); + else + return null; + case '\n': + case '\r': + return new ExitFlags(LinkedPositionUI.COMMIT, true); + default: + return null; + } + } + } + +// private static class BracketLevel { +// int fOffset; +// +// int fLength; +// +// LinkedPositionManager fManager; +// +// LinkedPositionUI fEditor; +// }; + + private class BracketInserter implements VerifyKeyListener, + LinkedPositionUI.ExitListener { + private boolean fCloseBracketsPHP = true; + + private boolean fCloseStringsPHPDQ = true; + + private boolean fCloseStringsPHPSQ = true; + + private int fOffset; + + private int fLength; + + public void setCloseBracketsPHPEnabled(boolean enabled) { + fCloseBracketsPHP = enabled; + } + + public void setCloseStringsPHPDQEnabled(boolean enabled) { + fCloseStringsPHPDQ = enabled; + } + + public void setCloseStringsPHPSQEnabled(boolean enabled) { + fCloseStringsPHPSQ = enabled; + } + + private boolean hasIdentifierToTheRight(IDocument document, int offset) { + try { + int end = offset; + IRegion endLine = document.getLineInformationOfOffset(end); + int maxEnd = endLine.getOffset() + endLine.getLength(); + while (end != maxEnd + && Character.isWhitespace(document.getChar(end))) + ++end; + return end != maxEnd + && Scanner.isPHPIdentifierPart(document.getChar(end)); + } catch (BadLocationException e) { + // be conservative + return true; + } + } + +// private boolean hasIdentifierToTheLeft(IDocument document, int offset) { +// try { +// int start = offset; +// IRegion startLine = document.getLineInformationOfOffset(start); +// int minStart = startLine.getOffset(); +// while (start != minStart +// && Character.isWhitespace(document.getChar(start - 1))) +// --start; +// return start != minStart +// && Scanner.isPHPIdentifierPart(document +// .getChar(start - 1)); +// } catch (BadLocationException e) { +// return true; +// } +// } + + private boolean hasCharacterToTheLeft(IDocument document, int offset, + char character) { + try { + int start = offset; + IRegion startLine = document.getLineInformationOfOffset(start); + int minStart = startLine.getOffset(); + while (start != minStart + && Character.isWhitespace(document.getChar(start - 1))) + --start; + return start != minStart + && document.getChar(start - 1) == character; + } catch (BadLocationException e) { + return false; + } + } + + private boolean hasCharacterToTheRight(IDocument document, int offset, + char character) { + try { + int end = offset; + IRegion endLine = document.getLineInformationOfOffset(end); + int maxEnd = endLine.getOffset() + endLine.getLength(); + while (end != maxEnd + && Character.isWhitespace(document.getChar(end))) + ++end; + return end != maxEnd && document.getChar(end) == character; + } catch (BadLocationException e) { + // be conservative + return true; + } + } + + /* + * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) + */ + public void verifyKey(VerifyEvent event) { + if (!event.doit) + return; + final ISourceViewer sourceViewer = getSourceViewer(); + IDocument document = sourceViewer.getDocument(); + final Point selection = sourceViewer.getSelectedRange(); + final int offset = selection.x; + final int length = selection.y; + try { + ITypedRegion partition = document.getPartition(offset); + String type = partition.getType(); + if (type.equals(IPHPPartitions.PHP_PARTITIONING) + || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) { + // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP + // and HTML area + switch (event.character) { + case '(': + if (hasCharacterToTheRight(document, offset + length, + '(')) + return; + // fall through + case '[': + if (!fCloseBracketsPHP) + return; + if (hasIdentifierToTheRight(document, offset + length)) + return; + // fall through + case '{': + if (!fCloseBracketsPHP) + return; + if (hasIdentifierToTheRight(document, offset + length)) + return; + // fall through + case '"': + if (event.character == '"') { + if (!fCloseStringsPHPDQ) + return; + // changed for statements like echo "" print "" + // if (hasIdentifierToTheLeft(document, offset) + // || + // hasIdentifierToTheRight(document, offset + + // length)) + if (hasIdentifierToTheRight(document, offset + + length)) + return; + } + // ITypedRegion partition= + // document.getPartition(offset); + // if (! + // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) + // && + // (partition.getOffset() != offset)) + // return; + final char characterDQ = event.character; + final char closingCharacterDQ = getPeerCharacter(characterDQ); + final StringBuffer bufferDQ = new StringBuffer(); + bufferDQ.append(characterDQ); + bufferDQ.append(closingCharacterDQ); + document.replace(offset, length, bufferDQ.toString()); + LinkedPositionManager managerDQ = new LinkedPositionManager( + document); + managerDQ.addPosition(offset + 1, 0); + fOffset = offset; + fLength = 2; + LinkedPositionUI editorDQ = new LinkedPositionUI( + sourceViewer, managerDQ); + editorDQ.setCancelListener(this); + editorDQ.setExitPolicy(new ExitPolicy( + closingCharacterDQ)); + editorDQ.setFinalCaretOffset(offset + 2); + editorDQ.enter(); + IRegion newSelectionDQ = editorDQ.getSelectedRegion(); + sourceViewer.setSelectedRange(newSelectionDQ + .getOffset(), newSelectionDQ.getLength()); + event.doit = false; + break; + case '\'': + if (event.character == '\'') { + if (!fCloseStringsPHPSQ) + return; + // changed for statements like echo "" print "" + // if (hasIdentifierToTheLeft(document, offset) + // || + // hasIdentifierToTheRight(document, offset + + // length)) + if (hasIdentifierToTheRight(document, offset + + length)) + return; + } + // ITypedRegion partition= + // document.getPartition(offset); + // if (! + // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) + // && + // (partition.getOffset() != offset)) + // return; + final char characterSQ = event.character; + final char closingCharacterSQ = getPeerCharacter(characterSQ); + final StringBuffer bufferSQ = new StringBuffer(); + bufferSQ.append(characterSQ); + bufferSQ.append(closingCharacterSQ); + document.replace(offset, length, bufferSQ.toString()); + LinkedPositionManager managerSQ = new LinkedPositionManager( + document); + managerSQ.addPosition(offset + 1, 0); + fOffset = offset; + fLength = 2; + LinkedPositionUI editorSQ = new LinkedPositionUI( + sourceViewer, managerSQ); + editorSQ.setCancelListener(this); + editorSQ.setExitPolicy(new ExitPolicy( + closingCharacterSQ)); + editorSQ.setFinalCaretOffset(offset + 2); + editorSQ.enter(); + IRegion newSelectionSQ = editorSQ.getSelectedRegion(); + sourceViewer.setSelectedRange(newSelectionSQ + .getOffset(), newSelectionSQ.getLength()); + event.doit = false; + case '\r': { // insert linebreaks and new closing brace + // after brace and return + if (!fCloseBracketsPHP) { + return; + } + if (hasCharacterToTheLeft(document, offset, '{') + && hasCharacterToTheRight(document, offset, '}')) { + String lineDelimiter = StubUtility + .getLineDelimiterFor(document); + int caretPos = sourceViewer.getTextWidget() + .getCaretOffset(); + final StringBuffer buffer = new StringBuffer( + lineDelimiter); + // get indentation + IRegion line = document + .getLineInformationOfOffset(offset); + String currentLine = document.get(line.getOffset(), + line.getLength()); + int index = 0; + int max = currentLine.length(); + StringBuffer indent = new StringBuffer(); + while (index < max + && Character.isWhitespace(currentLine + .charAt(index))) { + indent.append(currentLine.charAt(index)); + index++; + } + buffer.append(indent); + JavaHeuristicScanner scanner = new JavaHeuristicScanner( + document); + JavaIndenter indenter = new JavaIndenter(document, + scanner); + buffer.append(indenter.createIndent(1)); + int cursorPos = buffer.length(); + buffer.append(lineDelimiter); + buffer.append(indent); + document.replace(offset, length, buffer.toString()); + sourceViewer.getTextWidget().setCaretOffset( + caretPos + cursorPos); + event.doit = false; + } + } + } + } + } catch (BadLocationException e) { + } + } + + /* + * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) + */ + public void exit(boolean accept) { + if (accept) + return; + // remove brackets + try { + final ISourceViewer sourceViewer = getSourceViewer(); + IDocument document = sourceViewer.getDocument(); + document.replace(fOffset, fLength, null); + } catch (BadLocationException e) { + } + } + } + + /** The editor's save policy */ + protected ISavePolicy fSavePolicy; + + /** + * Listener to annotation model changes that updates the error tick in the + * tab image + */ + private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; + + /** The editor's paint manager */ + // private PaintManager fPaintManager; + /** The editor's bracket painter */ + // private BracketPainter fBracketPainter; + /** The editor's bracket matcher */ + //private PHPPairMatcher fBracketMatcher; + + /** The editor's line painter */ + // private LinePainter fLinePainter; + /** The editor's print margin ruler painter */ + // private PrintMarginPainter fPrintMarginPainter; + /** The editor's problem painter */ + // private ProblemPainter fProblemPainter; + /** The editor's tab converter */ + private TabConverter fTabConverter; + + /** History for structure select action */ + // private SelectionHistory fSelectionHistory; + /** The preference property change listener for php core. */ + // private IPropertyChangeListener fPropertyChangeListener = new + // PropertyChangeListener(); + /** The remembered java element */ + //private IJavaElement fRememberedElement; + + /** + * The remembered selection. + * + * @since 3.0 + */ + private RememberedSelection fRememberedSelection = new RememberedSelection(); + + /** The remembered php element offset */ + //private int fRememberedElementOffset; + + /** The bracket inserter. */ + private BracketInserter fBracketInserter = new BracketInserter(); + + /** The standard action groups added to the menu */ + private GenerateActionGroup fGenerateActionGroup; + + private CompositeActionGroup fContextMenuGroup; + + // private class PropertyChangeListener implements IPropertyChangeListener { + // /* + // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + // */ + // public void + // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent + // event) { + // handlePreferencePropertyChanged(event); + // } + // } + /* Preference key for code formatter tab size */ + private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE; + + /** Preference key for matching brackets */ + // private final static String MATCHING_BRACKETS = + // PreferenceConstants.EDITOR_MATCHING_BRACKETS; + /** Preference key for matching brackets color */ + // private final static String MATCHING_BRACKETS_COLOR = + // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; + /** Preference key for highlighting current line */ + // private final static String CURRENT_LINE = + // PreferenceConstants.EDITOR_CURRENT_LINE; + /** Preference key for highlight color of current line */ + // private final static String CURRENT_LINE_COLOR = + // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; + /** Preference key for showing print marging ruler */ + // private final static String PRINT_MARGIN = + // PreferenceConstants.EDITOR_PRINT_MARGIN; + /** Preference key for print margin ruler color */ + // private final static String PRINT_MARGIN_COLOR = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; + /** Preference key for print margin ruler column */ + // private final static String PRINT_MARGIN_COLUMN = + // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; + /** Preference key for inserting spaces rather than tabs */ + private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS; + + /** Preference key for error indication */ + // private final static String ERROR_INDICATION = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION; + /** Preference key for error color */ + // private final static String ERROR_INDICATION_COLOR = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; + /** Preference key for warning indication */ + // private final static String WARNING_INDICATION = + // PreferenceConstants.EDITOR_WARNING_INDICATION; + /** Preference key for warning color */ + // private final static String WARNING_INDICATION_COLOR = + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; + /** Preference key for task indication */ + //private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; + + /** Preference key for task color */ + //private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; + + /** Preference key for bookmark indication */ + //private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; + + /** Preference key for bookmark color */ + //private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; + + /** Preference key for search result indication */ + //private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; + + /** Preference key for search result color */ + //private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; + + /** Preference key for unknown annotation indication */ + //private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; + + /** Preference key for unknown annotation color */ + //private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; + + /** Preference key for linked position color */ + //private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR; + + /** Preference key for shwoing the overview ruler */ + //private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; + + /** Preference key for error indication in overview ruler */ + //private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for warning indication in overview ruler */ + //private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for task indication in overview ruler */ + //private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for bookmark indication in overview ruler */ + //private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for search result indication in overview ruler */ + //private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for unknown annotation indication in overview ruler */ + //private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + + /** Preference key for automatically closing double quoted strings */ + private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP; + + /** Preference key for automatically closing single quoted strings */ + private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP; + + /** Preference key for automatically wrapping Java strings */ + // private final static String WRAP_STRINGS = + // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ; + /** Preference key for automatically closing brackets and parenthesis */ + private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP; + + /** Preference key for automatically closing phpdocs and comments */ + //private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS; + + /** Preference key for automatically adding phpdoc tags */ + //private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS; + + /** Preference key for automatically formatting phpdocs */ + // private final static String FORMAT_JAVADOCS = + // PreferenceConstants.EDITOR_FORMAT_JAVADOCS; + /** Preference key for automatically closing strings */ + //private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML; + + /** Preference key for automatically closing brackets and parenthesis */ + //private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML; + + /** Preference key for smart paste */ + //private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE; + + // private final static class AnnotationInfo { + // public String fColorPreference; + // public String fOverviewRulerPreference; + // public String fEditorPreference; + // }; + // private final static Map ANNOTATION_MAP; + // static { + // + // AnnotationInfo info; + // ANNOTATION_MAP = new HashMap(); + // + // info = new AnnotationInfo(); + // info.fColorPreference = TASK_INDICATION_COLOR; + // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = TASK_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.TASK, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = ERROR_INDICATION_COLOR; + // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = ERROR_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.ERROR, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = WARNING_INDICATION_COLOR; + // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = WARNING_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.WARNING, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = BOOKMARK_INDICATION_COLOR; + // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = BOOKMARK_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR; + // info.fOverviewRulerPreference = + // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = SEARCH_RESULT_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.SEARCH, info); + // + // info = new AnnotationInfo(); + // info.fColorPreference = UNKNOWN_INDICATION_COLOR; + // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + // info.fEditorPreference = UNKNOWN_INDICATION; + // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info); + // }; + // + // private final static AnnotationType[] ANNOTATION_LAYERS = + // new AnnotationType[] { + // AnnotationType.UNKNOWN, + // AnnotationType.BOOKMARK, + // AnnotationType.TASK, + // AnnotationType.SEARCH, + // AnnotationType.WARNING, + // AnnotationType.ERROR }; + /** + * Creates a new php unit editor. + */ + + /** + * Reconciling listeners. + * + * @since 3.0 + */ + private ListenerList fReconcilingListeners = new ListenerList(); + + /** + * Mutex for the reconciler. See + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of + * the problem. + *

+ * TODO remove once the underlying problem is solved. + *

+ */ + private final Object fReconcilerLock = new Object(); + + public PHPUnitEditor() { + super(); + setDocumentProvider(PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider()); + setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$ + setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$ + setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$ + // don't set help contextId, we install our own help context + fSavePolicy = null; + fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this); + } + + /* + * @see AbstractTextEditor#createActions() + */ + protected void createActions() { + super.createActions(); + Action action; + // Action action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); + // //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); + // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ + // markAsStateDependentAction("CorrectionAssistProposal", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.QUICK_FIX_ACTION); + action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(), + "ContentAssistProposal.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); + setAction("ContentAssistProposal", action); //$NON-NLS-1$ + markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.CONTENT_ASSIST_ACTION); + // action = new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "ContentAssistContextInformation.", this, + // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); + // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ + // markAsStateDependentAction("ContentAssistContextInformation", true); + // //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(), + // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); + // //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX); + // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$ + // markAsStateDependentAction("ContentAssistCompletePrefix", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.PARAMETER_HINTS_ACTION); + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT); + setAction("Comment", action); //$NON-NLS-1$ + markAsStateDependentAction("Comment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT); + setAction("Uncomment", action); //$NON-NLS-1$ + markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); + + action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(), + "ToggleComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT); + setAction("ToggleComment", action); //$NON-NLS-1$ + markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION); + configureToggleCommentAction(); + + action = new TextOperationAction(PHPEditorMessages.getResourceBundle(), + "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT); + setAction("Format", action); //$NON-NLS-1$ + markAsStateDependentAction("Format", true); //$NON-NLS-1$ + markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); + + // action = new + // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(), + // "AddBlockComment.", this); //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); + // setAction("AddBlockComment", action); //$NON-NLS-1$ + // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("AddBlockComment", true); + // //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, + // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + // action = new RemoveBlockCommentAction( + // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); + // //$NON-NLS-1$ + // action + // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); + // setAction("RemoveBlockComment", action); //$NON-NLS-1$ + // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("RemoveBlockComment", true); + // //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + action = new IndentAction(PHPEditorMessages.getResourceBundle(), + "Indent.", this, false); //$NON-NLS-1$ + action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); + setAction("Indent", action); //$NON-NLS-1$ + markAsStateDependentAction("Indent", true); //$NON-NLS-1$ + markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); + // + // action= new IndentAction(PHPEditorMessages.getResourceBundle(), + // "Indent.", this, true); //$NON-NLS-1$ + // setAction("IndentOnTab", action); //$NON-NLS-1$ + // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ + // + + action = new AddBlockCommentAction(PHPEditorMessages + .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT); + setAction("AddBlockComment", action); //$NON-NLS-1$ + markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ + markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); + + action = new RemoveBlockCommentAction(PHPEditorMessages + .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ + action + .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); + setAction("RemoveBlockComment", action); //$NON-NLS-1$ + markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); + + // action= new IndentAction(PHPEditorMessages.getResourceBundle(), + // "Indent.", this, false); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT); + // setAction("Indent", action); //$NON-NLS-1$ + // markAsStateDependentAction("Indent", true); //$NON-NLS-1$ + // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ + // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); + // + action = new IndentAction(PHPEditorMessages.getResourceBundle(), + "Indent.", this, true); //$NON-NLS-1$ + setAction("IndentOnTab", action); //$NON-NLS-1$ + markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ + markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ + + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SMART_TAB)) { + // don't replace Shift Right - have to make sure their enablement is + // mutually exclusive + // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); + setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ + } + fGenerateActionGroup = new GenerateActionGroup(this, + ITextEditorActionConstants.GROUP_EDIT); + // ActionGroup rg= new RefactorActionGroup(this, + // ITextEditorActionConstants.GROUP_EDIT); + + // fActionGroups.addGroup(rg); + fActionGroups.addGroup(fGenerateActionGroup); + + // We have to keep the context menu group separate to have better + // control over positioning + fContextMenuGroup = new CompositeActionGroup( + new ActionGroup[] { fGenerateActionGroup + // rg, + // new LocalHistoryActionGroup(this, + // ITextEditorActionConstants.GROUP_EDIT) + }); + + } + + /* + * @see JavaEditor#getElementAt(int) + */ + protected IJavaElement getElementAt(int offset) { + return getElementAt(offset, true); + } + + /** + * Returns the most narrow element including the given offset. If + * reconcile is true the editor's input + * element is reconciled in advance. If it is false this + * method only returns a result if the editor's input element does not need + * to be reconciled. + * + * @param offset + * the offset included by the retrieved element + * @param reconcile + * true if working copy should be reconciled + */ + protected IJavaElement getElementAt(int offset, boolean reconcile) { + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + if (unit != null) { + try { + if (reconcile) { + synchronized (unit) { + unit.reconcile(); + } + return unit.getElementAt(offset); + } else if (unit.isConsistent()) + return unit.getElementAt(offset); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + } + return null; + } + + /* + * @see JavaEditor#getCorrespondingElement(IJavaElement) + */ + protected IJavaElement getCorrespondingElement(IJavaElement element) { + try { + return EditorUtility.getWorkingCopy(element, true); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x.getStatus()); + // nothing found, be tolerant and go on + } + return null; + } + + public void createPartControl(Composite parent) { + super.createPartControl(parent); + // fPaintManager = new PaintManager(getSourceViewer()); + LinePainter linePainter; + linePainter = new LinePainter(getSourceViewer()); + linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235, + 224)); + // fPaintManager.addPainter(linePainter); + // if (isBracketHighlightingEnabled()) + // startBracketHighlighting(); + // if (isLineHighlightingEnabled()) + // startLineHighlighting(); + // if (isPrintMarginVisible()) + // showPrintMargin(); + // Iterator e = ANNOTATION_MAP.keySet().iterator(); + // while (e.hasNext()) { + // AnnotationType type = (AnnotationType) e.next(); + // if (isAnnotationIndicationEnabled(type)) + // startAnnotationIndication(type); + // } + if (isTabConversionEnabled()) + startTabConversion(); + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // + // Preferences preferences = + // PHPeclipsePlugin.getDefault().getPluginPreferences(); + // preferences.addPropertyChangeListener(fPropertyChangeListener); + IPreferenceStore preferenceStore = getPreferenceStore(); + boolean closeBracketsPHP = preferenceStore + .getBoolean(CLOSE_BRACKETS_PHP); + boolean closeStringsPHPDQ = preferenceStore + .getBoolean(CLOSE_STRINGS_DQ_PHP); + boolean closeStringsPHPSQ = preferenceStore + .getBoolean(CLOSE_STRINGS_SQ_PHP); + fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP); + fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ); + fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ); + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer instanceof ITextViewerExtension) + ((ITextViewerExtension) sourceViewer) + .prependVerifyKeyListener(fBracketInserter); + } + + private static char getPeerCharacter(char character) { + switch (character) { + case '(': + return ')'; + case ')': + return '('; + case '[': + return ']'; + case ']': + return '['; + case '"': + return character; + case '\'': + return character; + case '{': + return '}'; + default: + throw new IllegalArgumentException(); + } + } + + // private void startBracketHighlighting() { + // if (fBracketPainter == null) { + // ISourceViewer sourceViewer = getSourceViewer(); + // fBracketPainter = new BracketPainter(sourceViewer); + // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); + // // fPaintManager.addPainter(fBracketPainter); + // } + // } + // + // private void stopBracketHighlighting() { + // if (fBracketPainter != null) { + // // fPaintManager.removePainter(fBracketPainter); + // fBracketPainter.deactivate(true); + // fBracketPainter.dispose(); + // fBracketPainter = null; + // } + // } + + // private boolean isBracketHighlightingEnabled() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(MATCHING_BRACKETS); + // } + + // private void startLineHighlighting() { + // if (fLinePainter == null) { + // ISourceViewer sourceViewer = getSourceViewer(); + // fLinePainter = new LinePainter(sourceViewer); + // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR)); + // // fPaintManager.addPainter(fLinePainter); + // } + // } + + // private void stopLineHighlighting() { + // if (fLinePainter != null) { + // // fPaintManager.removePainter(fLinePainter); + // fLinePainter.deactivate(true); + // fLinePainter.dispose(); + // fLinePainter = null; + // } + // } + + // private boolean isLineHighlightingEnabled() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(CURRENT_LINE); + // } + + // private void showPrintMargin() { + // if (fPrintMarginPainter == null) { + // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer()); + // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); + // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); + // // fPaintManager.addPainter(fPrintMarginPainter); + // } + // } + + // private void hidePrintMargin() { + // if (fPrintMarginPainter != null) { + // // fPaintManager.removePainter(fPrintMarginPainter); + // fPrintMarginPainter.deactivate(true); + // fPrintMarginPainter.dispose(); + // fPrintMarginPainter = null; + // } + // } + + // private boolean isPrintMarginVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(PRINT_MARGIN); + // } + + private int getTabSize() { + Preferences preferences = PHPeclipsePlugin.getDefault() + .getPluginPreferences(); + return preferences.getInt(CODE_FORMATTER_TAB_SIZE); + } + + private boolean isTabConversionEnabled() { + IPreferenceStore store = getPreferenceStore(); + return store.getBoolean(SPACES_FOR_TABS); + } + +// private Color getColor(String key) { +// RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key); +// return getColor(rgb); +// } + +// private Color getColor(RGB rgb) { +// JavaTextTools textTools = PHPeclipsePlugin.getDefault() +// .getJavaTextTools(); +// return textTools.getColorManager().getColor(rgb); +// } + + // private Color getColor(AnnotationType annotationType) { + // AnnotationInfo info = (AnnotationInfo) + // ANNOTATION_MAP.get(annotationType); + // if (info != null) + // return getColor(info.fColorPreference); + // return null; + // } + public void dispose() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer instanceof ITextViewerExtension) + ((ITextViewerExtension) sourceViewer) + .removeVerifyKeyListener(fBracketInserter); + // if (fPropertyChangeListener != null) { + // Preferences preferences = + // PHPeclipsePlugin.getDefault().getPluginPreferences(); + // preferences.removePropertyChangeListener(fPropertyChangeListener); + // fPropertyChangeListener = null; + // } + if (fJavaEditorErrorTickUpdater != null) { + fJavaEditorErrorTickUpdater.dispose(); + fJavaEditorErrorTickUpdater = null; + } + // if (fSelectionHistory != null) + // fSelectionHistory.dispose(); + // if (fPaintManager != null) { + // fPaintManager.dispose(); + // fPaintManager = null; + // } + if (fActionGroups != null) { + fActionGroups.dispose(); + fActionGroups = null; + } + super.dispose(); + } + + // protected AnnotationType getAnnotationType(String preferenceKey) { + // Iterator e = ANNOTATION_MAP.keySet().iterator(); + // while (e.hasNext()) { + // AnnotationType type = (AnnotationType) e.next(); + // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type); + // if (info != null) { + // if (preferenceKey.equals(info.fColorPreference) + // || preferenceKey.equals(info.fEditorPreference) + // || preferenceKey.equals(info.fOverviewRulerPreference)) + // return type; + // } + // } + // return null; + // } + /* + * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) + */ + protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { + try { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + if (asv != null) { + String p = event.getProperty(); + if (CLOSE_BRACKETS_PHP.equals(p)) { + fBracketInserter + .setCloseBracketsPHPEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (CLOSE_STRINGS_DQ_PHP.equals(p)) { + fBracketInserter + .setCloseStringsPHPDQEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (CLOSE_STRINGS_SQ_PHP.equals(p)) { + fBracketInserter + .setCloseStringsPHPSQEnabled(getPreferenceStore() + .getBoolean(p)); + return; + } + if (SPACES_FOR_TABS.equals(p)) { + if (isTabConversionEnabled()) + startTabConversion(); + else + stopTabConversion(); + return; + } + // if (MATCHING_BRACKETS.equals(p)) { + // if (isBracketHighlightingEnabled()) + // startBracketHighlighting(); + // else + // stopBracketHighlighting(); + // return; + // } + // if (MATCHING_BRACKETS_COLOR.equals(p)) { + // if (fBracketPainter != null) + // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR)); + // return; + // } + // if (CURRENT_LINE.equals(p)) { + // if (isLineHighlightingEnabled()) + // startLineHighlighting(); + // else + // stopLineHighlighting(); + // return; + // } + // if (CURRENT_LINE_COLOR.equals(p)) { + // if (fLinePainter != null) { + // stopLineHighlighting(); + // startLineHighlighting(); + // } + // return; + // } + // if (PRINT_MARGIN.equals(p)) { + // if (isPrintMarginVisible()) + // showPrintMargin(); + // else + // hidePrintMargin(); + // return; + // } + // if (PRINT_MARGIN_COLOR.equals(p)) { + // if (fPrintMarginPainter != null) + // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR)); + // return; + // } + // if (PRINT_MARGIN_COLUMN.equals(p)) { + // if (fPrintMarginPainter != null) + // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN)); + // return; + // } + // if (OVERVIEW_RULER.equals(p)) { + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // else + // hideOverviewRuler(); + // return; + // } + // AnnotationType type = getAnnotationType(p); + // if (type != null) { + // + // AnnotationInfo info = (AnnotationInfo) + // ANNOTATION_MAP.get(type); + // if (info.fColorPreference.equals(p)) { + // Color color = getColor(type); + // if (fProblemPainter != null) { + // fProblemPainter.setColor(type, color); + // fProblemPainter.paint(IPainter.CONFIGURATION); + // } + // setColorInOverviewRuler(type, color); + // return; + // } + // + // if (info.fEditorPreference.equals(p)) { + // if (isAnnotationIndicationEnabled(type)) + // startAnnotationIndication(type); + // else + // stopAnnotationIndication(type); + // return; + // } + // + // if (info.fOverviewRulerPreference.equals(p)) { + // if (isAnnotationIndicationInOverviewRulerEnabled(type)) + // showAnnotationIndicationInOverviewRuler(type, true); + // else + // showAnnotationIndicationInOverviewRuler(type, false); + // return; + // } + // } + IContentAssistant c = asv.getContentAssistant(); + if (c instanceof ContentAssistant) + ContentAssistPreference.changeConfiguration( + (ContentAssistant) c, getPreferenceStore(), event); + } + } finally { + super.handlePreferenceStoreChanged(event); + } + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) + */ + protected void handlePreferencePropertyChanged( + org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + if (asv != null) { + String p = event.getProperty(); + if (CODE_FORMATTER_TAB_SIZE.equals(p)) { + asv.updateIndentationPrefixes(); + if (fTabConverter != null) + fTabConverter.setNumberOfSpacesPerTab(getTabSize()); + } + } + super.handlePreferencePropertyChanged(event); + } + + /** + * Handles a property change event describing a change of the php core's + * preferences and updates the preference related editor properties. + * + * @param event + * the property change event + */ + // protected void + // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent + // event) { + // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + // if (asv != null) { + // String p = event.getProperty(); + // if (CODE_FORMATTER_TAB_SIZE.equals(p)) { + // asv.updateIndentationPrefixes(); + // if (fTabConverter != null) + // fTabConverter.setNumberOfSpacesPerTab(getTabSize()); + // } + // } + // } + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, + * org.eclipse.jface.text.source.IVerticalRuler, + * org.eclipse.jface.text.source.IOverviewRuler, boolean, int) + */ + protected ISourceViewer createJavaSourceViewer(Composite parent, + IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, + boolean isOverviewRulerVisible, int styles, IPreferenceStore store) { + return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, + isOverviewRulerVisible, styles, store); + } + + // protected ISourceViewer createJavaSourceViewer(Composite parent, + // IVerticalRuler ruler, int styles) { + // return new AdaptedSourceViewer(parent, ruler, styles); + // } +// private boolean isValidSelection(int offset, int length) { +// IDocumentProvider provider = getDocumentProvider(); +// if (provider != null) { +// IDocument document = provider.getDocument(getEditorInput()); +// if (document != null) { +// int end = offset + length; +// int documentLength = document.getLength(); +// return 0 <= offset && offset <= documentLength && 0 <= end +// && end <= documentLength; +// } +// } +// return false; +// } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement() + */ + protected IJavaElement getInputJavaElement() { + return PHPeclipsePlugin.getDefault().getWorkingCopyManager() + .getWorkingCopy(getEditorInput()); + } + + /* + * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) + */ + public void editorContextMenuAboutToShow(IMenuManager menu) { + super.editorContextMenuAboutToShow(menu); + ActionContext context = new ActionContext(getSelectionProvider() + .getSelection()); + fContextMenuGroup.setContext(context); + fContextMenuGroup.fillContextMenu(menu); + fContextMenuGroup.setContext(null); + } + + /* + * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) + */ + protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { + if (page != null) { + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + page.setInput(manager.getWorkingCopy(input)); + } + } + + /* + * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, + * IProgressMonitor) + */ + // protected void performSaveOperation(WorkspaceModifyOperation operation, + // IProgressMonitor progressMonitor) { + // IDocumentProvider p = getDocumentProvider(); + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(fSavePolicy); + // } + // + // try { + // super.performSaveOperation(operation, progressMonitor); + // } finally { + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(null); + // } + // } + // } + /* + * @see AbstractTextEditor#doSave(IProgressMonitor) + */ + public void doSave(IProgressMonitor progressMonitor) { + + IDocumentProvider p = getDocumentProvider(); + if (p == null) { + // editor has been closed + return; + } + + if (p.isDeleted(getEditorInput())) { + + if (isSaveAsAllowed()) { + + /* + * 1GEUSSR: ITPUI:ALL - User should never loose changes made in + * the editors. Changed Behavior to make sure that if called + * inside a regular save (because of deletion of input element) + * there is a way to report back to the caller. + */ + performSaveAs(progressMonitor); + + } else { + + /* + * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still + * there Missing resources. + */ + Shell shell = getSite().getShell(); + MessageDialog + .openError( + shell, + PHPEditorMessages + .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + } else { + if (getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) { + RTrimAction trimAction = new RTrimAction(); + trimAction.setActiveEditor(null, getSite().getPage() + .getActiveEditor()); + trimAction.run(null); + } + + setStatusLineErrorMessage(null); + + updateState(getEditorInput()); + validateState(getEditorInput()); + + IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() + .getWorkingCopyManager(); + ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); + + if (unit != null) { + synchronized (unit) { + performSave(false, progressMonitor); + } + } else + performSave(false, progressMonitor); + } + } + + public boolean isSaveAsAllowed() { + return true; + } + + /** + * The compilation unit editor implementation of this + * AbstractTextEditor method asks the user for the workspace + * path of a file resource and saves the document there. See + * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 + * + * @param progressMonitor + * the progress monitor + */ + protected void performSaveAs(IProgressMonitor progressMonitor) { + + Shell shell = getSite().getShell(); + IEditorInput input = getEditorInput(); + + SaveAsDialog dialog = new SaveAsDialog(shell); + + IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input) + .getFile() + : null; + if (original != null) + dialog.setOriginalFile(original); + + dialog.create(); + + IDocumentProvider provider = getDocumentProvider(); + if (provider == null) { + // editor has been programmatically closed while the dialog was open + return; + } + + if (provider.isDeleted(input) && original != null) { + String message = PHPEditorMessages + .getFormattedString( + "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ + dialog.setErrorMessage(null); + dialog.setMessage(message, IMessageProvider.WARNING); + } + + if (dialog.open() == Window.CANCEL) { + if (progressMonitor != null) + progressMonitor.setCanceled(true); + return; + } + + IPath filePath = dialog.getResult(); + if (filePath == null) { + if (progressMonitor != null) + progressMonitor.setCanceled(true); + return; + } + + IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); + IFile file = workspaceRoot.getFile(filePath); + final IEditorInput newInput = new FileEditorInput(file); + + boolean success = false; + try { + + provider.aboutToChange(newInput); + getDocumentProvider().saveDocument(progressMonitor, newInput, + getDocumentProvider().getDocument(getEditorInput()), true); + success = true; + + } catch (CoreException x) { + IStatus status = x.getStatus(); + if (status == null || status.getSeverity() != IStatus.CANCEL) + ErrorDialog + .openError( + shell, + PHPEditorMessages + .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ + } finally { + provider.changed(newInput); + if (success) + setInput(newInput); + } + + if (progressMonitor != null) + progressMonitor.setCanceled(!success); + } + + /* + * @see AbstractTextEditor#doSetInput(IEditorInput) + */ + protected void doSetInput(IEditorInput input) throws CoreException { + super.doSetInput(input); + configureTabConverter(); + configureToggleCommentAction(); + } + + // /* + // * @see + // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean) + // * @since 3.0 + // */ + // protected void installOverrideIndicator(boolean waitForReconcilation) { + // IAnnotationModel model= + // getDocumentProvider().getAnnotationModel(getEditorInput()); + // if (!waitForReconcilation) + // super.installOverrideIndicator(false); + // else { + // uninstallOverrideIndicator(); + // IJavaElement inputElement= getInputJavaElement(); + // if (model == null || inputElement == null) + // return; + // + // fOverrideIndicatorManager= new OverrideIndicatorManager(model, + // inputElement, null); + // addReconcileListener(fOverrideIndicatorManager); + // } + // } + // + // /* + // * @see + // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator() + // * @since 3.0 + // */ + // protected void uninstallOverrideIndicator() { + // if (fOverrideIndicatorManager != null) + // removeReconcileListener(fOverrideIndicatorManager); + // super.uninstallOverrideIndicator(); + // } + + /** + * Configures the toggle comment action + * + * @since 3.0 + */ + private void configureToggleCommentAction() { + IAction action = getAction("ToggleComment"); //$NON-NLS-1$ + if (action instanceof ToggleCommentAction) { + ISourceViewer sourceViewer = getSourceViewer(); + SourceViewerConfiguration configuration = getSourceViewerConfiguration(); + ((ToggleCommentAction) action).configure(sourceViewer, + configuration); + } + } + + // private void configureTabConverter() { + // if (fTabConverter != null) { + // IDocumentProvider provider = getDocumentProvider(); + // if (provider instanceof PHPDocumentProvider) { + // PHPDocumentProvider cup = (PHPDocumentProvider) provider; + // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); + // } + // } + // } + private void configureTabConverter() { + if (fTabConverter != null) { + IDocumentProvider provider = getDocumentProvider(); + if (provider instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider; + fTabConverter.setLineTracker(cup + .createLineTracker(getEditorInput())); + } + } + } + + private void startTabConversion() { + if (fTabConverter == null) { + fTabConverter = new TabConverter(); + configureTabConverter(); + fTabConverter.setNumberOfSpacesPerTab(getTabSize()); + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + asv.addTextConverter(fTabConverter); + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + asv.updateIndentationPrefixes(); + } + } + + private void stopTabConversion() { + if (fTabConverter != null) { + AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer(); + asv.removeTextConverter(fTabConverter); + // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 + asv.updateIndentationPrefixes(); + fTabConverter = null; + } + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, + * org.eclipse.core.runtime.IProgressMonitor) + */ + protected void performSave(boolean overwrite, + IProgressMonitor progressMonitor) { + // IDocumentProvider p = getDocumentProvider(); + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(fSavePolicy); + // } + // try { + // super.performSave(overwrite, progressMonitor); + // } finally { + // if (p instanceof PHPDocumentProvider) { + // PHPDocumentProvider cp = (PHPDocumentProvider) p; + // cp.setSavePolicy(null); + // } + // } + + IDocumentProvider p = getDocumentProvider(); + if (p instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; + cp.setSavePolicy(fSavePolicy); + } + try { + super.performSave(overwrite, progressMonitor); + } finally { + if (p instanceof ICompilationUnitDocumentProvider) { + ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p; + cp.setSavePolicy(null); + } + } + } + + /* + * @see AbstractTextEditor#doSaveAs + */ + public void doSaveAs() { + if (askIfNonWorkbenchEncodingIsOk()) { + super.doSaveAs(); + } + } + + /** + * Asks the user if it is ok to store in non-workbench encoding. + * + * @return if the user wants to continue + */ + private boolean askIfNonWorkbenchEncodingIsOk() { + IDocumentProvider provider = getDocumentProvider(); + if (provider instanceof IStorageDocumentProvider) { + IEditorInput input = getEditorInput(); + IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider; + String encoding = storageProvider.getEncoding(input); + String defaultEncoding = storageProvider.getDefaultEncoding(); + if (encoding != null && !encoding.equals(defaultEncoding)) { + Shell shell = getSite().getShell(); + String title = PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ + String msg; + if (input != null) + msg = MessageFormat + .format( + PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"), + new String[] { input.getName(), encoding }); //$NON-NLS-1$ + else + msg = MessageFormat + .format( + PHPEditorMessages + .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"), + new String[] { encoding }); //$NON-NLS-1$ + return MessageDialog.openQuestion(shell, title, msg); + } + } + return true; + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled() + * @since 3.0 + */ + public void aboutToBeReconciled() { + + // Notify AST provider + // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement()); + + // Notify listeners + Object[] listeners = fReconcilingListeners.getListeners(); + for (int i = 0, length = listeners.length; i < length; ++i) + ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled(); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, + * boolean, IProgressMonitor) + * @since 3.0 + */ + public void reconciled(CompilationUnit ast, boolean forced, + IProgressMonitor progressMonitor) { + + // Always notify AST provider + // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, + // getInputJavaElement()); + + // Notify listeners + // Object[] listeners = fReconcilingListeners.getListeners(); + // for (int i = 0, length= listeners.length; i < length; ++i) + // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, + // progressMonitor); + + // Update Java Outline page selection + if (!forced && !progressMonitor.isCanceled()) { + Shell shell = getSite().getShell(); + if (shell != null && !shell.isDisposed()) { + shell.getDisplay().asyncExec(new Runnable() { + public void run() { + selectionChanged(); + } + }); + } + } + } + + /** + * Returns the updated java element for the old java element. + */ +// private IJavaElement findElement(IJavaElement element) { +// if (element == null) +// return null; +// IWorkingCopyManager manager = PHPeclipsePlugin.getDefault() +// .getWorkingCopyManager(); +// ICompilationUnit unit = manager.getWorkingCopy(getEditorInput()); +// if (unit != null) { +// try { +// synchronized (unit) { +// unit.reconcile(); +// } +// IJavaElement[] findings = unit.findElements(element); +// if (findings != null && findings.length > 0) +// return findings[0]; +// } catch (JavaModelException x) { +// PHPeclipsePlugin.log(x.getStatus()); +// // nothing found, be tolerant and go on +// } +// } +// return null; +// } + + /** + * Returns the offset of the given Java element. + */ +// private int getOffset(IJavaElement element) { +// if (element instanceof ISourceReference) { +// ISourceReference sr = (ISourceReference) element; +// try { +// ISourceRange srcRange = sr.getSourceRange(); +// if (srcRange != null) +// return srcRange.getOffset(); +// } catch (JavaModelException e) { +// } +// } +// return -1; +// } + + /* + * @see AbstractTextEditor#restoreSelection() + */ + // protected void restoreSelection() { + // try { + // if (getSourceViewer() == null || fRememberedSelection == null) + // return; + // IJavaElement newElement = findElement(fRememberedElement); + // int newOffset = getOffset(newElement); + // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset + // - fRememberedElementOffset : 0; + // if (isValidSelection(delta + fRememberedSelection.getOffset(), + // fRememberedSelection.getLength())) + // selectAndReveal(delta + fRememberedSelection.getOffset(), + // fRememberedSelection.getLength()); + // } finally { + // fRememberedSelection = null; + // fRememberedElement = null; + // fRememberedElementOffset = -1; + // } + // } + /** + * Tells whether this is the active editor in the active page. + * + * @return true if this is the active editor in the active + * page + * @see IWorkbenchPage#getActiveEditor(); + */ + protected final boolean isActiveEditor() { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + IWorkbenchPage page = window.getActivePage(); + if (page == null) + return false; + IEditorPart activeEditor = page.getActiveEditor(); + return activeEditor != null && activeEditor.equals(this); + } + + /** + * Adds the given listener. Has no effect if an identical listener was not + * already registered. + * + * @param listener + * The reconcile listener to be added + * @since 3.0 + */ + final void addReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.add(listener); + } + } + + /** + * Removes the given listener. Has no effect if an identical listener was + * not already registered. + * + * @param listener + * the reconcile listener to be removed + * @since 3.0 + */ + final void removeReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.remove(listener); + } + } + + protected void updateStateDependentActions() { + super.updateStateDependentActions(); + fGenerateActionGroup.editorStateChanged(); + } + + /* + * @see AbstractTextEditor#rememberSelection() + */ + protected void rememberSelection() { + fRememberedSelection.remember(); + } + + /* + * @see AbstractTextEditor#restoreSelection() + */ + protected void restoreSelection() { + fRememberedSelection.restore(); + } + + /* + * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) + */ + protected boolean canHandleMove(IEditorInput originalElement, + IEditorInput movedElement) { + + String oldExtension = ""; //$NON-NLS-1$ + if (originalElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) originalElement).getFile(); + if (file != null) { + String ext = file.getFileExtension(); + if (ext != null) + oldExtension = ext; + } + } + + String newExtension = ""; //$NON-NLS-1$ + if (movedElement instanceof IFileEditorInput) { + IFile file = ((IFileEditorInput) movedElement).getFile(); + if (file != null) + newExtension = file.getFileExtension(); + } + + return oldExtension.equals(newExtension); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn() + */ + protected boolean isPrefQuickDiffAlwaysOn() { + // reestablishes the behaviour from AbstractDecoratedTextEditor which + // was hacked by JavaEditor + // to disable the change bar for the class file (attached source) java + // editor. + IPreferenceStore store = getPreferenceStore(); + return store + .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); + } + + /* + * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class required) { + if (SmartBackspaceManager.class.equals(required)) { + if (getSourceViewer() instanceof JavaSourceViewer) { + return ((JavaSourceViewer) getSourceViewer()) + .getBackspaceManager(); + } + } + + return super.getAdapter(required); + } + + /** + * Returns the mutex for the reconciler. See + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of + * the problem. + *

+ * TODO remove once the underlying problem is solved. + *

+ * + * @return the lock reconcilers may use to synchronize on + */ + public Object getReconcilerLock() { + return fReconcilerLock; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved() + */ + protected void editorSaved() { + super.editorSaved(); + ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance(); + if (a != null) { + //a.refresh(ShowExternalPreviewAction.PHP_TYPE); + a.doRun(ShowExternalPreviewAction.PHP_TYPE); + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PaintManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PartiallySynchronizedDocument.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PresentationAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PrintMarginPainter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemAnnotationIterator.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java new file mode 100644 index 0000000..d02d7cb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ProblemPainter.java @@ -0,0 +1,405 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ + +package net.sourceforge.phpeclipse.phpeditor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewerExtension5; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.jface.text.source.IAnnotationModelListener; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.PaintEvent; +import org.eclipse.swt.events.PaintListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Highlights the temporary problems. + */ +public class ProblemPainter implements IPainter, PaintListener, + IAnnotationModelListener { + + private static class ProblemPosition { + Position fPosition; + + Color fColor; + + boolean fMultiLine; + }; + + private boolean fIsActive = false; + + private boolean fIsPainting = false; + + private boolean fIsSettingModel = false; + + private ITextEditor fTextEditor; + + private ISourceViewer fSourceViewer; + + private StyledText fTextWidget; + + private IAnnotationModel fModel; + + private List fProblemPositions = new ArrayList(); + + private Map fColorTable = new HashMap(); + + private Set fAnnotationSet = new HashSet(); + + public ProblemPainter(ITextEditor textEditor, ISourceViewer sourceViewer) { + fTextEditor = textEditor; + fSourceViewer = sourceViewer; + fTextWidget = sourceViewer.getTextWidget(); + } + + private boolean hasProblems() { + return !fProblemPositions.isEmpty(); + } + + private void enablePainting() { + if (!fIsPainting && hasProblems()) { + fIsPainting = true; + fTextWidget.addPaintListener(this); + handleDrawRequest(null); + } + } + + private void disablePainting(boolean redraw) { + if (fIsPainting) { + fIsPainting = false; + fTextWidget.removePaintListener(this); + if (redraw && hasProblems()) + handleDrawRequest(null); + } + } + + private void setModel(IAnnotationModel model) { + if (fModel != model) { + if (fModel != null) + fModel.removeAnnotationModelListener(this); + fModel = model; + if (fModel != null) { + try { + fIsSettingModel = true; + fModel.addAnnotationModelListener(this); + } finally { + fIsSettingModel = false; + } + } + } + } + + private void catchupWithModel() { + if (fProblemPositions != null) { + fProblemPositions.clear(); + if (fModel != null) { + + Iterator e = new ProblemAnnotationIterator(fModel, true); + while (e.hasNext()) { + IProblemAnnotation pa = (IProblemAnnotation) e.next(); + Annotation a = (Annotation) pa; + + Color color = null; + AnnotationType type = pa.getAnnotationType(); + if (fAnnotationSet.contains(type)) + color = (Color) fColorTable.get(type); + + if (color != null) { + ProblemPosition pp = new ProblemPosition(); + pp.fPosition = fModel.getPosition(a); + pp.fColor = color; + pp.fMultiLine = true; + fProblemPositions.add(pp); + } + } + } + } + } + + private void updatePainting() { + disablePainting(true); + catchupWithModel(); + enablePainting(); + } + + /* + * @see IAnnotationModelListener#modelChanged(IAnnotationModel) + */ + public void modelChanged(final IAnnotationModel model) { + if (fTextWidget != null && !fTextWidget.isDisposed()) { + if (fIsSettingModel) { + // inside the ui thread -> no need for posting + updatePainting(); + } else { + Display d = fTextWidget.getDisplay(); + if (d != null) { + d.asyncExec(new Runnable() { + public void run() { + if (fTextWidget != null + && !fTextWidget.isDisposed()) + updatePainting(); + } + }); + } + } + } + } + + public void setColor(AnnotationType annotationType, Color color) { + if (color != null) + fColorTable.put(annotationType, color); + else + fColorTable.remove(annotationType); + } + + public void paintAnnotations(AnnotationType annotationType, boolean paint) { + if (paint) + fAnnotationSet.add(annotationType); + else + fAnnotationSet.remove(annotationType); + } + + public boolean isPaintingAnnotations() { + return !fAnnotationSet.isEmpty(); + } + + /* + * @see IPainter#dispose() + */ + public void dispose() { + + if (fColorTable != null) + fColorTable.clear(); + fColorTable = null; + + if (fAnnotationSet != null) + fAnnotationSet.clear(); + fAnnotationSet = null; + + fTextWidget = null; + fModel = null; + fProblemPositions = null; + } + + /* + * Returns the document offset of the upper left corner of the widgets + * viewport, possibly including partially visible lines. + */ + private int getInclusiveTopIndexStartOffset() { + + if (fTextWidget != null && !fTextWidget.isDisposed()) { + int top = fSourceViewer.getTopIndex(); + if ((fTextWidget.getTopPixel() % fTextWidget.getLineHeight()) != 0) + top--; + try { + IDocument document = fSourceViewer.getDocument(); + return document.getLineOffset(top); + } catch (BadLocationException ex) { + } + } + + return -1; + } + + /* + * @see PaintListener#paintControl(PaintEvent) + */ + public void paintControl(PaintEvent event) { + if (fTextWidget != null) + handleDrawRequest(event.gc); + } + + private void handleDrawRequest(GC gc) { + + int vOffset = getInclusiveTopIndexStartOffset(); + // http://bugs.eclipse.org/bugs/show_bug.cgi?id=17147 + int vLength = fSourceViewer.getBottomIndexEndOffset() + 1; + + for (Iterator e = fProblemPositions.iterator(); e.hasNext();) { + ProblemPosition pp = (ProblemPosition) e.next(); + Position p = pp.fPosition; + if (p.overlapsWith(vOffset, vLength)) { + + if (!pp.fMultiLine) { + + IRegion widgetRange = getWidgetRange(p); + if (widgetRange != null) + draw(gc, widgetRange.getOffset(), widgetRange + .getLength(), pp.fColor); + + } else { + + IDocument document = fSourceViewer.getDocument(); + try { + + int startLine = document.getLineOfOffset(p.getOffset()); + int lastInclusive = Math.max(p.getOffset(), p + .getOffset() + + p.getLength() - 1); + int endLine = document.getLineOfOffset(lastInclusive); + + for (int i = startLine; i <= endLine; i++) { + IRegion line = document.getLineInformation(i); + int paintStart = Math.max(line.getOffset(), p + .getOffset()); + int paintEnd = Math.min(line.getOffset() + + line.getLength(), p.getOffset() + + p.getLength()); + if (paintEnd > paintStart) { + // otherwise inside a line delimiter + IRegion widgetRange = getWidgetRange(new Position( + paintStart, paintEnd - paintStart)); + if (widgetRange != null) + draw(gc, widgetRange.getOffset(), + widgetRange.getLength(), pp.fColor); + } + } + + } catch (BadLocationException x) { + } + } + } + } + } + + private IRegion getWidgetRange(Position p) { + if (fSourceViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) fSourceViewer; + return extension.modelRange2WidgetRange(new Region(p.getOffset(), p + .getLength())); + + } else { + + IRegion region = fSourceViewer.getVisibleRegion(); + int offset = region.getOffset(); + int length = region.getLength(); + + if (p.overlapsWith(offset, length)) { + int p1 = Math.max(offset, p.getOffset()); + int p2 = Math.min(offset + length, p.getOffset() + + p.getLength()); + return new Region(p1 - offset, p2 - p1); + } + } + + return null; + } + + private int[] computePolyline(Point left, Point right, int height) { + + final int WIDTH = 4; // must be even + final int HEIGHT = 2; // can be any number + // final int MINPEEKS= 2; // minimal number of peeks + + int peeks = (right.x - left.x) / WIDTH; + // if (peeks < MINPEEKS) { + // int missing= (MINPEEKS - peeks) * WIDTH; + // left.x= Math.max(0, left.x - missing/2); + // peeks= MINPEEKS; + // } + + int leftX = left.x; + + // compute (number of point) * 2 + int length = ((2 * peeks) + 1) * 2; + if (length < 0) + return new int[0]; + + int[] coordinates = new int[length]; + + // cache peeks' y-coordinates + int bottom = left.y + height - 1; + int top = bottom - HEIGHT; + + // populate array with peek coordinates + for (int i = 0; i < peeks; i++) { + int index = 4 * i; + coordinates[index] = leftX + (WIDTH * i); + coordinates[index + 1] = bottom; + coordinates[index + 2] = coordinates[index] + WIDTH / 2; + coordinates[index + 3] = top; + } + + // the last down flank is missing + coordinates[length - 2] = left.x + (WIDTH * peeks); + coordinates[length - 1] = bottom; + + return coordinates; + } + + private void draw(GC gc, int offset, int length, Color color) { + if (gc != null) { + + Point left = fTextWidget.getLocationAtOffset(offset); + Point right = fTextWidget.getLocationAtOffset(offset + length); + + gc.setForeground(color); + int[] polyline = computePolyline(left, right, gc.getFontMetrics() + .getHeight()); + gc.drawPolyline(polyline); + + } else { + fTextWidget.redrawRange(offset, length, true); + } + } + + /* + * @see IPainter#deactivate(boolean) + */ + public void deactivate(boolean redraw) { + if (fIsActive) { + fIsActive = false; + disablePainting(redraw); + setModel(null); + catchupWithModel(); + } + } + + /* + * @see IPainter#paint(int) + */ + public void paint(int reason) { + if (!fIsActive) { + fIsActive = true; + IDocumentProvider provider = PHPeclipsePlugin.getDefault() + .getCompilationUnitDocumentProvider(); + setModel(provider.getAnnotationModel(fTextEditor.getEditorInput())); + } else if (CONFIGURATION == reason || INTERNAL == reason) + updatePainting(); + } + + /* + * @see IPainter#setPositionManager(IPositionManager) + */ + public void setPositionManager(IPositionManager manager) { + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java new file mode 100644 index 0000000..db7dede --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SmartyDocumentSetupParticipant.java @@ -0,0 +1,38 @@ +/********************************************************************** + Copyright (c) 2000, 2003 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.filebuffers.IDocumentSetupParticipant; +import org.eclipse.jface.text.IDocument; + +/** + * The document setup participant for PHPDT. + */ +public class SmartyDocumentSetupParticipant implements + IDocumentSetupParticipant { + + public SmartyDocumentSetupParticipant() { + } + + /* + * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument) + */ + public void setup(IDocument document) { + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupSmartyDocumentPartitioner(document, + IPHPPartitions.PHP_PARTITIONING, null); // IPHPPartitions.PHP_PARTITIONING, + // null); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/ToggleCommentAction.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java new file mode 100644 index 0000000..71b3da6 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/TogglePresentationAction.java @@ -0,0 +1,139 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpeclipse.phpeditor; + +import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.ui.texteditor.TextEditorAction; + +/** + * A toolbar action which toggles the presentation model of the connected text + * editor. The editor shows either the highlight range only or always the whole + * document. + */ +public class TogglePresentationAction extends TextEditorAction implements + IPropertyChangeListener { + + private IPreferenceStore fStore; + + /** + * Constructs and updates the action. + */ + public TogglePresentationAction() { + super(PHPEditorMessages.getResourceBundle(), + "TogglePresentation.", null); //$NON-NLS-1$ + PHPUiImages.setToolImageDescriptors(this, "segment_edit.gif"); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages + .getString("TogglePresentation.tooltip")); //$NON-NLS-1$ + setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_PRESENTATION); + // WorkbenchHelp.setHelp(this, + // IJavaHelpContextIds.TOGGLE_PRESENTATION_ACTION); + update(); + } + + /* + * @see IAction#actionPerformed + */ + public void run() { + + ITextEditor editor = getTextEditor(); + if (editor == null) + return; + + IRegion remembered = editor.getHighlightRange(); + editor.resetHighlightRange(); + + boolean showAll = !editor.showsHighlightRangeOnly(); + setChecked(showAll); + + editor.showHighlightRangeOnly(showAll); + if (remembered != null) + editor.setHighlightRange(remembered.getOffset(), remembered + .getLength(), true); + + fStore.removePropertyChangeListener(this); + fStore.setValue(PreferenceConstants.EDITOR_SHOW_SEGMENTS, showAll); + fStore.addPropertyChangeListener(this); + } + + /* + * @see TextEditorAction#update + */ + public void update() { + ITextEditor editor = getTextEditor(); + boolean checked = (editor != null && editor.showsHighlightRangeOnly()); + setChecked(checked); + setEnabled(editor != null); + } + + /* + * @see TextEditorAction#setEditor(ITextEditor) + */ + public void setEditor(ITextEditor editor) { + + super.setEditor(editor); + + if (editor != null) { + + if (fStore == null) { + fStore = PHPeclipsePlugin.getDefault().getPreferenceStore(); + fStore.addPropertyChangeListener(this); + } + synchronizeWithPreference(editor); + + } else if (fStore != null) { + fStore.removePropertyChangeListener(this); + fStore = null; + } + + update(); + } + + /** + * Synchronizes the appearance of the editor with what the preference store + * tells him. + */ + private void synchronizeWithPreference(ITextEditor editor) { + + if (editor == null) + return; + + boolean showSegments = fStore + .getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS); + setChecked(showSegments); + + if (editor.showsHighlightRangeOnly() != showSegments) { + IRegion remembered = editor.getHighlightRange(); + editor.resetHighlightRange(); + editor.showHighlightRangeOnly(showSegments); + if (remembered != null) + editor.setHighlightRange(remembered.getOffset(), remembered + .getLength(), true); + } + } + + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty() + .equals(PreferenceConstants.EDITOR_SHOW_SEGMENTS)) + synchronizeWithPreference(getTextEditor()); + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/WorkingCopyManager.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/actions/RTrimAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCodeScanner.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java new file mode 100644 index 0000000..eb8e5aa --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLCompletionProcessor.java @@ -0,0 +1,308 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor.php; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; +import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +//import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.TextPresentation; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationExtension; +import org.eclipse.jface.text.contentassist.IContextInformationPresenter; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.IEditorPart; + +/** + * HTML completion processor. + */ +public class HTMLCompletionProcessor implements IContentAssistProcessor { + + /** + * Simple content assist tip closer. The tip is valid in a range of 5 + * characters around its popup location. + */ + protected static class Validator implements IContextInformationValidator, + IContextInformationPresenter { + + protected int fInstallOffset; + + /* + * @see IContextInformationValidator#isContextInformationValid(int) + */ + public boolean isContextInformationValid(int offset) { + return Math.abs(fInstallOffset - offset) < 5; + } + + /* + * @see IContextInformationValidator#install(IContextInformation, + * ITextViewer, int) + */ + public void install(IContextInformation info, ITextViewer viewer, + int offset) { + fInstallOffset = offset; + } + + /* + * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, + * TextPresentation) + */ + public boolean updatePresentation(int documentPosition, + TextPresentation presentation) { + return false; + } + }; + + private static class ContextInformationWrapper implements + IContextInformation, IContextInformationExtension { + + private final IContextInformation fContextInformation; + + private int fPosition; + + public ContextInformationWrapper(IContextInformation contextInformation) { + fContextInformation = contextInformation; + } + + /* + * @see IContextInformation#getContextDisplayString() + */ + public String getContextDisplayString() { + return fContextInformation.getContextDisplayString(); + } + + /* + * @see IContextInformation#getImage() + */ + public Image getImage() { + return fContextInformation.getImage(); + } + + /* + * @see IContextInformation#getInformationDisplayString() + */ + public String getInformationDisplayString() { + return fContextInformation.getInformationDisplayString(); + } + + /* + * @see IContextInformationExtension#getContextInformationPosition() + */ + public int getContextInformationPosition() { + return fPosition; + } + + public void setContextInformationPosition(int position) { + fPosition = position; + } + }; + + protected IContextInformationValidator fValidator = new Validator(); + + private TemplateEngine fTemplateEngine; + + private char[] fProposalAutoActivationSet; + + private PHPCompletionProposalComparator fComparator; + + private int fNumberOfComputedResults = 0; + + private IEditorPart fEditor; + + protected IWorkingCopyManager fManager; + + public HTMLCompletionProcessor(IEditorPart editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("html"); //$NON-NLS-1$ + if (contextType != null) + fTemplateEngine = new TemplateEngine(contextType); + + fComparator = new PHPCompletionProposalComparator(); + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, documentOffset); + return internalComputeCompletionProposals(viewer, documentOffset, + contextInformationPosition); + } + + private ICompletionProposal[] internalComputeCompletionProposals( + ITextViewer viewer, int offset, int contextOffset) { + //IDocument document = viewer.getDocument(); + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + + if (fTemplateEngine != null) { + ICompletionProposal[] results; + // try { + fTemplateEngine.reset(); + fTemplateEngine.complete(viewer, offset, unit); + // } catch (JavaModelException x) { + // Shell shell= viewer.getTextWidget().getShell(); + // ErrorDialog.openError(shell, + // JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), + // JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), + // x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ + // } + + IPHPCompletionProposal[] templateResults = fTemplateEngine + .getResults(); + + // concatenate arrays + IPHPCompletionProposal[] total; + total = new IPHPCompletionProposal[templateResults.length]; + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + results = total; + + fNumberOfComputedResults = (results == null ? 0 : results.length); + /* + * Order here and not in result collector to make sure that the + * order applies to all proposals and not just those of the + * compilation unit. + */ + return order(results); + } + return new IPHPCompletionProposal[0]; + } + + private int guessContextInformationPosition(ITextViewer viewer, int offset) { + int contextPosition = offset; + //IDocument document = viewer.getDocument(); + return contextPosition; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + // public IContextInformation[] computeContextInformation(ITextViewer + // viewer, int documentOffset) { + // IContextInformation[] result = new IContextInformation[5]; + // for (int i = 0; i < result.length; i++) + // result[i] = new + // ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), + // new Object[] { new Integer(i), new Integer(documentOffset)}), + // //$NON-NLS-1$ + // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), + // new Object[] { new Integer(i), new Integer(documentOffset - 5), new + // Integer(documentOffset + 5)})); //$NON-NLS-1$ + // return result; + // } + /** + * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) + */ + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, offset); + List result = addContextInformations(viewer, contextInformationPosition); + return (IContextInformation[]) result + .toArray(new IContextInformation[result.size()]); + } + + private List addContextInformations(ITextViewer viewer, int offset) { + ICompletionProposal[] proposals = internalComputeCompletionProposals( + viewer, offset, -1); + + List result = new ArrayList(); + for (int i = 0; i < proposals.length; i++) { + IContextInformation contextInformation = proposals[i] + .getContextInformation(); + if (contextInformation != null) { + ContextInformationWrapper wrapper = new ContextInformationWrapper( + contextInformation); + wrapper.setContextInformationPosition(offset); + result.add(wrapper); + } + } + return result; + } + + /** + * Order the given proposals. + */ + private ICompletionProposal[] order(ICompletionProposal[] proposals) { + Arrays.sort(proposals, fComparator); + return proposals; + } + + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + public void orderProposalsAlphabetically(boolean order) { + fComparator.setOrderAlphabetically(order); + } + + /** + * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public char[] getContextInformationAutoActivationCharacters() { + return new char[] {}; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public IContextInformationValidator getContextInformationValidator() { + return fValidator; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public String getErrorMessage() { + return null; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLPartitionScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/HTMLWordExtractor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPAutoIndentStrategy.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java new file mode 100644 index 0000000..4638f76 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java @@ -0,0 +1,1068 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor.php; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpdt.core.ToolFactory; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols.TokenName; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies; +import net.sourceforge.phpdt.internal.compiler.ast.CompilationUnitDeclaration; +import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError; +import net.sourceforge.phpdt.internal.compiler.parser.UnitParser; +import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo; +import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory; +import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; +import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; +import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader; +import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal; +import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator; +import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator; +import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine; +import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine; +import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal; +import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine; +import net.sourceforge.phpdt.ui.IWorkingCopyManager; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.builder.IdentifierIndexManager; +import net.sourceforge.phpeclipse.phpeditor.PHPEditor; +import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.ITextViewer; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.jface.text.contentassist.IContextInformation; +import org.eclipse.jface.text.contentassist.IContextInformationExtension; +import org.eclipse.jface.text.contentassist.IContextInformationValidator; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IFileEditorInput; + +/** + * Example PHP completion processor. + */ +public class PHPCompletionProcessor implements IContentAssistProcessor { + /** + * Simple content assist tip closer. The tip is valid in a range of 5 + * characters around its popup location. + */ + // protected static class Validator implements IContextInformationValidator, + // IContextInformationPresenter { + // protected int fInstallOffset; + // + // /* + // * @see IContextInformationValidator#isContextInformationValid(int) + // */ + // public boolean isContextInformationValid(int offset) { + // return Math.abs(fInstallOffset - offset) < 5; + // } + // + // /* + // * @see IContextInformationValidator#install(IContextInformation, + // ITextViewer, int) + // */ + // public void install(IContextInformation info, ITextViewer viewer, int + // offset) { + // fInstallOffset = offset; + // } + // + // /* + // * @see + // org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, + // TextPresentation) + // */ + // public boolean updatePresentation(int documentPosition, TextPresentation + // presentation) { + // return false; + // } + // }; + private static class ContextInformationWrapper implements + IContextInformation, IContextInformationExtension { + private final IContextInformation fContextInformation; + + private int fPosition; + + public ContextInformationWrapper(IContextInformation contextInformation) { + fContextInformation = contextInformation; + } + + /* + * @see IContextInformation#getContextDisplayString() + */ + public String getContextDisplayString() { + return fContextInformation.getContextDisplayString(); + } + + /* + * @see IContextInformation#getImage() + */ + public Image getImage() { + return fContextInformation.getImage(); + } + + /* + * @see IContextInformation#getInformationDisplayString() + */ + public String getInformationDisplayString() { + return fContextInformation.getInformationDisplayString(); + } + + /* + * @see IContextInformationExtension#getContextInformationPosition() + */ + public int getContextInformationPosition() { + return fPosition; + } + + public void setContextInformationPosition(int position) { + fPosition = position; + } + }; + + // private class TableName { + // String fTableName; + // + // TableName() { + // fTableName = null; + // } + // + // /** + // * @return Returns the tableName. + // */ + // public String getTableName() { + // if (fTableName == null) { + // return ""; + // } + // return fTableName; + // } + // + // /** + // * @param tableName + // * The tableName to set. + // */ + // public void setTableName(String tableName) { + // fTableName = tableName; + // } + // } + + private char[] fProposalAutoActivationSet; + + protected IContextInformationValidator fValidator = null; + + private TemplateEngine fTemplateEngine; + + private PHPCompletionProposalComparator fComparator; + + private IEditorPart fEditor; + + protected IWorkingCopyManager fManager; + + public PHPCompletionProcessor(IEditorPart editor) { + fEditor = editor; + fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); + TemplateContextType contextType = PHPeclipsePlugin.getDefault() + .getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$ + if (contextType != null) + fTemplateEngine = new TemplateEngine(contextType); + fComparator = new PHPCompletionProposalComparator(); + } + + /** + * Tells this processor to order the proposals alphabetically. + * + * @param order + * true if proposals should be ordered. + */ + public void orderProposalsAlphabetically(boolean order) { + fComparator.setOrderAlphabetically(order); + } + + /** + * Sets this processor's set of characters triggering the activation of the + * completion proposal computation. + * + * @param activationSet + * the activation set + */ + public void setCompletionProposalAutoActivationCharacters( + char[] activationSet) { + fProposalAutoActivationSet = activationSet; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int documentOffset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, documentOffset); + return internalComputeCompletionProposals(viewer, documentOffset, + contextInformationPosition); + } + + private TokenName getLastToken(List list, ITextViewer viewer, + int completionPosition, JavaContext context) { + // TableName tableName) { + IDocument document = viewer.getDocument(); + int start = context.getStart(); + // int end = context.getEnd(); + String startText; + TokenName lastSignificantToken = ITerminalSymbols.TokenName.EOF; + try { + // begin search 2 lines behind of this + int j = start; + if (j != 0) { + char ch; + while (j > 0) { + ch = document.getChar(--j); + if (ch == '\n') { + break; + } + } + while (j > 0) { + ch = document.getChar(--j); + if (ch == '\n') { + break; + } + } + } + if (j != start) { + // scan the line for the dereferencing operator '->' + startText = document.get(j, start - j); + if (Scanner.DEBUG) { + System.out.println(startText); + } + TokenName token = ITerminalSymbols.TokenName.EOF; + // token = getLastSQLToken(startText); + // tableName.setTableName(getLastSQLTableName(startText)); + Scanner scanner = ToolFactory + .createScanner(false, false, false); + scanner.setSource(startText.toCharArray()); + scanner.setPHPMode(true); + TokenName beforeLastToken = ITerminalSymbols.TokenName.EOF; + TokenName lastToken = ITerminalSymbols.TokenName.EOF; + char[] ident = null; + try { + token = scanner.getNextToken(); + lastToken = token; + while (token != ITerminalSymbols.TokenName.ERROR + && token != ITerminalSymbols.TokenName.EOF) { + beforeLastToken = lastToken; + if (token == ITerminalSymbols.TokenName.VARIABLE) { + ident = scanner.getCurrentTokenSource(); + if (ident.length == 5 && ident[0] == '$' + && ident[1] == 't' && ident[2] == 'h' + && ident[3] == 'i' && ident[4] == 's') { + token = ITerminalSymbols.TokenName.THIS_PHP_COMPLETION; + } + } + lastToken = token; + // System.out.println(scanner.toStringAction(lastToken)); + token = scanner.getNextToken(); + } + } catch (InvalidInputException e1) { + } catch (SyntaxError e) { + } + switch (lastToken) { + case MINUS_GREATER: + // dereferencing operator '->' found + lastSignificantToken = ITerminalSymbols.TokenName.MINUS_GREATER; + if (beforeLastToken == ITerminalSymbols.TokenName.VARIABLE) { + lastSignificantToken = ITerminalSymbols.TokenName.VARIABLE; + list.set(0, ident); + } else if (beforeLastToken == ITerminalSymbols.TokenName.THIS_PHP_COMPLETION) { + lastSignificantToken = ITerminalSymbols.TokenName.THIS_PHP_COMPLETION; + list.set(0, ident); + } + break; + case NEW: + lastSignificantToken = ITerminalSymbols.TokenName.NEW; + break; + } + } + } catch (BadLocationException e) { + } + return lastSignificantToken; + } + + String getSQLTableName(String sqlText, int start) { + int tableNameStart = -1; + int currentCharacterPosition = start + 1; + char ch; + try { + while (true) { + ch = sqlText.charAt(currentCharacterPosition++); + if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) { + tableNameStart = currentCharacterPosition - 1; + } else { + if (!Scanner.isPHPIdentifierPart(ch)) { + return sqlText.substring(tableNameStart, + currentCharacterPosition - 1); + } + } + } + } catch (IndexOutOfBoundsException e) { + if (tableNameStart >= 0) { + return sqlText.substring(tableNameStart, + currentCharacterPosition - 1); + } + } + return ""; + } + + // private String getLastSQLTableName(String startText) { + // // scan for sql identifiers + // char ch = ' '; + // int currentSQLPosition = startText.length(); + // int identEnd = -1; + // String ident = null; + // try { + // while (true) { + // ch = startText.charAt(--currentSQLPosition); + // if (Scanner.isSQLIdentifierPart(ch)) { + // // if (ch >= 'A' && ch <= 'Z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // // } else if (ch >= 'a' && ch <= 'z') { + // // if (identEnd < 0) { + // // identEnd = currentSQLPosition + 1; + // // } + // } else if (identEnd >= 0) { + // ident = startText.substring(currentSQLPosition + 1, identEnd); + // // select -- from -- where -- + // // update -- set -- where -- + // // insert into -- ( -- ) values ( -- ) + // if (ident.length() >= 4 && ident.length() <= 6) { + // ident = ident.toLowerCase(); + // switch (ident.length()) { + // // case 3 : + // // if (ident.equals("set")) { + // // // System.out.println("set"); + // // token = ITerminalSymbols.TokenName.SQLset; + // // return token; + // // } + // // break; + // case 4: + // if (ident.equals("from")) { + // // System.out.println("from"); + // return getSQLTableName(startText, identEnd); + // } else if (ident.equals("into")) { + // // System.out.println("into"); + // return getSQLTableName(startText, identEnd); + // } + // break; + // case 6: + // if (ident.equals("update")) { + // // System.out.println("update"); + // return getSQLTableName(startText, identEnd); + // } + // break; + // } + // } + // identEnd = -1; + // } else if (Character.isWhitespace(ch)) { + // } + // } + // } catch (IndexOutOfBoundsException e) { + // } + // return ""; + // } + + /** + * Detect the last significant SQL token in the text before the completion + * + * @param startText + */ + // private int getLastSQLToken(String startText) { + // int token; + // // scan for sql identifiers + // char ch = ' '; + // int currentSQLPosition = startText.length(); + // int identEnd = -1; + // String ident = null; + // try { + // while (true) { + // ch = startText.charAt(--currentSQLPosition); + // if (ch >= 'A' && ch <= 'Z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // } else if (ch >= 'a' && ch <= 'z') { + // if (identEnd < 0) { + // identEnd = currentSQLPosition + 1; + // } + // } else if (identEnd >= 0) { + // ident = startText.substring(currentSQLPosition + 1, identEnd); + // // select -- from -- where -- + // // update -- set -- where -- + // // insert into -- ( -- ) values ( -- ) + // if (ident.length() >= 3 && ident.length() <= 6) { + // ident = ident.toLowerCase(); + // switch (ident.length()) { + // case 3: + // if (ident.equals("set")) { + // // System.out.println("set"); + // token = ITerminalSymbols.TokenName.SQLset; + // return token; + // } + // break; + // case 4: + // if (ident.equals("from")) { + // // System.out.println("from"); + // token = ITerminalSymbols.TokenName.SQLfrom; + // // getSQLTableName(); + // return token; + // } else if (ident.equals("into")) { + // // System.out.println("into"); + // token = ITerminalSymbols.TokenName.SQLinto; + // return token; + // } + // break; + // case 5: + // if (ident.equals("where")) { + // // System.out.println("where"); + // token = ITerminalSymbols.TokenName.SQLwhere; + // return token; + // } + // break; + // case 6: + // if (ident.equals("select")) { + // // System.out.println("select"); + // token = ITerminalSymbols.TokenName.SQLselect; + // return token; + // } else if (ident.equals("insert")) { + // // System.out.println("insert"); + // token = ITerminalSymbols.TokenName.SQLinsert; + // return token; + // } else if (ident.equals("update")) { + // // System.out.println("update"); + // token = ITerminalSymbols.TokenName.SQLupdate; + // return token; + // } else if (ident.equals("values")) { + // // System.out.println("values"); + // token = ITerminalSymbols.TokenName.SQLvalues; + // return token; + // } + // break; + // } + // } + // identEnd = -1; + // } + // } + // } catch (IndexOutOfBoundsException e) { + // } + // return ITerminalSymbols.TokenName.EOF; + // } + private ICompletionProposal[] internalComputeCompletionProposals( + ITextViewer viewer, int offset, int contextOffset) { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor + .getEditorInput()); + IDocument document = viewer.getDocument(); + IFile file = null; + IProject project = null; + if (offset > 0) { + PHPEditor editor = null; + if (fEditor != null && (fEditor instanceof PHPEditor)) { + editor = (PHPEditor) fEditor; + IEditorInput editorInput = editor.getEditorInput(); + if (editorInput instanceof IFileEditorInput) { + file = ((IFileEditorInput) editorInput).getFile(); + project = file.getProject(); + } else { + return new ICompletionProposal[0]; + } + } + } + + Point selection = viewer.getSelectedRange(); + // remember selected text + String selectedText = null; + if (selection.y != 0) { + try { + selectedText = document.get(selection.x, selection.y); + } catch (BadLocationException e) { + } + } + + if (offset > 2 && fProposalAutoActivationSet != null) { + // restrict auto activation for '>' character to '->' token + + try { + char ch = document.getChar(offset - 1); + if (ch == '>') { + for (int i = 0; i < fProposalAutoActivationSet.length; i++) { + ch = fProposalAutoActivationSet[i]; + if (ch == '>') { // auto activation enabled + ch = document.getChar(offset - 2); + if (ch != '-') { + return new IPHPCompletionProposal[0]; + } + break; + } + } + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ + JavaContext context = (JavaContext) phpContextType.createContext( + document, offset, selection.y, unit); + context.setVariable("selection", selectedText); //$NON-NLS-1$ + String prefix = context.getKey(); + + HashMap methodVariables = null; + // HashMap typeVariables = null; + HashMap unitVariables = null; + ICompilationUnit compilationUnit = (ICompilationUnit) context + .findEnclosingElement(IJavaElement.COMPILATION_UNIT); + // if (compilationUnit != null) { + // unitVariables = ((CompilationUnit) compilationUnit).variables; + // } + IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE); + if (type != null) { + // typeVariables = ((SourceType) type).variables; + } + IMethod method = (IMethod) context + .findEnclosingElement(IJavaElement.METHOD); + // if (method != null) { + // methodVariables = ((SourceMethod) method).variables; + // } + + boolean emptyPrefix = prefix == null || prefix.equals(""); + IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0]; + + if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { + // php Variable ? + String lowerCasePrefix = prefix.toLowerCase(); + HashSet localVariables = new HashSet(); + if (compilationUnit != null) { + unitVariables = getUnitVariables(unitVariables, compilationUnit); + getVariableProposals(localVariables, viewer, project, context, + unitVariables, lowerCasePrefix, 94); + } + if (method != null) { + methodVariables = getMethodVariables(methodVariables, method); + getVariableProposals(localVariables, viewer, project, context, + methodVariables, lowerCasePrefix, 99); + } + if (!localVariables.isEmpty()) { + localVariableResults = (IPHPCompletionProposal[]) localVariables + .toArray(new IPHPCompletionProposal[localVariables + .size()]); + } + } + + // TableName sqlTable = new TableName(); + ArrayList list = new ArrayList(); + list.add(null); + TokenName lastSignificantToken = getLastToken(list, viewer, offset, context); // , + // sqlTable); + boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenName.MINUS_GREATER) + || (lastSignificantToken == ITerminalSymbols.TokenName.VARIABLE) + || (lastSignificantToken == ITerminalSymbols.TokenName.NEW) + || (lastSignificantToken == ITerminalSymbols.TokenName.THIS_PHP_COMPLETION); + + if (fTemplateEngine != null) { + IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0]; + ICompletionProposal[] results; + if (!emptyPrefix) { + fTemplateEngine.reset(); + fTemplateEngine.complete(viewer, offset, unit); + templateResults = fTemplateEngine.getResults(); + } + // TODO delete this + IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0]; + + // declarations stored in file project.index on project level + IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0]; + if (project != null) { + DeclarationEngine declarationEngine; + JavaContextType contextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ + if (contextType != null) { + IdentifierIndexManager indexManager = PHPeclipsePlugin + .getDefault().getIndexManager(project); + SortedMap sortedMap; + declarationEngine = new DeclarationEngine(project, + contextType, lastSignificantToken, file); + if (lastSignificantToken == ITerminalSymbols.TokenName.THIS_PHP_COMPLETION) { + // complete '$this->' + sortedMap = indexManager.getIdentifiers(file); + declarationEngine.completeObject(viewer, offset, + sortedMap, unit); + } else { + String typeRef = null; + char[] varName = (char[]) list.get(0); + if (varName != null) { + if (method != null) { + methodVariables = getMethodVariables( + methodVariables, method); + VariableInfo info = (VariableInfo) methodVariables + .get(new String(varName)); + if (info != null && info.typeIdentifier != null) { + typeRef = new String(info.typeIdentifier); + } + } + } + if (typeRef != null) { + // complete '$variable->' with type information + sortedMap = indexManager.getIdentifiers(typeRef); + declarationEngine.completeObject(viewer, offset, + sortedMap, unit); + } else { + // complete '$variable->' without type information + sortedMap = indexManager.getIdentifierMap(); + declarationEngine.complete(viewer, offset, + sortedMap, unit); + } + } + declarationResults = declarationEngine.getResults(); + } + } + // built in function names from phpsyntax.xml + ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData(); + IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0]; + if ((!useClassMembers) && syntaxbuffer != null) { + BuiltInEngine builtinEngine; + JavaContextType contextType = (JavaContextType) PHPeclipsePlugin + .getDefault().getTemplateContextRegistry() + .getContextType("php"); //$NON-NLS-1$ + if (contextType != null) { + builtinEngine = new BuiltInEngine(contextType); + builtinEngine.complete(viewer, offset, syntaxbuffer, unit); + builtinResults = builtinEngine.getResults(); + } + } + // ICompletionProposal[] sqlResults = new ICompletionProposal[0]; + // if (project != null) { + // sqlResults = getSQLProposals(viewer, project, context, prefix, + // sqlTable); + // } + // concatenate the result arrays + IPHPCompletionProposal[] total; + total = new IPHPCompletionProposal[localVariableResults.length + + templateResults.length + identifierResults.length + + builtinResults.length + declarationResults.length];// + + // sqlResults.length]; + System.arraycopy(templateResults, 0, total, 0, + templateResults.length); + System.arraycopy(identifierResults, 0, total, + templateResults.length, identifierResults.length); + System.arraycopy(builtinResults, 0, total, templateResults.length + + identifierResults.length, builtinResults.length); + System.arraycopy(declarationResults, 0, total, + templateResults.length + identifierResults.length + + builtinResults.length, declarationResults.length); + // System.arraycopy(sqlResults, 0, total, templateResults.length + + // identifierResults.length + builtinResults.length + // + declarationResults.length, sqlResults.length); + // System.arraycopy(localVariableResults, 0, total, + // templateResults.length + // + identifierResults.length + builtinResults.length + // + declarationResults.length + sqlResults.length, + // localVariableResults.length); + System + .arraycopy(localVariableResults, 0, total, + templateResults.length + identifierResults.length + + builtinResults.length + + declarationResults.length, + localVariableResults.length); + results = total; + // fNumberOfComputedResults = (results == null ? 0 : + // results.length); + /* + * Order here and not in result collector to make sure that the + * order applies to all proposals and not just those of the + * compilation unit. + */ + return order(results); + } + return new IPHPCompletionProposal[0]; + } + + /** + * @param unitVariables + * @param unit + */ + private HashMap getUnitVariables(HashMap unitVariables, + ICompilationUnit unit) { + if (unitVariables == null) { + try { + String unitText = unit.getSource(); + unitVariables = new HashMap(); + + ProblemReporter problemReporter = new ProblemReporter( + DefaultErrorHandlingPolicies.exitAfterAllProblems(), + new CompilerOptions(JavaCore.getOptions()), + new DefaultProblemFactory()); + UnitParser parser = new UnitParser(problemReporter); + parser.compilationUnit = new CompilationUnitDeclaration( + problemReporter, null, unitText.length()); + parser.parse(unitText, unitVariables); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + PHPeclipsePlugin.log(e); + } + } + return unitVariables; + } + + /** + * @param methodVariables + * @param method + */ + private HashMap getMethodVariables(HashMap methodVariables, IMethod method) { + if (methodVariables == null) { + try { + String methodText = method.getSource(); + methodVariables = new HashMap(); + ProblemReporter problemReporter = new ProblemReporter( + DefaultErrorHandlingPolicies.exitAfterAllProblems(), + new CompilerOptions(JavaCore.getOptions()), + new DefaultProblemFactory()); + UnitParser parser = new UnitParser(problemReporter); + parser.compilationUnit = new CompilationUnitDeclaration( + problemReporter, null, methodText.length()); + parser.parseFunction(methodText, methodVariables); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + PHPeclipsePlugin.log(e); + } + } + return methodVariables; + } + + /** + * @param viewer + * @param project + * @param context + * @param prefix + * @return + */ + private void getVariableProposals(HashSet localVariables, + ITextViewer viewer, IProject project, JavaContext context, + HashMap variables, String prefix, int relevance) { + // try { + int start = context.getStart(); + int end = context.getEnd(); + IRegion region = new Region(start, end - start); + // IMethod method = (IMethod) + // context.findEnclosingElement(IJavaElement.METHOD); + // if (method != null && (method instanceof SourceMethod) && + // ((SourceMethod) + // method).variables != null) { + // HashMap map = ((SourceMethod) method).variables; + Set set = variables.keySet(); + Iterator iter = set.iterator(); + String varName; + boolean matchesVarName; + while (iter.hasNext()) { + varName = (String) iter.next(); + if (varName.length() >= prefix.length()) { + matchesVarName = true; + for (int i = 0; i < prefix.length(); i++) { + if (prefix.charAt(i) != Character.toLowerCase(varName + .charAt(i))) { + matchesVarName = false; + break; + } + } + if (matchesVarName) { + LocalVariableProposal prop; + // if (varName.length == prefix.length()) { + // prop = new LocalVariableProposal(new String(varName), + // region, + // viewer, relevance-10); + // } else { + prop = new LocalVariableProposal(new String(varName), + region, viewer, relevance); + // } + localVariables.add(prop); + } + } + } + // } + + // char[] varName; + // boolean matchesVarName; + // if (method != null) { + // ISourceRange range = method.getSourceRange(); + // char[] source = method.getSource().toCharArray(); + // Scanner scanner = new Scanner(); + // scanner.setSource(source); + // scanner.phpMode = true; + // int token = Scanner.TokenName.WHITESPACE; + // while ((token = scanner.getNextToken()) != Scanner.TokenName.EOF) { + // if (token == Scanner.TokenName.Variable) { + // varName = scanner.getCurrentTokenSource(); + // if (varName.length >= prefix.length()) { + // matchesVarName = true; + // for (int i = 0; i < prefix.length(); i++) { + // if (prefix.charAt(i) != varName[i]) { + // matchesVarName = false; + // break; + // } + // } + // if (matchesVarName) { + // LocalVariableProposal prop = new LocalVariableProposal(new + // String(varName), region, viewer); + // if (varName.length == prefix.length()) { + // prop.setRelevance(98); + // } + // localVariables.add(prop); + // } + // } + // } + // } + // } + // } catch (Throwable e) { + // // ignore - Syntax exceptions could occur, if there are syntax errors + // ! + // } + } + + /** + * @param viewer + * @param project + * @param context + * @param prefix + * @param sqlTable + * @param sqlResults + * @return + */ + // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, + // IProject + // project, DocumentTemplateContext context, + // String prefix, TableName sqlTable) { + // ICompletionProposal[] sqlResults = new ICompletionProposal[0]; + // // Get The Database bookmark from the Quantum SQL plugin: + // // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance(); + // // if (sqlBookMarks != null) { + // String bookmarkString = + // ProjectPrefUtil.getMiscProjectsPreferenceValue(project, + // IPreferenceConstants.PHP_BOOKMARK_DEFAULT); + // if (bookmarkString != null && !bookmarkString.equals("")) { + // String[] bookmarks = ExternalInterface.getBookmarkNames(); + // boolean foundBookmark = false; + // for (int i = 0; i < bookmarks.length; i++) { + // if (bookmarks[i].equals(bookmarkString)) { + // foundBookmark = true; + // } + // } + // if (!foundBookmark) { + // return sqlResults; + // } + // // Bookmark bookmark = sqlBookMarks.find(bookmarkString); + // ArrayList sqlList = new ArrayList(); + // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) { + // ExternalInterface.connectBookmark(bookmarkString, null); + // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) { + // return sqlResults; + // } + // } + // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) { + // try { + // int start = context.getStart(); + // int end = context.getEnd(); + // String foundSQLTableName = sqlTable.getTableName(); + // String tableName; + // String columnName; + // String prefixWithoutDollar = prefix; + // boolean isDollarPrefix = false; + // if (prefix.length() > 0 && prefix.charAt(0) == '$') { + // prefixWithoutDollar = prefix.substring(1); + // isDollarPrefix = true; + // } + // IRegion region = new Region(start, end - start); + // ResultSet set; + // if (!isDollarPrefix) { + // String[] tableNames = ExternalInterface.getMatchingTableNames(null, + // bookmarkString, prefixWithoutDollar, null, false); + // for (int i = 0; i < tableNames.length; i++) { + // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer, + // PHPUiImages.get(PHPUiImages.IMG_TABLE))); + // } + // } + // + // String[] columnNames = ExternalInterface.getMatchingColumnNames(null, + // bookmarkString, prefixWithoutDollar, null, false); + // for (int i = 0; i < columnNames.length; i++) { + // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer, + // PHPUiImages.get(PHPUiImages.IMG_TABLE))); + // } + // + // sqlResults = new IPHPCompletionProposal[sqlList.size()]; + // for (int i = 0; i < sqlList.size(); i++) { + // sqlResults[i] = (SQLProposal) sqlList.get(i); + // } + // } catch (Exception /* NotConnectedException */ e) { + // + // } + // // } + // } + // // } + // return sqlResults; + // } + private boolean looksLikeMethod(PHPCodeReader reader) throws IOException { + int curr = reader.read(); + while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr)) + curr = reader.read(); + + if (curr == PHPCodeReader.EOF) + return false; + + return Scanner.isPHPIdentifierPart((char) curr); + } + + private int guessContextInformationPosition(ITextViewer viewer, int offset) { + int contextPosition = offset; + IDocument document = viewer.getDocument(); + try { + + PHPCodeReader reader = new PHPCodeReader(); + reader.configureBackwardReader(document, offset, true, true); + + int nestingLevel = 0; + + int curr = reader.read(); + while (curr != PHPCodeReader.EOF) { + + if (')' == (char) curr) + ++nestingLevel; + + else if ('(' == (char) curr) { + --nestingLevel; + + if (nestingLevel < 0) { + int start = reader.getOffset(); + if (looksLikeMethod(reader)) + return start + 1; + } + } + + curr = reader.read(); + } + } catch (IOException e) { + } + return contextPosition; + } + + /** + * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) + */ + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + int contextInformationPosition = guessContextInformationPosition( + viewer, offset); + List result = addContextInformations(viewer, contextInformationPosition); + return (IContextInformation[]) result + .toArray(new IContextInformation[result.size()]); + } + + private List addContextInformations(ITextViewer viewer, int offset) { + ICompletionProposal[] proposals = internalComputeCompletionProposals( + viewer, offset, -1); + List result = new ArrayList(); + for (int i = 0; i < proposals.length; i++) { + IContextInformation contextInformation = proposals[i] + .getContextInformation(); + if (contextInformation != null) { + ContextInformationWrapper wrapper = new ContextInformationWrapper( + contextInformation); + wrapper.setContextInformationPosition(offset); + result.add(wrapper); + } + } + return result; + } + + /** + * Order the given proposals. + */ + private ICompletionProposal[] order(ICompletionProposal[] proposals) { + Arrays.sort(proposals, fComparator); + // int len = proposals.length; + // if (len > 10) { + // len = 10; + // } + // for (int i = 0; i < len; i++) { + // System.out.println(proposals[i].getDisplayString()); + // } + return proposals; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public char[] getCompletionProposalAutoActivationCharacters() { + return fProposalAutoActivationSet; + // return null; // new char[] { '$' }; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public char[] getContextInformationAutoActivationCharacters() { + return null; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public IContextInformationValidator getContextInformationValidator() { + if (fValidator == null) + fValidator = new JavaParameterListValidator(); + return fValidator; + } + + /* + * (non-Javadoc) Method declared on IContentAssistProcessor + */ + public String getErrorMessage() { + return null; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java new file mode 100644 index 0000000..29b5d5d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDocumentPartitioner.java @@ -0,0 +1,97 @@ +/********************************************************************** + Copyright (c) 2002 Widespace, OU and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://solareclipse.sourceforge.net/legal/cpl-v10.html + + Contributors: + Igor Malinin - initial contribution + + $Id: PHPDocumentPartitioner.java,v 1.6 2006-10-21 23:18:33 pombredanne Exp $ + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor.php; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.ui.text.rules.FlatNode; +import net.sourceforge.phpeclipse.ui.text.rules.MultiViewPartitioner; +import net.sourceforge.phpeclipse.ui.text.rules.ViewNode; +import net.sourceforge.phpeclipse.xml.ui.text.XMLTextTools; + +//incastrix +//import org.eclipse.jface.text.Assert; +import org.eclipse.core.runtime.Assert; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentPartitioner; +import org.eclipse.jface.text.rules.IPartitionTokenScanner; + +/** + * + * + * @author Igor Malinin + */ +public class PHPDocumentPartitioner extends MultiViewPartitioner { + public static final String PHP_TEMPLATE_DATA = "__php_template_data"; + + public static final String PHP_SCRIPT_CODE = "__php_script_code"; + + public static final String[] LEGAL_TYPES = { PHP_TEMPLATE_DATA, + PHP_SCRIPT_CODE }; + + public PHPDocumentPartitioner(IPartitionTokenScanner scanner) { + super(scanner); + } + + protected FlatNode createNode(String type, int offset, int length) { + if (type.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { + if (DEBUG) { + Assert.isTrue(offset >= 0); + } + ViewNode node = new ViewNode(type); + node.offset = offset; + node.length = length; + return node; + } + + return super.createNode(type, offset, length); + } + + /* + * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#createPartitioner(String) + */ + protected IDocumentPartitioner createPartitioner(String contentType) { + if (contentType == null) { + // return JavaTextTools.createHTMLPartitioner(); + return PHPeclipsePlugin.getDefault().getJavaTextTools() + .getXMLTextTools().createPHPXMLPartitioner(); + } + + if (contentType.equals(PHPPartitionScanner.PHP_SCRIPTING_AREA)) { + return PHPeclipsePlugin.getDefault().getJavaTextTools() + .createPHPPartitioner(); + } + return null; + } + + /* + * @see net.sf.solareclipse.text.rules.DocumentViewPartitioner#getContentType(String, + * String) + */ + protected String getContentType(String parent, String view) { + if (parent == null) { + if (view == IDocument.DEFAULT_CONTENT_TYPE) { + return PHP_TEMPLATE_DATA; + } + } else { + if (view == IDocument.DEFAULT_CONTENT_TYPE) { + return PHP_SCRIPT_CODE; + } + } + + return super.getContentType(parent, view); + } + + public String[] getLegalContentTypes() { + return LEGAL_TYPES; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPDoubleClickSelector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPEditorMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPPartitionScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPWordExtractor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyCodeScanner.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/SmartyDocCodeScanner.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml new file mode 100644 index 0000000..9f1a1c0 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/syntax.xml @@ -0,0 +1,6638 @@ + + +Returns the sum of two arbitrary precision numbers +Compares two arbitrary precision numbers +Returns the quotient of two arbitrary precision numbers (division) +Returns the modulus of the two arbitrary precision operands +Returns the multiplication of two arbitrary precision numbers +Returns the value of an arbitrary precision number raised to the power of another +Returns the value of an arbitrary precision number raised to the power of another reduced by a modulous +Sets default scale parameter for all bc math functions +Returns the square root of an arbitray precision number +Returns the difference between two arbitrary precision numbers +Compresses a string into BZip2 encoded data +Decompresses BZip2 compressed data +Returns the error number +Returns the error number and error string in an associative array +Returns the error string +Opens a new BZip2 stream +Reads up to length bytes from a BZip2 stream, or 1024 bytes if length is not specified +Convert Julian Day to UNIX timestamp +Convert UNIX timestamp to Julian Day +Returns the number of days in a month for a given year and calendar +Converts from Julian Day Count to a supported calendar and return extended information +Returns information about a particular calendar +Converts from a supported calendar to Julian Day Count +Converts a french republic calendar date to julian day count +Converts a gregorian calendar date to julian day count +Returns name or number of day of week from julian day count +Returns name of month for julian day count +Converts a julian day count to a french republic calendar date +Converts a julian day count to a gregorian calendar date +Converts a julian day count to a jewish calendar date +Convert a julian day count to a julian calendar date +Converts a jewish calendar date to a julian day count +Converts a julian calendar date to julian day count +Return the timestamp of midnight on Easter of a given year (defaults to current year) +Return the number of days after March 21 that Easter falls on for a given year (defaults to current year) +Generate a globally unique identifier (GUID) +Connect events from a COM object to a PHP object +Returns a handle to an already running instance of a COM object +Loads a Typelibrary and registers its constants +Process COM messages, sleeping for up to timeoutms milliseconds +Print out a PHP class definition for a dispatchable interface +Determines the filename into which an object will be saved, or false if none is set, via IPersistFile::GetCurFile +Gets maximum stream size required to store the object data, via IPersistStream::GetSizeMax (or IPersistStreamInit::GetSizeMax) +Initializes the object to a default state, via IPersistStreamInit::InitNew +Load object data from file, via IPersistFile::Load +Initializes an object from the stream where it was previously saved, via IPersistStream::Load or OleLoadFromStream +Persist object data to file, via IPersistFile::Save +Saves the object to a stream, via IPersistStream::Save +Creates a persistence helper object, usually associated with a com_object +Returns the absolute value of a variant +"Adds" two variant values together and returns the result +performs a bitwise AND operation between two variants and returns the result +Convert a variant into a new variant object of another type +concatenates two variant values together and returns the result +Compares two variants +Returns a variant date representation of a unix timestamp +Converts a variant date/time value to unix timestamp +Returns the result from dividing two variants +Performs a bitwise equivalence on two variants +Returns the integer part ? of a variant +Returns the VT_XXX type code for a variant +Converts variants to integers and then returns the result from dividing them +Performs a bitwise implication on two variants +Returns the integer portion of a variant +Divides two variants and returns only the remainder +multiplies the values of the two variants and returns the result +Performs logical negation on a variant +Performs bitwise not negation on a variant +Performs a logical disjunction on two variants +Returns the result of performing the power function with two variants +Rounds a variant to the specified number of decimal places +Assigns a new value for a variant object +Convert a variant into another type. Variant is modified "in-place" +subtracts the value of the right variant from the left variant value and returns the result +Performs a logical exclusion on two variants +Checks for alphanumeric character(s) +Checks for alphabetic character(s) +Checks for control character(s) +Checks for numeric character(s) +Checks for any printable character(s) except space +Checks for lowercase character(s) +Checks for printable character(s) +Checks for any printable character which is not whitespace or an alphanumeric character +Checks for whitespace character(s) +Checks for uppercase character(s) +Checks for character(s) representing a hexadecimal digit +Close a cURL session +Copy a cURL handle along with all of it's preferences +Return an integer containing the last error number +Return a string contain the last error for the current session +Perform a cURL session +Get information regarding a specific transfer +Initialize a cURL session +Set an option for a cURL transfer +Set an array of option for a cURL transfer +Return cURL version information. +Add a normal cURL handle to a cURL multi handle +Close a set of cURL handles +Run the sub-connections of the current cURL handle +Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set +Get information about the current transfers +Returns a new cURL multi handle +Remove a multi handle from a set of cURL handles +Get all the sockets associated with the cURL extension, which can then be "selected" +Returns true(1) if it is a valid date in gregorian calendar +Format a local date/time +Returns new DateTime object +Sets the date. +Gets the default timezone used by all date/time functions in a script +Sets the default timezone used by all date/time functions in a script +Returns date formatted according to given format + +Sets the ISO date. +Alters the timestamp. +Returns the DST offset. +Returns associative array with detailed info about given date +Returns an array with information about sun set/rise and twilight begin/end +Returns time of sunrise for a given day and location +Returns time of sunset for a given day and location +Sets the time. +Return new DateTimeZone object relative to give DateTime +Sets the timezone for the DateTime object. +Get date/time information +Format a GMT date/time +Get UNIX timestamp for a GMT date +Format a GMT/UCT time/date according to locale settings +Format a local time/date as integer +Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array +Get UNIX timestamp for a date +Format a local time/date according to locale settings +Convert string representation of date and time to a timestamp +Return current UNIX timestamp +Creates new DateTime object +Creates new DateTimeZone object. +Returns associative array containing dst, offset and the timezone name +Returns numerically index array with all timezone identifiers. +Returns the timezone name from abbrevation +Returns the name of the timezone. +Returns the timezone offset. +Returns new DateTimeZone object +Returns numeracilly indexed array containing associative array for all transitions for the timezone. +Closes database +Deletes the entry associated with key If inifile: remove all other key lines +Checks, if the specified key exists +Fetches the data associated with key +Resets the internal key pointer and returns the first key +List configured database handlers +If not inifile: Insert value as key, return false, if key exists already If inifile: Add vakue as key (next instance of key) +List opened databases +Returns the next key +Opens path using the specified handler in mode +Optimizes (e.g. clean up, vacuum) database +Opens path using the specified handler in mode persistently +Inserts value as key, replaces key, if key exists already If inifile: remove all other key lines +Synchronizes database +Adds a record to the database +Closes an open dBase-format database file +Creates a new dBase-format database file +Marks a record to be deleted + +Returns an array representing a record from the database +Returns an associative array representing a record from the database +Returns the number of fields (columns) in the database +Returns the number of records in the database +Opens a dBase-format database file +Packs the database (deletes records marked for deletion) +Replaces a record to the database +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Attr-isId Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-32791A2F Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-7C603781 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3EDB695F Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-E5CBA7FB Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6531BCCF Since: +Register extended class used to create base node type +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-adoptNode Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1084891198 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrAttrNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D26C0AF8 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1334481328 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-35CB04B5 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-2141741547 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-DocCrElNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-392B75AE Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-135944439 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1975348127 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBId Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C9094 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getElBTNNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Core-Document-importNode Since: DOM Level 2 +URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load Since: DOM Level 3 +Since: DOM extended +Since: DOM extended +URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3 +Convenience method to save to file +Convenience method to output as html +Convenience method to save to file as html +URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3 +Since: DOM extended +Substitutues xincludes in a DomDocument +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-canSetParameter Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-getParameter Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocument Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocType Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementation3-getFeature Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-5CED94D7 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList-item Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpl Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpls Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMStringList-item Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-666EE0F9 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-217A91B8 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAtNodeNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAttrNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1938918D Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C90942 Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttr Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttrNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6D6AC0F9 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D589198 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElRemAtNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-F68F082 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-887236154 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAtNodeNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAttrNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttr Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNode Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNS Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1074577549 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getNamedItemNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-349467F9 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D58B193 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-removeNamedItemNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1025163788 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-setNamedItemNS Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getName Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getNamespaceURI Since: +Canonicalize nodes to a string +Canonicalize nodes to a file +Gets an xpath for a node +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-184E7107 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3A0ED0A4 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-compareDocumentPosition Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getFeature Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getUserData Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-NodeHasAttrs Since: DOM Level 2 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-810594187 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-952280727 Since: +URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isEqualNode Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isSameNode Since: DOM Level 3 +URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-lookupNamespacePrefix Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-normalize Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1734834066 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-785887307 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-setUserData Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-844377136 Since: +Get a simplexml_element object from dom to allow for processing +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset16 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset32 Since: +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-isWhitespaceInElementContent Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-replaceWholeText Since: DOM Level 3 +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-38853C1D Since: +Get the type of an image +Reads header data from the JPEG/TIFF image filename and optionally reads the internal thumbnails +Get headername for index or false if not defined +Reads the embedded thumbnail +Get the number of rows affected by the last statement +Turns on auto-commit +Get the size of a BLOB identified by blob_handle +Change the user for a session +Get the size of a CLOB identified by clob_handle +Close a connection to a database server +Commit the transaction +Create a connection to a database server +Create a BLOB in the database for use with an insert or update statement +Create a CLOB in the database for use with an insert or update statement +Create a new database on the server +Move the internal row counter to the specified row_number +Get or set the database name used with a connection +Get or set the databsae password used with a connection +Send one or more SQL statements to a specified database on the server +Gets the status (Stopped, Starting, Running, Stopping) for a given database +Drop a database on the server +Returns the last error code +Returns the last error string +Fetches a result row as an array (associative, numeric or both) +Detch a row of data. Returns an assoc array +Get the field properties for a specified field_index +Returns an array of the lengths of each column in the result set +Fetch a row of data. Returns an object +Fetch a row of data. Returns an indexed array +??? +Get the column length for a specified field_index +Get the column name for a specified field_index +??? +Get the table name for a specified field_index +Get the field type for a specified field_index +free the memory used to store a result +??? +Get or set the host name used with a connection +Get the internal index for the last insert statement +Retreive a list of all databases on the server +Retrieve a list of all fields for the specified database.table +Retreive a list of all tables from the specifoied database +Switch to the next result if multiple results are available +Get number of fields in the result set +Get number of rows +Get or set the user password used with a connection +Create a persistant connection to a database server +Send one or more SQL statements to the server and execute them +Read the BLOB data identified by blob_handle +Read the CLOB data identified by clob_handle +??? +Rollback all statments since last commit +Get the number of rows affected by the last statement +Select the database to open +Change input/output character set +Sets the mode for how LOB data re retreived (actual data or a handle) +Change the password for a given user +Sets the transaction locking and isolation +Start a database on the server +Stop a database on the server +Retreive the table name for index after a call to fbsql_list_tables() +Get or set the host user used with a connection +Enable or disable FrontBase warnings +Add javascript code to the fdf file +Adds a template into the FDF document +Closes the FDF document +Creates a new FDF document +Call a user defined function for each document value +Gets error code for last operation +Gets error description for error code +Gets the appearance of a field and creates a PDF document out of it. +Get attached uploaded file +Gets FDF file encoding scheme +Gets the value of /F key +Gets the flags of a field +Gets a value from the opt array of a field +Gets the value of /Status key +Gets the value of a field as string +Gets version number for FDF api or file +Set FDF specific HTTP headers +Gets the name of the next field name or the first field name +Opens a new FDF document +Opens a new FDF document from string +Sets target frame for form +Writes out the FDF file +Returns the FDF file as a string +Sets the appearence of a field +Sets FDF encoding (either "Shift-JIS" or "Unicode") +Sets the value of /F key +Sets flags for a field in the FDF document +Sets the javascript action for a field +Adds javascript code to be executed when Acrobat opens the FDF +Sets a value in the opt array for a field +Sets the value of /Status key +Sets the submit form action for a field +Sets target frame for form +Sets the value of a field +Sets FDF version for a file +* Returns true if the variable with the name 'name' exists in source. +* Returns the filtered variable 'name'* from source `type`. +* Returns an array with all arguments defined in 'definition'. +* Returns the filtered version of the vriable. +* Returns an array with all arguments defined in 'definition'. +* Returns the filter ID belonging to a named filter +Attempt to allocate space on the remote FTP server +Changes to the parent directory +Changes directories +Sets permissions on a file +Closes the FTP stream +Opens a FTP stream +Deletes a file +Requests execution of a program on the FTP server +Retrieves a file from the FTP server and writes it to an open file +Stores a file from an open file to the FTP server +Retrieves a file from the FTP server and writes it to a local file +Gets an FTP option +Logs into the FTP server +Returns the last modification time of the file, or -1 on error +Creates a directory and returns the absolute path for the new directory or false on error +Continues retrieving/sending a file nbronously +Retrieves a file from the FTP server asynchronly and writes it to an open file +Stores a file from an open file to the FTP server nbronly +Retrieves a file from the FTP server nbhronly and writes it to a local file +Stores a file on the FTP server +Returns an array of filenames in the given directory +Turns passive mode on or off +Stores a file on the FTP server +Returns the present working directory +Sends a literal command to the FTP server +Returns a detailed listing of a directory as an array of output lines +Renames the given file to a new path +Removes a directory +Sets an FTP option +Sends a SITE command to the server +Returns the size of the file, or -1 on error +Opens a FTP-SSL stream +Returns the system type identifier + +Output WBMP image to browser or file +Turn alpha blending mode on or off for the given image +Should antialiased functions used or not +Draw a partial ellipse +Draw a character +Draw a character rotated 90 degrees counter-clockwise +Allocate a color for an image +Allocate a color with an alpha level. Works for true color and palette based images +Get the index of the color of a pixel +Get the index of the closest color to the specified color +Find the closest matching colour with alpha transparency +Get the index of the color which has the hue, white and blackness nearest to the given color +De-allocate a color for an image +Get the index of the specified color +Find exact match for colour with transparency +Makes the colors of the palette version of an image more closely match the true color version +Get the index of the specified color or its closest possible alternative +Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images +Set the color for the specified palette index +Get the colors for an index +Find out the number of colors in an image's palette +Define a color as transparent +Apply a 3x3 convolution matrix, using coefficient div and offset +Copy part of an image +Merge one part of an image with another +Merge one part of an image with another +Copy and resize part of an image using resampling to help ensure clarity +Copy and resize part of an image +Create a new image +Create a new image from GD file or URL +Create a new image from GD2 file or URL +Create a new image from a given part of GD2 file or URL +Create a new image from GIF file or URL +Create a new image from JPEG file or URL +Create a new image from PNG file or URL +Create a new image from the image stream in the string +Create a new image from WBMP file or URL +Create a new image from XBM file or URL +Create a new image from XPM file or URL +Create a new true color image +Draw a dashed line +Destroy an image +Draw an ellipse +Flood fill +Draw a filled partial ellipse +Draw an ellipse +Draw a filled polygon +Draw a filled rectangle +Flood fill to specific color +Applies Filter an image using a custom angle +Get font height +Get font width +Give the bounding box of a text using fonts via freetype2 +Write text to the image using fonts via freetype2 +Apply a gamma correction to a GD image +Output GD image to browser or file +Output GD2 image to browser or file +Output GIF image to browser or file +Grab a screenshot +Grab a window or its client area using a windows handle (HWND property in COM instance) +Enable or disable interlace +return true if the image uses truecolor +Output JPEG image to browser or file +Set the alpha blending flag to use the bundled libgd layering effects +Draw a line +Load a new font +Copy the palette from the src image onto the dst image +Output PNG image to browser or file +Draw a polygon +Return the bounding box needed by a string if rasterized +Make a copy of a font for purposes like extending or reenconding +To change a fonts character encoding vector +Extend or or condense (if extend < 1) a font +Free memory used by a font +Load a new font from specified file +Slant a font +Rasterize a string over an image +Draw a rectangle +Rotate an image using a custom angle +Include alpha channel to a saved image +Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color +Set a single pixel +Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. +Set line thickness for drawing lines, ellipses, rectangles, polygons etc. +Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color +Draw a string horizontally +Draw a string vertically - rotated 90 degrees counter-clockwise +Get image width +Get image height +Convert a true colour image to a palette based image with a number of colours, optionally using dithering. +Give the bounding box of a text using TrueType fonts +Write text to the image using a TrueType font +Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM +Output WBMP image to browser or file +Output XBM image to browser or file +Bind to the text domain domain_name, looking for translations in dir. Returns the current domain +Return the translation of msgid for domain_name and category, or msgid unaltered if a translation does not exist +Return the translation of msgid for domain_name, or msgid unaltered if a translation does not exist +Return the translation of msgid for the current domain, or msgid unaltered if a translation does not exist +Plural version of gettext() +Set the textdomain to "domain". Returns the current domain +Calculates absolute value +Add a and b +Calculates logical AND of a and b +Clears bit in a +Compares two numbers +Calculates one's complement of a +Divide a by b, returns quotient only +Divide a by b, returns quotient and reminder +Divide a by b, returns reminder only +Divide a by b using exact division algorithm +Calculates factorial function +Computes greatest common denominator (gcd) of a and b +Computes G, S, and T, such that AS + BT = G = `gcd' (A, B) +Calculates hamming distance between a and b +Initializes GMP number +Gets signed long value of GMP number +Computes the inverse of a modulo b +Computes Jacobi symbol +Computes Legendre symbol +Computes a modulo b +Multiply a and b +Negates a number +Finds next prime of a +Calculates logical OR of a and b +Checks if a is an exact square +Calculates the population count of a +Raise base to power exp +Raise base to power exp and take result modulo mod +Checks if a is "probably prime" +Gets random number +Finds first zero bit +Finds first non-zero bit +Sets or clear bit in a +Gets the sign of the number +Takes integer part of square root of a +Square root with remainder +Gets string representation of GMP number +Subtract b from a +Tests if bit is set in a +Calculates logical exclusive OR of a and b +Generate a hash of a given input string Returns lowercase hexits by default +Return a list of registered hashing algorithms +Generate a hash of a given file Returns lowercase hexits by default +Output resulting digest +Generate a hash of a given input string with a key using HMAC Returns lowercase hexits by default +Generate a hash of a given file with a key using HMAC Returns lowercase hexits by default +Initialize a hashing context +Pump data into the hashing algorithm +Pump data into the hashing algorithm from a file +Pump data into the hashing algorithm from an open stream +Returns str converted to the out_charset character set +Get internal encoding and output encoding for ob_iconv_handler() +Decodes a mime header field +Decodes multiple mime header fields +Composes a mime header field with field_name and field_value in a specified scheme +Sets internal encoding and output encoding for ob_iconv_handler() +Returns the character count of str +Finds position of first occurrence of needle within part of haystack beginning with offset +Finds position of last occurrence of needle within part of haystack beginning with offset +Returns specified part of a string +Convert an 8-bit string to a quoted-printable string +Returns an array of all IMAP alerts that have been generated since the last page load or since the last imap_alerts() call, whichever came last. The alert stack is cleared after imap_alerts() is called. +Append a new message to a specified mailbox +Decode BASE64 encoded text +Convert an 8bit string to a base64 string +Read the message body +Read the structure of a specified body section of a specific message +Get mailbox properties +Clears flags on messages +Close an IMAP stream +Create a new mailbox +Mark a message for deletion +Delete a mailbox +Returns an array of all IMAP errors generated since the last page load, or since the last imap_errors() call, whichever came last. The error stack is cleared after imap_errors() is called. +Permanently delete all messages marked for deletion +Read an overview of the information in the headers of the given message sequence +Get a specific body section +Get the full unfiltered header for a message +Read the full structure of a message +Returns the quota set to the mailbox account qroot +Returns the quota set to the mailbox account mbox +Gets the ACL for a given mailbox +Reads the list of mailboxes and returns a full array of objects containing name, attributes, and delimiter +Return a list of subscribed mailboxes, in the same format as imap_getmailboxes() +Read the headers of the message +Returns headers for all messages in a mailbox +Returns the last error that was generated by an IMAP function. The error stack is NOT cleared after this call. +Read the list of mailboxes +Return a list of subscribed mailboxes +Send an email message +Create a MIME message based on given envelope and body sections +Copy specified message to a mailbox +Move specified message to a mailbox +Returns info about the current mailbox +Decode mime header element in accordance with RFC 2047 and return array of objects containing 'charset' encoding and decoded 'text' +Get the sequence number associated with a UID +Gives the number of messages in the current mailbox +Gives the number of recent messages in current mailbox +Open an IMAP stream to a mailbox +Check if the IMAP stream is still active +Convert a quoted-printable string to an 8-bit string +Rename a mailbox +Reopen an IMAP stream to a new mailbox +Parses an address string +Parse a set of mail headers contained in a string, and return an object similar to imap_headerinfo() +Returns a properly formatted email address given the mailbox, host, and personal info +Save a specific body section to a file +Read list of mailboxes containing a certain string +Return a list of messages matching the given criteria +Will set the quota for qroot mailbox +Sets the ACL for a given mailbox +Sets flags on messages +Sort an array of message headers, optionally including only messages that meet specified criteria. +Get status info from a mailbox +Subscribe to a mailbox +Return threaded by REFERENCES tree +Set or fetch imap timeout +Get the unique message id associated with a standard sequential message number +Remove the delete flag from a message +Unsubscribe from a mailbox +Decode a modified UTF-7 string +Encode a string in modified UTF-7 +Convert a mime-encoded text to UTF-8 +Add data into created blob +Cancel creating blob +Close blob +Create blob for adding data +Output blob contents to browser +Get len bytes data from open blob +Create blob, copy file in it, and close it +Return blob length and other useful info +Open blob for retrieving data parts +Frees the event handler set by ibase_set_event_handler() +Register the callback for handling each of the named events +Waits for any one of the passed Interbase events to be posted by the database, and returns its name +Returns the number of rows affected by the previous INSERT, UPDATE or DELETE statement +Execute a previously prepared query +Fetch a row from the results of a query +Fetch a object from the results of a query +Fetch a row from the results of a query +Get information about a field +Free memory used by a query +Free the memory used by a result +Assign a name to a result for use with ... WHERE CURRENT OF <name> statements +Get the number of fields in result +Get the number of params in a prepared query +Return the number of rows that are available in a result +Get information about a parameter +Prepare a query for later execution +Execute a query +Add a user to security database +Initiates a backup task in the service manager and returns immediately +Request statistics about a database +Delete a user from security database +Execute a maintenance command on the database server +Modify a user in security database +Initiates a restore task in the service manager and returns immediately +Request information about a database server +Connect to the service manager +Disconnect from the service manager +Close an InterBase connection +Commit transaction +Commit transaction and retain the transaction context +Open a connection to an InterBase database +Drop an InterBase database +Return error code +Return error message +Increments the named generator and returns its new value +Open a persistent connection to an InterBase database +Rollback transaction +Rollback transaction and retain the transaction context +Start a transaction over one or several databases +Decodes the JSON representation into a PHP value +Returns the JSON representation of a value +Translate 8859 characters to t61 characters +Add entries to LDAP directory +Bind to LDAP directory +Determine if an entry has a specific value for one of its attributes +Connect to an LDAP server +Count the number of entries in a search result +Delete an entry from a directory +Convert DN to User Friendly Naming format +Convert error number to error string +Get the current ldap error number +Get the current ldap error string +Splits DN into its component parts +Return first attribute +Return first result id +Return first reference +Free result memory +Get attributes from a search result entry +Get the DN of a result entry +Get all result entries +Get the current value of various session-wide parameters +Get all values with lengths from a result entry +Single-level search +Add attribute values to current +Delete attribute values +Replace attribute values with new ones +Get the next attribute in result +Get next result entry +Get next reference +Extract information from reference entry +Extract information from result +Read an entry +Bind to LDAP directory using SASL +Search LDAP tree under base_dn +Set the value of various session-wide parameters +Set a callback function to do re-binds on referral chasing. +Sort LDAP result entries +Start TLS +Translate t61 characters to 8859 characters +Unbind from LDAP directory +Clear last error from libxml +Retrieve array of errors +Retrieve last error from libxml +Set the streams context for the next libxml document load or write +Disable libxml errors and allow user to fetch error information as needed +Check if the string is valid for the specified encoding +Returns a case-folded version of sourcestring +Returns converted string in desired encoding +Conversion between full-width character and half-width character (Japanese) +Converts the string resource in variables to desired encoding +Decodes the MIME "encoded-word" in the string +Converts HTML numeric entities to character code +Encodings of the given string is returned (as a string) +Converts the string to MIME "encoded-word" in the format of =?charset?(B|Q)?encoded_string?= +Converts specified characters to HTML numeric entities +Returns the current settings of mbstring +Returns the input encoding +Sets the current output_encoding or returns the current output_encoding as a string +Sets the current internal encoding or Returns the current internal encoding as a string +Sets the current language or Returns the current language as a string +Returns an array of all supported entity encodings or Returns the entity encoding as a string +Returns an array of all supported alias encodings +Returns an array or string of all supported mime names +Returns string in output buffer converted to the http_output encoding +Parses GET/POST/COOKIE data and sets global variables +Return the preferred MIME name (charset) as a string +* Sends an email message with MIME scheme +Returns part of a string +Trim the string in terminal width +Finds position of first occurrence of a string within another, case insensitive +Finds first occurrence of a string within another, case insensitive +Get character numbers of a string +Find position of first occurrence of a string within another +Finds the last occurrence of a character in a string within another +Finds the last occurrence of a character in a string within another, case insensitive +Finds position of last occurrence of a string within another, case insensitive +Find position of last occurrence of a string within another +Finds first occurrence of a string within another +* Returns a lowercased version of sourcestring +* Returns a uppercased version of sourcestring +Gets terminal width of a string +Sets the current substitute_character or returns the current substitute_character +Returns part of a string +Count the number of substring occurrences +Regular expression match for multibyte string +Regular expression match for multibyte string +Replace regular expression for multibyte string +Regular expression search for multibyte string +Get search start position +Get matched substring of the last time +Initialize string and regular expression for search. +Regular expression search for multibyte string +Regular expression search for multibyte string +Set search start position +Case-insensitive regular expression match for multibyte string +Case insensitive replace regular expression for multibyte string +Returns the current encoding for regex as a string. +Set or get the default options for mbregex functions +split multibyte string into array by regular expression +CBC crypt/decrypt data using key key with cipher cipher starting with iv +CFB crypt/decrypt data using key key with cipher cipher starting with iv +Create an initialization vector (IV) +OFB crypt/decrypt data using key key with cipher cipher starting with iv +ECB crypt/decrypt data using key key with cipher cipher starting with iv +Returns the name of the algorithm specified by the descriptor td +Returns the block size of the cipher specified by the descriptor td +Returns the size of the IV in bytes of the algorithm specified by the descriptor td +Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td +Returns the name of the mode specified by the descriptor td +This function decrypts the crypttext +Returns TRUE if the alrogithm is a block algorithms +Returns TRUE if the mode is for use with block algorithms +Returns TRUE if the mode outputs blocks +This function runs the self test on the algorithm specified by the descriptor td +OFB crypt/decrypt data using key key with cipher cipher starting with iv +This function encrypts the plaintext +This function terminates encrypt specified by the descriptor td +This function initializes all buffers for the specific module +Get the key size of cipher +Get the name of cipher +Get the IV size of cipher (Usually the same as the blocksize) +Get the key size of cipher +List all algorithms in "module_dir" +List all modes "module_dir" +Free the descriptor td +Returns the block size of the algorithm +Returns the maximum supported key size of the algorithm +This function decrypts the crypttext +Returns TRUE if the algorithm is a block algorithm +Returns TRUE if the mode is for use with block algorithms +Returns TRUE if the mode outputs blocks of bytes +Opens the module of the algorithm and the mode to be used +Does a self test of the module "module" +OFB crypt/decrypt data using key key with cipher cipher starting with iv +This function decrypts the plaintext +Hash data with hash +Gets the number of available hashes +Gets the block size of hash +Gets the name of hash +Get the name of the keygen algorithm +Get the required size of the salt for the keygen algorithm +Generate a key +Get the number of available keygen algorithms +Generates a key using hash functions +Whether the keygen algorithm uses the bytes_count parameter +Whether the keygen algorithm uses a hash algorithm +Whether the keygen algorithm requires a salt +Return content-type for file +Returns the action flag for keyPress(char) +Set scale (?) +Use constant pool (?) +Use SWF version (?) +Creates a new SWFAction object, compiling the given script +Creates a new SWFBitmap object from jpg (with optional mask) or dbl file +Returns the height of this bitmap +Returns the width of this bitmap +Creates a new SWFButton object +associates a sound with a button transition NOTE: the transitions are all wrong _UP, _OVER, _DOWN _HIT +Sets the action to perform when conditions described in flags is met +Sets the character to display for the condition described in flags +Sets the action to perform when button is pressed +Sets the character for this button's down state +Sets the character for this button's hit test state +enable track as menu button behaviour +Sets the character for this button's over state +Sets the character for this button's up state +Adds this SWFAction to the given SWFSprite instance +Sets the add color part of this SWFDisplayItem's CXform to (r, g, b [, a]), a defaults to 0 +another way of defining a MASK layer +Displaces this SWFDisplayItem by (dx, dy) in movie coordinates +Moves this SWFDisplayItem to movie coordinates (x, y) +Sets the multiply color part of this SWFDisplayItem's CXform to (r, g, b [, a]), a defaults to 1.0 +Rotates this SWFDisplayItem the given (clockwise) degrees from its current orientation +Rotates this SWFDisplayItem the given (clockwise) degrees from its original orientation +Multiplies this SWFDisplayItem's current x scale by xScale, its y scale by yScale +Scales this SWFDisplayItem by xScale in the x direction, yScale in the y, or both to xScale if only one arg +Sets this SWFDisplayItem's z-depth to depth. Items with higher depth values are drawn on top of those with lower values +defines a MASK layer at level +Sets the item's transform matrix +Sets this SWFDisplayItem's name to name +Sets this SWFDisplayItem's ratio to ratio. Obviously only does anything if displayitem was created from an SWFMorph +Adds xSkew to this SWFDisplayItem's x skew value +Sets this SWFDisplayItem's x skew value to xSkew +Adds ySkew to this SWFDisplayItem's y skew value +Sets this SWFDisplayItem's y skew value to ySkew +Creates a new SWFFill object +Moves this SWFFill to shape coordinates (x,y) +Rotates this SWFFill the given (clockwise) degrees from its original orientation +Scales this SWFFill by xScale in the x direction, yScale in the y, or both to xScale if only one arg +Sets this SWFFill's x skew value to xSkew +Sets this SWFFill's y skew value to ySkew +Creates a new SWFFont object from given file +adds characters to a font required within textfields +Returns the ascent of the font, or 0 if not available +Returns the descent of the font, or 0 if not available +Returns the leading of the font, or 0 if not available +Returns the glyph shape of a char as a text string +Calculates the width of the given string in this font at full height +Calculates the width of the given string in this font at full height +Calculates the width of the given string in this font at full height +adds characters to a font for exporting font +adds characters to a font for exporting font +Creates a new SWFGradient object +Adds given entry to the gradient +Creates a new SWFMorph object +Return's this SWFMorph's start shape object +Return's this SWFMorph's start shape object +Creates swfmovie object according to the passed version + +Labels frame + + + + + +Saves the movie. 'where' can be stream and the movie will be saved there otherwise it is treated as string and written in file with that name + +Sets background color (r,g,b) +Sets movie dimension +Sets number of frames +Sets movie rate +Sets sound stream of the SWF movie. The parameter can be stream or string. Retuens the number of frames. +Returns a SWFPrebuiltClip object +Creates a new SWFShape object +Returns a fill object, for use with swfshape_setleftfill and swfshape_setrightfill. If 1 or 2 parameter(s) is (are) passed first should be object (from gradient class) and the second int (flags). Gradient fill is performed. If 3 or 4 parameters are passed : r, g, b [, a]. Solid fill is performed. +Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock +Draws a circle of radius r centered at the current location, in a counter-clockwise fashion +Draws a cubic bezier curve using the current position and the three given points as control points +Draws a cubic bezier curve using the current position and the three given points as control points +Draws a curve from the current pen position (x, y) to the point (x+bdx, y+bdy) in the current line style, using point (x+adx, y+ady) as a control point or draws a cubic bezier to point (x+cdx, x+cdy) with control points (x+adx, y+ady) and (x+bdx, y+bdy) +Draws a curve from the current pen position (x,y) to the point (bx, by) in the current line style, using point (ax, ay) as a control point. Or draws a cubic bezier to point (dx, dy) with control points (ax, ay) and (bx, by) +Draws the first character in the given string into the shape using the glyph definition from the given font +Draws a line from the current pen position (x, y) to the point (x+dx, y+dy) in the current line style +Draws a line from the current pen position to shape coordinates (x, y) in the current line style +Moves the pen from its current location by vector (x, y) +Moves the pen to shape coordinates (x, y) +Sets the left side fill style to fill in case only one parameter is passed. When 3 or 4 parameters are passed they are treated as : int r, int g, int b, int a . Solid fill is performed in this case before setting left side fill type. +Sets the right side fill style to fill in case only one parameter is passed. When 3 or 4 parameters are passed they are treated as : int r, int g, int b, int a . Solid fill is performed in this case before setting right side fill type. +Sets the current line style for this SWFShape +Creates a new SWFSound object from given file +Creates a new SWFSprite object +Adds the character to the sprite, returns a displayitem object +Labels frame +Moves the sprite to the next frame +Remove the named character from the sprite's display list +Sets the number of frames in this SWFSprite +Creates new SWFText object +Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color +Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color +Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color +Returns the ascent of the current font at its current size, or 0 if not available +Returns the descent of the current font at its current size, or 0 if not available +Returns the leading of the current font at its current size, or 0 if not available +calculates the width of the given string in this text objects current font and size +calculates the width of the given string in this text objects current font and size +Calculates the width of the given string in this text objects current font and size +Moves this SWFText object's current pen position to (x, y) in text coordinates +Sets this SWFText object's current color to the given color +Sets this SWFText object's current font to given font +Sets this SWFText object's current height to given height +Sets this SWFText object's current letterspacing to given spacing +Creates a new SWFTextField object +adds characters to a font that will be available within a textfield +Adds the given string to this textfield +Sets the alignment of this textfield +Sets the width and height of this textfield +Sets the color of this textfield +Sets the font for this textfield +Sets the font height of this textfield +Sets the indentation of the first line of this textfield +Sets the left margin of this textfield +Sets the line spacing of this textfield +Sets both margins of this textfield +Sets the variable name of this textfield +Sets the padding of this textfield +Sets the right margin of this textfield +Returns a SWVideoStream object +Return number of affected rows +Close an mSQL connection +Open a connection to an mSQL Server +Create an mSQL database +Move internal result pointer +Send an SQL query to mSQL +Drop (delete) an mSQL database +Returns the text of the error message from previous mSQL operation +Fetch a result row as an associative array +Get column information from a result and return as an object +Fetch a result row as an object +Get a result row as an enumerated array +Get the flags associated with the specified field in a result +Returns the length of the specified field +Get the name of the specified field in a result +Set result pointer to a specific field offset +Get name of the table the specified field is in +Get the type of the specified field in a result +Free result memory +List databases available on an mSQL server +List mSQL result fields +List tables in an mSQL database +Get number of fields in a result +Get number of rows in a result +Open a persistent connection to an mSQL Server +Send an SQL query to mSQL +Get result data +Select an mSQL database +Adds a parameter to a stored procedure or a remote stored procedure +Closes a connection to a MS-SQL server +Establishes a connection to a MS-SQL server +Moves the internal row pointer of the MS-SQL result associated with the specified result identifier to pointer to the specified row number +Executes a stored procedure on a MS-SQL server database +Returns an associative array of the current row in the result set specified by result_id +Returns an associative array of the current row in the result set specified by result_id +Returns the next batch of records +Gets information about certain fields in a query result +Returns a psuedo-object of the current row in the result set specified by result_id +Returns an array of the current row in the result set specified by result_id +Get the length of a MS-SQL field +Returns the name of the field given by offset in the result set given by result_id +Seeks to the specified field offset +Returns the type of a field +Free a MS-SQL result index +Free a MS-SQL statement index +Gets the last message from the MS-SQL server +Converts a 16 byte binary GUID to a string +Initializes a stored procedure or a remote stored procedure +Sets the lower error severity +Sets the lower message severity +Move the internal result pointer to the next result +Returns the number of fields fetched in from the result id specified +Returns the number of rows fetched in from the result id specified +Establishes a persistent connection to a MS-SQL server +Perform an SQL query on a MS-SQL server database +Returns the contents of one cell from a MS-SQL result set +Returns the number of records affected by the query +Select a MS-SQL database +Gets number of affected rows in previous MySQL operation +Returns the default character set for the current connection +Close a MySQL connection +Opens a connection to a MySQL Server +Create a MySQL database +Move internal result pointer +Sends an SQL query to MySQL +Drops (delete) a MySQL database +Returns the number of the error message from previous MySQL operation +Returns the text of the error message from previous MySQL operation +Escape string for mysql query +Fetch a result row as an array (associative, numeric or both) +Fetch a result row as an associative array +Gets column information from a result and return as an object +Gets max data size of each column in a result +Fetch a result row as an object +Gets a result row as an enumerated array +Gets the flags associated with the specified field in a result +Returns the length of the specified field +Gets the name of the specified field in a result +Sets result pointer to a specific field offset +Gets name of the table the specified field is in +Gets the type of the specified field in a result +Free result memory +Returns a string that represents the client library version +Returns a string describing the type of connection in use, including the server host name +Returns the protocol version used by current connection +Returns a string that represents the server version number +Returns a string containing information about the most recent query +Gets the ID generated from the previous INSERT operation +List databases available on a MySQL server +List MySQL result fields +Returns a result set describing the current server threads +List tables in a MySQL database +Gets number of fields in a result +Gets number of rows in a result +Opens a persistent connection to a MySQL Server +Ping a server connection. If no connection then reconnect. +Sends an SQL query to MySQL +Escape special characters in a string for use in a SQL statement, taking into account the current charset of the connection +Gets result data +Selects a MySQL database +sets client character set +Returns a string containing status information +Returns the thread id of current connection +Sends an SQL query to MySQL, without fetching and buffering the result rows +Get number of affected rows in previous MySQL operation +Turn auto commit on or of +Change logged-in user of the active connection +Returns the name of the character set used for this connection +Close connection +Commit outstanding actions and close transaction +Move internal result pointer + + +Returns the numerical value of the error message from previous MySQL operation +Returns the text of the error message from previous MySQL operation +Fetch the number of fields returned by the last query for the given link +Set result pointer to a specified field offset +Get current field offset of result pointer +Free query result memory for the given result handle +Get MySQL client info +Get MySQL client info +Get MySQL protocol information +Get MySQL server info +Return the MySQL version for the server referenced by the given link +Get information about the most recent query +Initialize mysqli and return a resource for use with mysql_real_connect +Get the ID generated from the previous INSERT operation +Kill a mysql process on the server +check if there any more query results from a multi query +read next result from multi_query +Get number of fields in result +Get number of rows in result +Set options +Ping a server connection or reconnect if there is no connection +Prepare a SQL statement for execution +Open a connection to a mysql server +Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection +Binary-safe version of mysql_query() +Undo actions from current transaction +Select a MySQL database +unsets user defined handler for load local infile command +Set callback functions for LOAD DATA LOCAL INFILE +Returns the SQLSTATE error from previous MySQL operation + +Get current system status +Return the number of rows affected in the last query for the given link + + +Bind variables to a prepared statement as parameters +Bind variables to a prepared statement for result storage +Close statement +Move internal result pointer + + +Execute a prepared statement +Fetch results from a prepared statement into the bound variables +Return the number of result columns for the given statement +Free stored result memory for the given statement handle +Initialize statement object +Get the ID generated from the previous INSERT operation +Return the number of rows in statements result set +Return the number of parameter for the given statement +prepare server side statement with query +reset a prepared statement +return result set from statement + + + +Buffer result set on client +Return the current thread ID +Return whether thread safety is given or not +Directly retrieve query results - do not buffer results on client side + +initialize and start embedded server +Open a connection to a mysql server +Returns the numerical value of the error message from last connect command +Returns the text of the error message from previous MySQL operation +returns a character set object +allows to execute multiple queries +sets client character set + + + + +Enforce execution of a query on the master in a master/slave setup + + + + +Enforce execution of a query on a slave in a master/slave setup +sets report level +Bind a PHP array to an Oracle PL/SQL type by name +Bind a PHP variable to an Oracle placeholder by name +Cancel reading from a cursor +Disconnect from database +Append an object to the collection +Assign a collection from another existing collection +Assign element val to collection at index ndx +Retrieve the value at collection index ndx +Return the max value of a collection. For a varray this is the maximum length of the array +Return the size of a collection +Trim num elements from the end of a collection +Commit the current context +Connect to an Oracle database and log on. Returns a new session. +Define a PHP variable to an Oracle column by name +Return the last error of stmt|connection|global. If no error happened returns false. +Execute a parsed statement +Prepare a new row of data for reading +Fetch all rows of result data into an array +Fetch a result row as an array +Fetch a result row as an associative array +Fetch a result row as an object +Fetch a result row as an enumerated array +Tell whether a column is NULL +Tell the name of a column +Tell the precision of a column +Tell the scale of a column +Tell the maximum data size of a column +Tell the data type of a column +Tell the raw oracle data type of a column +Deletes collection object +Deletes large object description +Free all resources associated with a statement +Toggle internal debugging output for the OCI extension +Appends data from a LOB to another LOB +Closes lob descriptor +Copies data from a LOB to another LOB +Checks if EOF is reached +Erases a specified portion of the internal LOB, starting at a specified offset +Writes a large object into a file +Flushes the LOB buffer +Loads file into a LOB +Tests to see if two LOB/FILE locators are equal +Loads a large object +Reads particular part of a large object +Rewind pointer of a LOB +Saves a large object +Moves the pointer of a LOB +Returns size of a large object +Tells LOB pointer position +Truncates a LOB +Writes data to current position of a LOB +Writes temporary blob +Initialize a new collection +Connect to an Oracle database and log on. Returns a new session. +Return a new cursor (Statement-Handle) - use this to bind ref-cursors! +Initialize a new empty descriptor LOB/FILE (LOB is default) +Return the number of result columns in a statement +Return the row count of an OCI statement +Parse a query and return a statement +Changes the password of an account +Connect to an Oracle database using a persistent connection and log on. Returns a new session. +Return a single column of result data +Rollback the current context +Return a string containing server version information +Sets the number of rows to be prefetched on execute to prefetch_rows for stmt +Return the query type of an OCI statement +Fetch a row of result data into an array +Returns current state of buffering for a LOB +Enables/disables buffering for a LOB + + + + + + + + + + + + +Toggle autocommit mode or get status +Handle binary column data +Close an ODBC connection +Close all ODBC connections +Returns a result identifier that can be used to fetch a list of columns and associated privileges for the specified table +Returns a result identifier that can be used to fetch a list of column names in specified tables +Commit an ODBC transaction +Connect to a datasource +Get cursor name +Return information about the currently connected data source +Get the last error code +Get the last error message +Prepare and execute an SQL statement +Execute a prepared statement +Fetch a result row as an associative array +Fetch one result row into an array +Fetch a result row as an object +Fetch a row +Get the length (precision) of a column +Get a column name +Return column number +Get the scale of a column +Get the datatype of a column +Returns a result identifier to either a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table +Free resources associated with a result +Returns a result identifier containing information about data types supported by the data source +Handle LONG columns +Checks if multiple results are avaiable +Get number of columns in a result +Get number of rows in a result +Establish a persistent connection to a datasource +Prepares a statement for execution +Returns a result identifier listing the column names that comprise the primary key for a table +Returns a result identifier containing the list of input and output parameters, as well as the columns that make up the result set for the specified procedures +Returns a result identifier containg the list of procedure names in a datasource +Get result data +Print result as HTML table +Rollback a transaction +Sets connection or statement options +Returns a result identifier containing either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction +Returns a result identifier that contains statistics about a single table and the indexes associated with the table +Returns a result identifier containing a list of tables and the privileges associated with each table +Call the SQLTables function + +Exports a CSR to file or a var +Exports a CSR to file +Returns the subject of a CERT or FALSE on error +Returns the subject of a CERT or FALSE on error +Generates a privkey and CSR +Signs a cert with another CERT +Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages +Opens data +Creates and exports a PKCS12 to a var +Creates and exports a PKCS to file +Parses a PKCS12 to an array +Decrypts the S/MIME message in the file name infilename and output the results to the file name outfilename. recipcert is a CERT for one of the recipients. recipkey specifies the private key matching recipcert, if recipcert does not include the key +Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile +Signs the MIME message in the file named infile with signcert/signkey and output the result to file name outfile. headers lists plain text headers to exclude from the signed portion of the message, and should include to, from and subject as a minimum +Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers +Gets an exportable representation of a key into a string or file +Gets an exportable representation of a key into a file +Frees a key +returns an array with the key details (bits, pkey, type) +Gets private keys +Gets public key from X.509 certificate +Generates a new private key +Decrypts data with private key +Encrypts data with private key +Decrypts data with public key +Encrypts data with public key +Seals data +Signs data +Verifys data +Checks if a private key corresponds to a CERT +Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs +Exports a CERT to file or a var +Exports a CERT to file or a var +Frees X.509 certificates +Returns an array of the fields/values of the CERT +Reads X.509 certificates +Set an alarm clock for delivery of a signal +Executes specified program in current process space as defined by exec(2) +Forks the currently running process following the same behavior as the UNIX fork() system call +Get the priority of any process +Change the priority of any process +Assigns a system signal handler to a PHP function +Waits on or returns the status of a forked child as defined by the waitpid() system call +Waits on or returns the status of a forked child as defined by the waitpid() system call +Returns the status code of a child's exit +Returns true if the child status code represents a successful exit +Returns true if the child status code represents a process that was terminated due to a signal +Returns true if the child status code represents a stopped process (WUNTRACED must have been used with waitpid) +Returns the number of the signal that caused the process to stop who's status code is passed +Returns the number of the signal that terminated the process who's status code is passed +Searches array and returns entries which match regex +Returns the error code of the last regexp execution. +Perform a Perl-style regular expression match +Perform a Perl-style global regular expression match +Quote regular expression characters plus an optional character +Perform Perl-style regular expression replacement. +Perform Perl-style regular expression replacement using replacement callback. +Split string into an array using a perl-style regular expression as a delimiter +Return array of available PDO drivers + +Prevents serialization of a PDO instance +Prevents use of a PDO instance that has been unserialized +Initiates a transaction +Commit a transaction +Fetch the error code associated with the last operation on the database handle +Fetch extended error information associated with the last operation on the database handle +Execute a query that does not return a row set, returning the number of affected rows +Get an attribute +Returns the id of the last row that we affected on this connection. Some databases require a sequence or table name to be passed in. Not always meaningful. +Prepares a statement for execution and returns a statement object +Prepare and execute $sql; returns the statement object for iteration +quotes string for use in a query. The optional paramtype acts as a hint for drivers that have alternate quoting styles. The default value is PDO_PARAM_STR +roll back a transaction +Set an attribute +Return array of available PDO drivers +Prevents serialization of a PDOStatement instance +Prevents use of a PDOStatement instance that has been unserialized +bind a column to a PHP variable. On each row fetch $param will contain the value of the corresponding column. $column is the 1-based offset of the column, or the column name. For portability, don't call this before execute(). +bind a parameter to a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). This isn't supported by all drivers. It should be called prior to execute(). +bind an input parameter to the value of a PHP variable. $paramno is the 1-based position of the placeholder in the SQL statement (but can be the parameter name for drivers that support named placeholders). It should be called prior to execute(). +Closes the cursor, leaving the statement ready for re-execution. +Returns the number of columns in the result set +A utility for internals hackers to debug parameter internals +Fetch the error code associated with the last operation on the statement handle +Fetch extended error information associated with the last operation on the statement handle +Execute a prepared statement, optionally binding parameters +Fetches the next row and returns it, or false if there are no more rows +Returns an array of all of the results. +Returns a data of the specified column in the result set. +Fetches the next row and returns it as an object. +Get an attribute +Returns meta data for a numbered column +Advances to the next rowset in a multi-rowset statement handle. Returns true if it succeded, false otherwise +Returns the number of rows in a result set, or the number of rows affected by the last execute(). It is not always meaningful. +Set an attribute +Changes the default fetch mode for subsequent fetches (params have different meaning for different fetch modes) +Returns the number of affected tuples +Cancel request +Get the current client encoding +Close a PostgreSQL connection +Open a PostgreSQL connection +Get connection is busy or not +Reset connection (reconnect) +Get connection status +Check and convert values for PostgreSQL SQL statement +Copy table from array +Copy table to array +Get the database name +Delete records has ids (id=>value) +Sync with backend. Completes the Copy command +Escape binary for bytea type +Escape string for text/char type +Execute a prepared query +Fetch all rows into array +Fetch all rows into array +Fetch a row as an array +Fetch a row as an assoc array +Fetch a row as an object +Returns values from a result identifier +Get a row as an enumerated array +Test if a field is NULL +Returns the name of the field +Returns the field number of the named field +Returns the printed length +Returns the internal size of the field +Returns the name of the table field belongs to, or table's oid if oid_only is true +Returns the type name for the given field +Returns the type oid for the given field +Free result memory +Get asynchronous notification +Get backend(server) pid +Get asynchronous query result +Returns the host name associated with the connection +Insert values (filed=>value) to table +Get the error message string +Returns the last notice set by the backend +Returns the last object identifier +Close a large object +Create a large object +Export large object direct to filesystem +Import large object direct from filesystem +Open a large object and return fd +Read a large object +Read a large object and send straight to browser +Seeks position of large object +Returns current position of large object +Delete a large object +Write a large object +Get meta_data +Return the number of fields in the result +Return the number of rows in the result +Get the options associated with the connection +Open a persistent PostgreSQL connection +Ping database. If connection is bad, try to reconnect. +Return the port number associated with the connection +Prepare a query for future execution +Send null-terminated string to backend server +Execute a query +Execute a query +Get error message associated with result +Get error message field associated with result +Set internal row offset +Get status of query result +Select records that has ids (id=>value) +Executes prevriously prepared stmtname asynchronously +Asynchronously prepare a query for future execution +Send asynchronous query +Send asynchronous parameterized query +Set client encoding +Set error verbosity +Enable tracing a PostgreSQL connection +Get transaction status +Return the tty name associated with the connection +Unescape binary for bytea type +Disable tracing of a PostgreSQL connection +Update table using values (field=>value) and ids (id=>value) +Returns an array with client, protocol and server version (when available) +Determine accessibility of a file (POSIX.1 5.6.3) +Generate terminal path name (POSIX.1, 4.7.1) +Retrieve the error number set by the last posix function which failed. +Get working directory pathname (POSIX.1, 5.2.2) +Get the current effective group id (POSIX.1, 4.2.1) +Get the current effective user id (POSIX.1, 4.2.1) +Get the current group id (POSIX.1, 4.2.1) +Group database access (POSIX.1, 9.2.1) +Group database access (POSIX.1, 9.2.1) +Get supplementary group id's (POSIX.1, 4.2.3) +Get user name (POSIX.1, 4.2.4) +Get the process group id of the specified process (This is not a POSIX function, but a SVR4ism, so we compile conditionally) +Get current process group id (POSIX.1, 4.3.1) +Get the current process id (POSIX.1, 4.1.1) +Get the parent process id (POSIX.1, 4.1.1) +User database access (POSIX.1, 9.2.2) +User database access (POSIX.1, 9.2.2) +Get system resource consumption limits (This is not a POSIX function, but a BSDism and a SVR4ism. We compile conditionally) +Get process group id of session leader (This is not a POSIX function, but a SVR4ism, so be compile conditionally) +Get the current user id (POSIX.1, 4.2.1) +Calculate the group access list for the user specified in name. +Determine if filedesc is a tty (POSIX.1, 4.7.1) +Send a signal to a process (POSIX.1, 3.3.2) +Make a FIFO special file (POSIX.1, 5.4.2) +Make a special or ordinary file (POSIX.1) +Set effective group id +Set effective user id +Set group id (POSIX.1, 4.2.2) +Set process group id for job control (POSIX.1, 4.3.3) +Create session and set process group id (POSIX.1, 4.3.2) +Set user id (POSIX.1, 4.2.2) +Retrieve the system error message associated with the given errno. +Get process times (POSIX.1, 4.5.2) +Determine terminal device name (POSIX.1, 4.7.2) +Get system name (POSIX.1, 4.4.1) +Adds a word to a personal list +Adds a word to the current session +Returns true if word is valid +Clears the current session +Create a new config to be used later to create a manager +location of language data files +location of the main word list +Ignore words <= n chars +Select mode for config (PSPELL_FAST, PSPELL_NORMAL or PSPELL_BAD_SPELLERS) +Use a personal dictionary for this config +Use a personal dictionary with replacement pairs for this config +Consider run-together words as valid components +Save replacement pairs when personal list is saved for this config +Load a dictionary +Load a dictionary based on the given config +Load a dictionary with a personal wordlist +Saves the current (personal) wordlist +Notify the dictionary of a user-selected replacement +Returns array of suggestions +Reads a line +Adds a line to the history +Initializes the readline callback interface and terminal, prints the prompt and returns immediately +Removes a previously installed callback handler and restores terminal settings +Informs the readline callback interface that a character is ready for input +Clears the history +Readline completion function? +Gets/sets various internal readline variables. +Lists the history +Inform readline that the cursor has moved to a new line +Reads the history +Ask readline to redraw the display +Writes the history +Recode file input into file output according to request +Recode string str according to request string +Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire +Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter +Deserializes data and reinitializes the variables +Destroy the current session and all data associated with it +Serializes the current setup and returns the serialized representation +Return the session cookie parameters +Return the current session id. If newid is given, the session id is replaced with newid +Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname +Return the current session name. If newname is given, the session name is replaced with newname +Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. +Return the current save path passed to module_name. If newname is given, the save path is replaced with newname +Set session cookie parameters +Sets user-level functions +Begin session - reinitializes freezed variables, registers browsers etc +Unset all registered variables +Write session data and end session +Add Attribute with optional namespace information +Add Element with optional namespace information +Return a well-formed XML string based on SimpleXML element +Identifies an element's attributes +Finds children of given node +Return all namespaces registered with document +Finds children of given node +Return all namespaces in use +Creates a prefix/ns context for the next XPath query +Runs XPath query on the XML data +SimpleXMLElement constructor +Return a string to confirm that the module is compiled in +* * Generic SNMPv3 object fetcher * From here is passed on the the common internal object fetcher. * * st=SNMP_CMD_GET snmp3_get() - query an agent and return a single value. * st=SNMP_CMD_GETNEXT snmp3_getnext() - query an agent and return the next single value. * st=SNMP_CMD_WALK snmp3_walk() - walk the mib and return a single dimensional array * containing the values. * st=SNMP_CMD_REALWALK snmp3_real_walk() - walk the mib and return an * array of oid,value pairs. * st=SNMP_CMD_SET snmp3_set() - query an agent and set a single value * +Fetch a SNMP object +Fetch a SNMP object +Return all objects including their respective object id withing the specified one +Set the value of a SNMP object +Return all objects under the specified object id +Fetch the value of a SNMP object +Fetch the value of a SNMP object +Fetch the value of a SNMP object +Fetch the value of a SNMP object +Fetch the value of a SNMP object +Return the current status of quick_print +Return the method how the SNMP values will be returned +Reads and parses a MIB file into the active MIB tree. +Return all values that are enums with their enum value instead of the raw integer +Set the OID output format. +Return all objects including their respective object id withing the specified one +Specify the method how the SNMP values will be returned +Fetch a SNMP object +Fetch a SNMP object +Return all objects including their respective object id withing the specified one +Set the value of a SNMP object +Return all objects under the specified object id +SoapClient::__doRequest() +Returns array of cookies. +Returns last SOAP request headers +Returns last SOAP response headers +Sets cookie thet will sent with SOAP request. The call to this function will effect all folowing calls of SOAP methods. If value is not specified cookie is removed. +Sets the location option (the endpoint URL that will be touched by the following SOAP requests). If new_location is not specified or null then SoapClient will use endpoint from WSDL file. The function returns old value of location options. +Sets SOAP headers for subsequent calls (replaces any previous values). If no value is specified, all of the headers are removed. +Adds one or several functions those will handle SOAP requests +Returns list of defined functions +Sets class which will handle SOAP requests +Sets object which will handle SOAP requests +Accepts a connection on the listening socket fd +Binds an open socket to a listening port, port is only specified in AF_INET family. +Clears the error on the socket or the last error code. +Closes a file descriptor +Opens a connection to addr:port on the socket specified by socket +Creates an endpoint for communication in the domain specified by domain, of type specified by type +Opens a socket on port to accept connections +Creates a pair of indistinguishable sockets and stores them in fds. +Gets socket options for the socket +Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type. +Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type. +Returns the last socket error (either the last used or the provided socket resource) +Sets the maximum number of connections allowed to be waited for on the socket specified by fd +Reads a maximum of length bytes from socket +Receives data from a connected socket +Receives data from a socket, connected or not +Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usec +Sends data to a connected socket +Sends a message to a socket, whether it is connected or not +Sets blocking mode on a socket resource +Sets nonblocking mode on a socket resource +Sets socket options for the socket +Shuts down a socket for receiving, sending, or both. +Returns a string describing an error +Writes the buffer to the socket resource, length is optional +Return all classes and interfaces implemented by SPL +Return an array containing the names of all parent classes +Default implementation for __autoload() +Try all registerd autoload function to load the requested class +Register and return default file extensions for spl_autoload +Register given function as __autoload() implementation +Unregister given function as __autoload() implementation +Return an array containing the names of all clsses and interfaces defined in SPL +Return hash id for given object +Move to next entry +Rewind array back to the start +Seek to position. +Check whether array contains more entries +proto void ArrayIterator::__construct(array|object ar = array() [, int flags = 0]) U Cronstructs a new array iterator from a path. +proto void ArrayIterator::append(mixed $newval) U Appends the value (cannot be called for objects). +proto int ArrayIterator::asort() U Sort the entries by values. +proto int ArrayIterator::count() U Return the number of elements in the Iterator. +Get flags +Create a new iterator from a ArrayObject instance +Get the class used in getIterator. +proto int ArrayIterator::ksort() U Sort the entries by key. +proto int ArrayIterator::natcasesort() U Sort the entries by key using case insensitive "natural order" algorithm. +proto int ArrayIterator::natsort() U Sort the entries by values using "natural order" algorithm. +proto bool ArrayIterator::offsetExists(mixed $index) U Returns whether the requested $index exists. +proto mixed ArrayIterator::offsetGet(mixed $index) U Returns the value at the specified $index. +proto void ArrayIterator::offsetSet(mixed $index, mixed $newval) U Sets the value at the specified $index to $newval. +proto void ArrayIterator::offsetUnset(mixed $index) U Unsets the value at the specified $index. +Set flags +Set the class used in getIterator. +proto int ArrayIterator::uasort(callback cmp_function) U Sort the entries by values user defined function. +proto int ArrayIterator::uksort(callback cmp_function) U Sort the entries by key using user defined function. +Create a sub iterator for the current element (same class as $this) +Check whether current element has children (e.g. is an array) +Cronstructs a new dir iterator from a path. +Return number of entries in directory, works only when USE_GLOB is in effect +Return this (needed for Iterator interface) +Returns filename component of current dir entry +Returns an iterator for the current entry if it is a directory +Return filename of current dir entry +Returns true if current entry is '.' or '..' +Return current dir entry +Move to next entry +Rewind dir back to the start +Check whether dir contains more entries +Cronstructs a new dir iterator from a path. +Return getFilename(), getFileInfo() or $this depending on flags +Get sub path +Get sub path and file name +Returns whether current entry is a directory and not '.' or '..' +Return getPathname() or getFilename() depending on flags +Move to next entry +Rewind dir back to the start +Cronstructs a new SplFileInfo from a path. +Get last access time of file +Returns filename component of path +Get inode modification time of file +Get/copy file info +Return filename only +Get file group +Get file inode +Return the target of a symbolic link +Get last modification time of file +Get file owner +Return the path +Get/copy file info +Return path and filename +Get file permissions +Return the resolved path +Get file size +Get file type +Returns true if file is directory +Returns true if file is executable +Returns true if file is a regular file +Returns true if file is symbolic link +Returns true if file can be read +Returns true if file can be written +Open the current file +Class to use in openFile() +Class to use in getFileInfo(), getPathInfo() +Construct a new file object +Return current line from file +Return whether end of file is reached +Flush the file +Get a character form the file +Return current line as csv +Rturn next line from file +Get a line from file pointer and strip HTML tags +Portable file locking +Output all remaining data from a file pointer +Implements a mostly ANSI compatible fscanf() +Return current file position +Stat() on a filehandle +Return current file position +Truncate file to 'size' length +Binary-safe file write +Read NULL +Get the delimiter and enclosure character used in fgetcsv +Get file handling flags +Get maximum line length +Return false +Return line number +Read next line +Rewind the file and read the first line +Seek to specified line +Set the delimiter and enclosure character used in fgetcsv +Set file handling flags +Set maximum line length +Return !eof() +Construct a new temp file object +Create an AppendIterator +Append an iterator +Get access to inner ArrayIterator +Get index of iterator +Forward to next element +Rewind to the first iterator and rewind the first iterator, too +Check if the current state is valid +Construct a CachingIterator from an Iterator +Return the string representation of the current element +Number of cached elements +Return the cache +Return the internal flags +Check whether the inner iterator has a valid next element +Move the iterator forward +Return whether the requested index exists +Return the internal cache if used +Set given index in cache +Unset given index in cache +Rewind the iterator +Set the internal flags +Check whether the current element is valid +Throws exception BadMethodCallException +Throws exception BadMethodCallException +Does nothing +Does nothing +Return false +Create an Iterator from another iterator +proto mixed CachingIterator::current() U proto mixed LimitIterator::current() U proto mixed ParentIterator::current() U proto mixed IteratorIterator::current() U proto mixed NoRewindIterator::current() U proto mixed AppendIterator::current() U Get the current element value +proto Iterator CachingIterator::getInnerIterator() U proto Iterator LimitIterator::getInnerIterator() U proto Iterator ParentIterator::getInnerIterator() U Get the inner iterator +proto mixed CachingIterator::key() U proto mixed LimitIterator::key() U proto mixed ParentIterator::key() U proto mixed IteratorIterator::key() U proto mixed NoRewindIterator::key() U proto mixed AppendIterator::key() U Get the current key +Move the iterator forward +Rewind the iterator +proto bool ParentIterator::valid() U proto bool IteratorIterator::valid() U proto bool NoRewindIterator::valid() U Check whether the current element is valid +Create an iterator from another iterator +Prevent a call to inner iterators rewind() (internally the current data will be fetched if valid()) +Create an iterator from anything that is traversable +Return the current position +Move the iterator forward +Rewind the iterator to the specified starting offset +Seek to the given position +Check whether the current element is valid +Create an iterator from another iterator +Return inner iterators current() +Return inner iterators key() +Return inner iterators next() +Prevent a call to inner iterators rewind() +Return inner iterators valid() +Create a ParentIterator from a RecursiveIterator +proto void IteratorIterator::next() U proto void NoRewindIterator::next() U Move the iterator forward +proto void IteratorIterator::rewind() Rewind the iterator +Create an iterator from a RecursiveIterator +Return the inner iterator's children as a RecursiveCachingIterator +Check whether the current element of the inner iterator has children +Create a RecursiveFilterIterator from a RecursiveIterator +Return the inner iterator's children contained in a RecursiveFilterIterator +Check whether the inner iterator's current element has children +Called when recursing one level down +Called when iteration begins (after first rewind() call) +Return children of current element +Called for each element to test whether it has children +Access the current element value +Called when end recursing one level +Called when iteration ends (when valid() first returns false +Get the current depth of the recursive iteration +The current active sub iterator +The current active sub iterator or the iterator at specified level +Access the current key +Move forward to the next element +Called when the next element is available +Rewind the iterator to the first element of the top level inner iterator. +Set the maximum allowed depth (or any depth if pmax_depth = -1] +Check whether the current position is valid +Create an RecursiveRegexIterator from another recursive iterator and a regular expression +Return the inner iterator's children contained in a RecursiveRegexIterator +Create an RegexIterator from another iterator and a regular expression +Match (string)current() against regular expression +Returns current PREG flags (if in use or NULL) +Returns current operation flags +Returns current operation mode +Set operation flags +Set new operation mode +Set PREG flags +Construct a LimitIterator from an Iterator with a given starting offset and optionally a maximum count +Calls a function for every element in an iterator +Count the elements in an iterator +Copy the iterator into an array +Attaches an object to the storage if not yet contained +Determine whethe an object is contained in the storage +Determine number of objects in storage + +Detaches an object from the storage + + + + + + +Get number of child elements +Get current element +Get child element iterator +Check whether element has children (elements) +Get name of current child element +Move to next element +Rewind to first element +Check whether iteration is valid +Executes a query against a given database and returns an array of arrays. +Set busy timeout duration. If ms <= 0, all busy handlers are disabled. +Returns the number of rows that were changed by the most recent SQL statement. +Closes an open sqlite database. +Fetches a column from the current row of a result set. +Registers an aggregate function for queries. +Registers a "regular" function for queries. +Fetches the current row from a result set as an array. +Returns the textual description of an error code. +Escapes a string for use as a query parameter. +Executes a result-less query against a given database +Opens a SQLite database and creates an object for it. Will create the database if it does not exist. +Fetches all rows from a result set as an array of arrays. +Fetches the next row from a result set as an array. +Return an array of column types from a particular table. +Fetches the next row from a result set as an object. +Fetches the first column of a result set as a string. +Returns the name of a particular field of a result set. +* Returns whether a previous row is available. +Return the current row index of a buffered result. +Returns the error code of the last error for a database. +Returns the rowid of the most recently inserted row. +Returns the encoding (iso8859 or UTF-8) of the linked SQLite library. +Returns the version of the linked SQLite library. +Seek to the next row number of a result set. +Returns the number of fields in a result set. +Returns the number of rows in a buffered result set. +Opens a SQLite database. Will create the database if it does not exist. +Opens a persistent handle to a SQLite database. Will create the database if it does not exist. +* Seek to the previous row number of a result set. +Executes a query against a given database and returns a result handle. +Seek to the first row number of a buffered result set. +Seek to a particular row number of a buffered result set. +Executes a query and returns either an array for one single column or the value of the first row. +Decode binary encoding on a string parameter passed to an UDF. +Apply binary encoding (if required) to a string to return from an UDF. +Executes a query that does not prefetch and buffer all data. +Returns whether more rows are available. +Retuns an array with all string keys lowercased [or uppercased] +Split array into chunks +Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values +Return the value as key and the frequency of that value in input as value +Returns the entries of arr1 that have values which are not present in any of the others arguments. +Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal +Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved. +Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function. +Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved. +Create an array containing num elements starting with index start_key each initialized to val +Create an array using the elements of the first parameter as keys each initialized to val +Filters elements from the array via the callback. +Return array with key <-> value flipped +Returns the entries of arr1 that have values which are present in all the other arguments +Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check +Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data. +Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback. +Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data. +Checks if the given key or index exists in the array +Return just the keys from the input array, optionally only for the specified search_value +Applies the callback to the elements in given arrays. +Merges elements from passed arrays into one array +Recursively merges elements from passed arrays into one array +Sort multiple arrays at once similar to how ORDER BY clause works in SQL +Returns a copy of input array padded with pad_value to size pad_size +Pops an element off the end of the array +Returns the product of the array entries +Pushes elements onto the end of the array +Return key/keys for random entry/entries in the array +Iteratively reduce the array to a single value via the callback. +Return input as a new array with the order of the entries reversed +Searches the array for a given value and returns the corresponding key if successful +Pops an element off the beginning of the array +Returns elements specified by offset and length +Removes the elements designated by offset and length and replace them with supplied array +Returns the sum of the array entries +Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function. +Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Entries are compared by user supplied function. +Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions. +Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback. +Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback. +Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks. +Removes duplicate values from array +Pushes elements onto the beginning of the array +Return just the values from the input array +Apply a user function to every member of an array +Apply a user function recursively to every member of an array +Sort an array in reverse order and maintain index association +Sort an array and maintain index association +Creates a hash containing variables and their values +Count the number of elements in a variable (usually an array) +Return the element currently pointed to by the internal array pointer +Advances array argument's internal pointer to the last element and return it +Imports variables into symbol table from an array +Checks if the given value exists in the array +Return the key of the element currently pointed to by the internal array pointer +Sort an array by key value in reverse order +Sort an array by key +Return the highest value in an array or a series of arguments +Return the lowest value in an array or a series of arguments +Sort an array using case-insensitive natural sort +Sort an array using natural sort +Move array argument's internal pointer to the next element and return it +Move array argument's internal pointer to the previous element and return it +Create an array containing the range of integers or characters from low to high (inclusive) +Set array argument's internal pointer to the first element and return it +Sort an array in reverse order +Randomly shuffle the contents of an array +Sort an array +Sort an array with a user-defined comparison function and maintain index association +Sort an array by keys using a user-defined comparison function +Sort an array by values using a user-defined comparison function +Checks if assertion is false +Set/get the various assert flags +Decodes string using MIME base64 algorithm +Encodes string using MIME base64 algorithm +Call a user function which is the first parameter +Call a user function which is the first parameter with the arguments contained in array +Call a user method on a specific object or class +Call a user method on a specific object or class using a parameter array +Returns true if client disconnected +Returns the connection status bitfield +Given the name of a constant this function will return the constant's associated value +Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet. +Send an error message somewhere +Flush the output buffer +Get the value of a PHP configuration option +Get the name of the owner of the current PHP script +Get the current include_path configuration option +Get the value of an environment variable +Get options from the command line argument list +Returns protocol number associated with name as per /etc/protocols +Returns protocol name associated with protocol number proto +Returns port associated with service. Protocol must be "tcp" or "udp" +Returns service name associated with port. Protocol must be "tcp" or "udp" +Syntax highlight a source file +Syntax highlight a string or optionally return it +Set whether we want to ignore a user abort event or not +Import GET/POST/Cookie variables into the global scope +Converts a packed inet address to a human readable IP address string +Converts a human readable IP address to a packed binary string +Get a configuration option +Get all configuration options +Restore the value of a configuration option specified by varname +Set a configuration option, returns false on error and the old value of the configuration option on success +Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address +Check if file was created by rfc1867 upload +Converts an (IPv4) Internet network address into a string in Internet standard dotted format +Move a file if and only if it was created by an upload +Parse configuration file +Return source with stripped comments and whitespace +Prints out or returns information about the specified variable +Set the value of an environment variable +Register a user-level function to be called on request termination +Registers a tick callback function +Restore the value of the include_path configuration option +Sets the include_path configuration option +Delay for a given number of seconds + +Delay for a number of seconds and nano seconds +Make the script sleep until the specified time +Unregisters a tick callback function +Delay for a given number of micro seconds +Get information about the capabilities of a browser. If browser_name is omitted or null, HTTP_USER_AGENT is used. Returns an object by default; if return_array is true, returns an array. +Calculate the crc32 polynomial of a string +Hash a string +Convert from one Cyrillic character set to another +Parse a time/date generated with strftime() +Change the current directory +Change root directory +Close directory connection identified by the dir_handle +Directory class with properties, handle and class and methods read, rewind and close +Gets the current directory +Find pathnames matching a pattern +Open a directory and return a dir_handle +Read directory entry from dir_handle +Rewind dir_handle back to the start +List files & directories inside the specified path +Load a PHP extension at runtime +Check DNS records corresponding to a given Internet host name or IP address +Get MX records corresponding to a given Internet host name +Get the Internet host name corresponding to a given IP address +Get the IP address corresponding to a given Internet host name +Return a list of IP addresses that a given hostname resolves to. +Quote and escape an argument for use in a shell command +Escape shell metacharacters +Execute an external program +Execute an external program and display raw output +Change the priority of the current process +Execute command via shell and return complete output as string +Execute an external program and display output +Copy a file +Close an open file pointer +Test for end-of-file on a file pointer +Flushes output +Get a character from file pointer +Get line from file pointer and parse for CSV fields +Get a line from file pointer +Get a line from file pointer and strip HTML tags +Read entire file into an array +Read the entire file into a string +Write/Create a file with contents data and return the number of bytes written +Portable file locking +Match filename against pattern +Open a file or a URL and return a file pointer +Output all remaining data from a file pointer +Format line as CSV and write to file pointer +Binary-safe file read +Implements a mostly ANSI compatible fscanf() +Seek on a file pointer +Stat() on a filehandle +Get file pointer's read/write position +Truncate file to 'size' length +Binary-safe file write +Extracts all meta tag content attributes from a file and returns an array +Create a directory +Close a file pointer opened by popen() +Execute a command and open either a read or a write pipe to it +Output a file or a URL +Return the resolved path +Rename a file +Rewind the position of a file pointer +Remove a directory +Returns directory path used for temporary files +Create a unique filename in a directory +Create a temporary file that will be deleted automatically after use +Return or change the umask +Delete a file +Change file group +Change file mode +Clear file stat cache +Get free disk space for filesystem that path is on +Get total disk space for filesystem that path is on +Returns true if filename exists +Get last access time of file +Get inode modification time of file +Get file group +Get file inode +Get last modification time of file +Get file owner +Get file permissions +Get file size +Get file type +Returns true if file is directory +Returns true if file is executable +Returns true if file is a regular file +Returns true if file is symbolic link +Returns true if file can be read +Returns true if file can be written +Change symlink group +Give information about a file or symbolic link +Give information about a file +Set modification time of file +Output a formatted string into a stream +Output a formatted string +Return a formatted string +Output a formatted string into a stream +Output a formatted string +Return a formatted string +Open Internet or Unix domain socket connection +Open persistent Internet or Unix domain socket connection +Convert a pathname and a project identifier to a System V IPC key +Sends a raw HTTP header +Return list of headers to be sent / already sent +Returns true if headers have already been sent, false otherwise +Send a cookie +Send a cookie with no url encoding of the value +Returns the internal translation table used by htmlspecialchars and htmlentities +Convert all HTML entities to their applicable characters +Convert all applicable characters to HTML entities +Convert special characters to HTML entities +Convert special HTML entities back to characters +Generates a form-encoded query string from an associative array or object. +Get the size of an image as 4-element array +Get file extension for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype +Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype +Return the special ID used to request the PHP logo in phpinfo screens +Return the actual loaded ini filename +Return comma-separated string of .ini files parsed from the additional ini dir +Return the special ID used to request the PHP logo in phpinfo screens +Return the special ID used to request the PHP logo in phpinfo screens +Return the current SAPI module name +Return information about the system PHP was built on +Prints the list of people who've contributed to the PHP project +Output a page of useful information about PHP and the current request +Return the current PHP version +Return the special ID used to request the Zend logo in phpinfo screens +Embed binary IPTC data into a JPEG image. +Parse binary IPTC-data into associative array +Returns a value from the combined linear congruential generator +Calculate Levenshtein distance between two strings +Create a hard link +Returns the st_dev field of the UNIX C stat structure describing the link +Return the target of a symbolic link +Create a symbolic link +Calculate EZMLM list hash value. +Send an email message +Return the absolute value of the number +Return the arc cosine of the number in radians +Returns the inverse hyperbolic cosine of the number, i.e. the value whose hyperbolic cosine is number +Returns the arc sine of the number in radians +Returns the inverse hyperbolic sine of the number, i.e. the value whose hyperbolic sine is number +Returns the arc tangent of the number in radians +Returns the arc tangent of y/x, with the resulting quadrant determined by the signs of y and x +Returns the inverse hyperbolic tangent of the number, i.e. the value whose hyperbolic tangent is number +Converts a number in a string from any base <= 36 to any base <= 36 +Returns the decimal equivalent of the binary number +Returns the next highest integer value of the number +Returns the cosine of the number in radians +Returns the hyperbolic cosine of the number, defined as (exp(number) + exp(-number))/2 +Returns a string containing a binary representation of the number +Returns a string containing a hexadecimal representation of the given number +Returns a string containing an octal representation of the given number +Converts the number in degrees to the radian equivalent +Returns e raised to the power of the number +Returns exp(number) - 1, computed in a way that accurate even when the value of number is close to zero +Returns the next lowest integer value from the number +Returns the remainder of dividing x by y as a float +Returns the decimal equivalent of the hexadecimal number +Returns sqrt(num1*num1 + num2*num2) +Returns whether argument is finite +Returns whether argument is infinite +Returns whether argument is not a number +Returns the natural logarithm of the number, or the base log if base is specified +Returns the base-10 logarithm of the number +Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero +Formats a number with grouped thousands +Returns the decimal equivalent of an octal string +Returns an approximation of pi +Returns base raised to the power of exponent. Returns integer result when possible +Converts the radian number to the equivalent number in degrees +Returns the number rounded to specified precision +Returns the sine of the number in radians +Returns the hyperbolic sine of the number, defined as (exp(number) - exp(-number))/2 +Returns the square root of the number +Returns the tangent of the number in radians +Returns the hyperbolic tangent of the number, defined as sinh(number)/cosh(number) +Calculate the md5 hash of a string +Calculate the md5 hash of given filename +Break english phrases down into their phonemes +Returns an array of usage statistics +Returns the current time as array +Returns either a string or a float containing the current time in seconds and microseconds +Takes one or more arguments and packs them into a binary string according to the format argument +Unpack binary string into named array elements according to format argument +Get time of last page modification +Get PHP script owner's GID +Get the inode of the current script being parsed +Get current process ID +Get PHP script owner's UID +close a process opened by proc_open +get information about a process opened by proc_open +Run a process with more control over it's file descriptors +kill a process opened by proc_open +Convert a quoted-printable string to an 8 bit string +Returns the maximum value a random number can have +Returns the maximum value a random number from Mersenne Twister can have +Returns a random number from Mersenne Twister +Seeds Mersenne Twister random number generator +Returns a random number +Seeds random number generator +Regular expression match +Replace regular expression +Case-insensitive regular expression match +Case insensitive replace regular expression +Split string into array by regular expression +Split string into array by regular expression case-insensitive +Make regular expression for case insensitive match +Calculate the sha1 hash of a string +Calculate the sha1 hash of given filename +Calculate the soundex key of a string +Create a file context and optionally set parameters +Get a handle on the default file/stream context and optionally set parameters +Retrieve options for a stream/wrapper/context +* Overloaded form: stream_context_set_option(resource context|resource stream, array options) * Set an option (or several options) for a wrapper +Set parameters for a file context +Reads up to maxlen bytes from source stream and writes them to dest stream. +Convenience wrapper for ini_set('unicode.stream_encoding', $encoding) +Set character set for stream encoding UTODO: Return current encoding charset +Append a filter to a stream +Prepend a filter to a stream +Flushes any data in the filter's internal buffer, removes it from the chain, and frees the resource +Reads all remaining bytes (or up to maxlen bytes) from a stream and returns them as a string. +Read up to maxlen bytes from a stream or until the ending string is found +Retrieves header/meta data from streams/file pointers +Retrieves list of registered socket transports +Retrieves list of registered stream wrappers + +Determine what file will be opened by calls to fopen() with a relative path +Runs the select() system call on the sets of streams with a timeout specified by tv_sec and tv_usec +Set blocking/non-blocking mode on a socket or stream +Set timeout on stream read to seconds + microseonds +Set file write buffer +Accept a client connection from a server socket +Open a client connection to a remote address +Enable or disable a specific kind of crypto on the stream +Returns either the locally bound or remote name for a socket stream +Creates a pair of connected, indistinguishable socket streams +Receives data from a socket stream +Send data to a socket stream. If target_addr is specified it must be in dotted quad (or [ipv6]) format +Create a server socket bound to localaddress +causes all or part of a full-duplex connection on the socket associated with stream to be shut down. If how is SHUT_RD, further receptions will be disallowed. If how is SHUT_WR, further transmissions will be disallowed. If how is SHUT_RDWR, further receptions and transmissions will be disallowed. +Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\n', '\r', '\t' etc...) +Escapes single quote, double quotes and backslash characters in a string with backslashes +Returns the filename component of the path +Converts the binary representation of data to hex +Converts a codepoint number to a character +Returns split line +Returns info about what characters are used in input +Returns the directory name component of the path +Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned. +Converts logical Hebrew text to visual text +Converts logical Hebrew text to visual text with newline conversion +Joins array elements placing glue string between items and return one string +An alias for implode +Returns numeric formatting information based on the current locale +Strips whitespace from the beginning of a string +Convert monetary value(s) to string +Converts newlines to HTML line breaks +Query language and locale information +Returns the codepoint value of a character +Parses GET/POST/COOKIE data and sets global variables +Returns information about a certain string +Quotes meta characters +Removes trailing whitespace +Set locale information +Calculates the similarity between two strings +Implements an ANSI C compatible sscanf +Parse a CSV string into an array +Replaces all occurrences of search in haystack with replace / case-insensitive +Returns input string padded on the left or right to specified length with pad_string +Returns the input string repeat mult times +Replaces all occurrences of search in haystack with replace +Perform the rot13 transform on a string +Shuffles string. One permutation of all possible is created +Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long. +Counts the number of words inside a string. If format of 1 is specified, then the function will return an array containing all the words found inside the string. If format of 2 is specified, then the function will return an associated array where the position of the word is the key and the word itself is the value. For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters. +An alias for strstr +Compares two strings using the current locale +Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars) +Strips HTML and PHP tags from a string +Strips backslashes from a string. Uses C-style conventions +Finds position of first occurrence of a string within another, case insensitive +Strips backslashes from a string +Finds first occurrence of a string within another, case insensitive +Returns the result of case-insensitive string comparison using 'natural' algorithm +Returns the result of string comparison using 'natural' algorithm +Search a string for any of a set of characters +Finds position of first occurrence of a string within another +Finds the last occurrence of a character in a string within another +Reverse a string +Finds position of last occurrence of a string within another string +Finds position of last occurrence of a string within another string +Finds length of initial segment consisting entirely of characters found in mask. If start or/and length is provided works like strspn(substr($s,$start,$len),$good_chars) +Finds first occurrence of a string within another +Tokenize a string +Makes a string lowercase +Makes a string titlecase +Makes a string uppercase +Translates characters in str using given translation tables +Returns part of a string +Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters +Returns the number of times a substring occurs in the string +Replaces part of a string with another string +Strips whitespace from the beginning and end of a string +Makes a string's first character uppercase +Uppercase the first character of every word in a string +Wraps buffer to selected number of characters using string break char +Close connection to system logger +Initializes all syslog-related variables +Open connection to system logger +Generate a system log message +Get the float value of a variable +Returns the type of the variable +Get the integer value of a variable using the optional base for the conversion +Returns true if variable is an array +Returns true if variable is a native (binary) string +Returns true if variable is a boolean +Returns true if variable is a native, unicode or binary string +Returns true if var is callable. +Returns true if variable is float point +Returns true if variable is a long (integer) +Returns true if variable is null +Returns true if value is a number or a numeric string +Returns true if variable is an object +Returns true if variable is a resource +Returns true if value is a scalar +Returns true if variable is a Unicode or binary string +Returns true if variable is a unicode string +Set the type of the variable +Get the string value of a variable +Generates a unique ID +fetches all the headers sent by the server in response to a HTTP request +Parse a URL and return its components +Decodes URL-encodes string +URL-encodes string +Decodes URL-encoded string +URL-encodes string +Append bucket to brigade +Return a bucket object from the brigade for operating on +Create a new bucket for use on the current stream +Prepend bucket to brigade +Registers a custom filter handler class +Returns a list of registered filters +Non-function +decode a uuencoded string +uuencode a string +Dumps a string representation of an internal zend value to output. +Returns the peak allocated by PHP memory +Returns the allocated by PHP memory +Returns a string representation of variable (which can later be unserialized) +Takes a string representation of variable and recreates it +Dumps a string representation of variable to output +Outputs or returns a string representation of a variable +Dumps a string representation of variable to output (verbose form) +Compares two "PHP-standardized" version number strings +Get number of affected rows in last query +Close Sybase connection +Open Sybase server connection +Move internal row pointer +Fetch row as array +Get field information +Fetch row as object +Get row as enumerated array +Set field offset +Free result memory +Returns the last message from server (over min_message_severity) +Sets the minimum error severity +Sets the minimum message severity +Get number of fields in result +Get number of rows in result +Open persistent Sybase connection +Send Sybase query +Get result data +Select Sybase database +Get number of affected rows in last query +Close Sybase connection +Open Sybase server connection +Move internal row pointer +Sets deadlock retry count +Fetch row as array +Fetch row as array without numberic indices +Get field information +Fetch row as object +Get row as enumerated array +Set field offset +Free result memory +Returns the last message from server (over min_message_severity) +Sets minimum client severity +Sets minimum server severity +Get number of fields in result +Get number of rows in result +Open persistent Sybase connection +Send Sybase query +Get result data +Select Sybase database +Set the error handler, to be called when a server message is raised. If error_func is NULL the handler will be deleted +Send Sybase query +Attach to a message queue +Send a message of type msgtype (must be > 0) to a message queue +Destroy the queue +Send a message of type msgtype (must be > 0) to a message queue +Set information for a message queue +Returns information about a message queue +Acquires the semaphore with the given id, blocking if necessary +Return an id for the semaphore with the given key, and allow max_acquire (default 1) processes to acquire it simultaneously +Releases the semaphore with the given id +Removes semaphore from Unix systems +Creates or open a shared memory segment +Disconnects from shared memory segment +Returns a variable from shared memory +Checks whether a specific entry exists +Inserts or updates a variable in shared memory +Removes shared memory from Unix systems +Removes variable from shared memory +Returns the parent node if available or NULL +Returns true if this node has children +Returns true if this node has siblings +Returns true if this node is ASP +Returns true if this node represents a comment +Returns true if this node is part of a HTML document +Returns true if this node is JSTE +Returns true if this node is PHP +Returns true if this node represents text (no markup) +Returns the Number of Tidy accessibility warnings encountered for specified document. +Execute configured cleanup and repair operations on parsed markup +Returns the Number of Tidy configuration errors encountered for specified document. +Run configured diagnostics on parsed and repaired markup. +Returns the Number of Tidy errors encountered for specified document. +Returns a TidyNode Object starting from the <BODY> tag of the tidy parse tree +Get current Tidy configuration +Return warnings and errors which occured parsing the specified document +Returns a TidyNode Object starting from the <HEAD> tag of the tidy parse tree +Returns a TidyNode Object starting from the <HTML> tag of the tidy parse tree +Get the Detected HTML version for the specified document. +Returns the documentation for the given option name +Return a string representing the parsed tidy markup +Get release date (version) for Tidy library +Returns a TidyNode Object representing the root of the tidy parse tree +Get status of specfied document. +Returns the value of the specified configuration option for the tidy document. +Indicates if the document is a XHTML document. +Indicates if the document is a generic (non HTML/XHTML) XML document. +Parse markup in file or URI +Parse a document stored in a string +Repair a file using an optionally provided configuration file +Repair a string using an optionally provided configuration file +Returns the Number of Tidy warnings encountered for specified document. + + +Compare two strings using collation }}} +Returns a collation attribute }}} +Returns the current collation strength }}} +Set a collation attribute }}} +Set the collation strength }}} +Sort an array using collation }}} +Compare two strings using collation +Create a new Collator object +Returns a collation attribute +Returns default collator +Returns the current collation strength +Set a collation attribute +Sets default collator +Set the collation strength +Sort an array using collation +Create a new Collator object +Returns default locale +Sets default locale +Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name. +Enumerate all code points with their general categories invoking a callback for each category +Get the character representation for the specified digit (optionally in the specified radix) +Translate a human readable character name into a codepoint +Get the "age" of the code point (the Unicode version when it was first designated or assigned a character) +Returns the combining class of the character +Returns the decimal digit value of the character (optionally in the specific radix). +Returns the bidirectional category value for the character, which is used in the Unicode bidirectional algorithm (UAX #9 http://www.unicode.org/reports/tr9/) +Maps the specified character to its "mirror-image" +Get the human readable name associated with the character +Get the numeric value for the character, as defined in the Unicode Character Database +Get the property ID for the given property name +Get the maximum possible value associated with the specified property +Get the minimum possible value for the specified property +Get the Unicode name for the given property +Get the value of a property associated with the character +Get the value ID for the given property value name +Get the Unicode name for the givenproperty value +Returns the general category value for the code point +Determines if all the characters in the string have the specified binary property +Determines if the string consists only of alpanumeric characters +Determines if the string consists only of letter characters +Determines if the string consists only of characters with Alphabetic property +Determines if the string consists of only of base characters +Determines if the string consists only of "blank" characters +Determines if the string consists only of control characters +Determines if the string consists only of defined characters (valid Unicode points) +Determines if the string consists only of digits +Determines if the string consists only of "graphic" characters +Determines if the specified characters should be regarded as an ignorable character in an identifier, according to Java +etermines if the specified characters are permissible in an identifier, according to Java +Determines if the specified character is permissible as the first character in an identifier according to Unicode +Determines whether the specified code points are ISO control codes +Determines if the string is lowercase +Determines whether the specified characters have the Bidi_Mirrored property +Determines if the string consists only of printable characters +Determines if the string consists only of punctuation characters +Determines if the string consists only of space characters +Determines whether the string consists only of titlecase characters +Determines if the string is uppercase +Determines if the string consists only of characters with Uppercase property +Determines if the the code point is valid character, according to Unicode +Determines if the string consists only of whitespace characters, according to Java/ICU +Determines if the string consists only of hexadecimal digits +Transliterate a string from the source script to the target script +Takes a binary string converts it to a Unicode string using the specifed encoding +Takes a Unicode string and converts it to a binary string using the specified encoding +Returns global conversion error mode for the specified conversion direction +Returns global substitution character for conversion from Unicode to codepage +Restores the active error handler to the one which was previously active (before the last unicode_set_error_handler() call) +Check whether unicode semantics are enabled +Set (or clear) the custom Unicode conversion error handler +Sets global conversion error mode for the specified conversion direction +Sets global substitution character for conversion from Unicode to codepage +TextIterator constructor +Returns the element at the current boundary +Positions iterator at the first character in the text and returns the offset +Advances to the text boundary following the specified offset and returns its offset +Return all text pieces determined by the text boundaries +Returns locales for which text boundary information is available +Return the status from the break rule that determined the most recent boundary +Return the statuses from the break rules that determined the most recent boundary +Determines whether specified offset is a text boundary +Returns the number boundaries iterated through +Positions iterator beyond the last character in the text and returns the offset +Advances to the n'th text boundary following the current one and returns its offset +Returns the offset of the current text boundary +Advances to the text boundary preceding the specified offset and returns its offset +Advances to the n'th text boundary preceding the current one and returns its offset +Determines validity of the iterator +Serializes given variables and adds them to packet given by packet_id +Ends specified WDDX packet and returns the string containing the packet +Starts a WDDX packet with optional comment and returns the packet id +Creates a new packet and serializes the given value +Creates a new packet and serializes given variables into a struct +Unserializes given packet and returns a PHP value +Converts a UTF-8 encoded string to ISO-8859-1 +Encodes an ISO-8859-1 string to UTF-8 +Get XML parser error string +Get current byte index for an XML parser +Get current column number for an XML parser +Get current line number for an XML parser +Get XML parser error code +Start parsing an XML document +Parsing a XML document +Create an XML parser +Create an XML parser +Free an XML parser +Get options from an XML parser +Set options in an XML parser +Set up character data handler +Set up default handler +Set up start and end element handlers +Set up character data handler +Set up external entity reference handler +Set up notation declaration handler +Set up object which should be used for callbacks +Set up processing instruction (PI) handler +Set up character data handler +Set up unparsed entity declaration handler +Sets the string that the the XMLReader will parse. +Closes xmlreader - current frees resources until xmlTextReaderClose is fixed in libxml +Moves the position of the current instance to the next node in the stream. +Get value of an attribute from current element +Get value of an attribute at index from current element +Get value of a attribute via name and namespace from current element +Indicates whether given property (one of the parser option constants) is set or not on parser +Returns boolean indicating if parsed document is valid or not. Must set XMLREADER_LOADDTD or XMLREADER_VALIDATE parser option prior to the first call to read or this method will always return FALSE +Return namespaceURI for associated prefix on current node +Positions reader at specified attribute - Returns TRUE on success and FALSE on failure +Positions reader at attribute at spcecified index. Returns TRUE on success and FALSE on failure +Positions reader at attribute spcified by name and namespaceURI. Returns TRUE on success and FALSE on failure +Moves the position of the current instance to the node that contains the current Attribute node. +Moves the position of the current instance to the first attribute associated with the current node. +Moves the position of the current instance to the next attribute associated with the current node. +Moves the position of the current instance to the next node in the stream. +Sets the URI that the the XMLReader will parse. +Moves the position of the current instance to the next node in the stream. +Reads the contents of the current node, including child nodes and markup. +Reads the contents of the current node, including child nodes and markup. +Reads the contents of an element or a text node as a string. +Sets parser property (one of the parser option constants). Properties must be set after open() or XML() and before the first read() is called +Sets the string that the the XMLReader will parse. +Sets the string that the the XMLReader will parse. +Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read(). +Decodes XML into native PHP types +Decodes XML into native PHP types +Generates XML for a PHP value +Generates XML for a method request +Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings +Determines if an array value represents an XMLRPC fault. +Decodes XML into a list of method descriptions +Adds introspection documentation +Parses XML requests and call methods +Creates an xmlrpc server +Destroys server resources +Register a PHP function to generate documentation +Register a PHP function to handle method matching method_name +Sets xmlrpc type, base64 or datetime, for a PHP string value +End attribute - returns FALSE on error +End current CDATA - returns FALSE on error +Create end comment - returns FALSE on error +End current document - returns FALSE on error +End current DTD - returns FALSE on error +End current DTD AttList - returns FALSE on error +End current DTD element - returns FALSE on error +End current DTD Entity - returns FALSE on error +End current element - returns FALSE on error +End current PI - returns FALSE on error +Output current buffer +End current element - returns FALSE on error +Create new xmlwriter using memory for string output +Create new xmlwriter using source uri for output +Output current buffer as string +Toggle indentation on/off - returns FALSE on error +Set string used for indenting - returns FALSE on error +Create start attribute - returns FALSE on error +Create start namespaced attribute - returns FALSE on error +Create start CDATA tag - returns FALSE on error +Create start comment - returns FALSE on error +Create document tag - returns FALSE on error +Create start DTD tag - returns FALSE on error +Create start DTD AttList - returns FALSE on error +Create start DTD element - returns FALSE on error +Create start DTD Entity - returns FALSE on error +Create start element tag - returns FALSE on error +Create start namespaced element tag - returns FALSE on error +Create start PI tag - returns FALSE on error +Write text - returns FALSE on error +Write full attribute - returns FALSE on error +Write full namespaced attribute - returns FALSE on error +Write full CDATA tag - returns FALSE on error +Write full comment tag - returns FALSE on error +Write full DTD tag - returns FALSE on error +Write full DTD AttList tag - returns FALSE on error +Write full DTD element tag - returns FALSE on error +Write full DTD Entity tag - returns FALSE on error +Write full element tag - returns FALSE on error +Write full namesapced element tag - returns FALSE on error +Write full PI tag - returns FALSE on error +Write text - returns FALSE on error + + +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since: + + + +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since: + + +Add a file in a Zip archive using its path and the name to use. +Add a file using content and the entry name +close the zip archive +Returns the index of the entry named filename in the archive +Delete a file using its index +Delete a file using its index +Returns the comment of an entry using its index +Returns the comment of an entry using its index +Returns the comment of an entry using its name +get the contents of an entry using its index +get the contents of an entry using its name +Returns the name of the file at position index +get a stream for an entry using its name +Returns the index of the entry named filename in the archive +Create new zip using source uri for output, return TRUE on success or the error code +Rename an entry selected by its index to new_name +Rename an entry selected by its name to new_name +Set or remove (NULL/'') the comment of the archive +Set or remove (NULL/'') the comment of an entry using its index +Set or remove (NULL/'') the comment of an entry using its Name +Returns the zip entry informations using its index +Returns the information about a the zip entry filename +All changes to files and global information in archive are reverted +Revert all global changes to the archive archive. For now, this only reverts archive comment changes. +Changes to the file at position index are reverted +Changes to the file named 'name' are reverted +Close a Zip archive +Close a zip entry +Return the compressed size of a ZZip entry +Return a string containing the compression method used on a particular entry +Return the actual filesize of a ZZip entry +Return the name given a ZZip entry +Open a Zip File, pointed by the resource entry +Read from an open directory entry +Create new zip using source uri for output +Returns the next file in the archive +Encode data with the zlib encoding +Decode gzip encoded data +Encode data with the raw deflate encoding +Encode data with the gzip encoding +Read and uncompress entire .gz-file into an array +Decode raw deflate encoded data +Open a .gz-file and return a .gz-file pointer +Decode zlib encoded data +Output a .gz-file +Uncompress any raw/gzip/zlib encoded data +Compress data with the specified encoding +Returns the coding type used for output compression +Sets the maximum time a script can run +Clean (delete) the current output buffer +Clean the output buffer, and delete current output buffer +Flush (send) the output buffer, and delete current output buffer +Flush (send) contents of the output buffer. The last buffer content is sent to next buffer +Get current buffer contents and delete current output buffer +Return the contents of the output buffer +Get current buffer contents, flush (send) the output buffer, and delete current output buffer +Return the length of the output buffer +Return the nesting level of the output buffer +Turn implicit flush on/off and is equivalent to calling flush() after every output call +Turn on Output Buffering (specifying an optional output handler). +Add URL rewriter values +Reset(clear) URL rewriter values +Registers a custom URL protocol handler class +Restore the original protocol handler, overriding if necessary +Unregister a wrapper for the life of the current request. +Terminate apache process after this request +Get a list of loaded Apache modules +Fetch Apache version +Perform a partial request of the given URI to obtain information about it +Get and set Apache request notes +Fetch all HTTP request headers +Reset the Apache write timer +Fetch all HTTP response headers +Set an Apache subprocess_env variable +Alias for apache_request_headers() +Perform an Apache sub-request +Get a list of loaded Apache modules +Fetch Apache version +Get an Apache subprocess_env variable +Get and set Apache request notes +Fetch all HTTP response headers +Set an Apache subprocess_env variable +Fetch all HTTP request headers +Perform an apache sub-request +Get a list of loaded Apache modules +Fetch Apache version +Get an Apache subprocess_env variable +Get and set Apache request notes +Fetch all HTTP response headers +Set an Apache subprocess_env variable +Fetch all HTTP request headers +Perform an apache sub-request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Terminate apache process after this request +Get a list of loaded Apache modules +Fetch Apache version +Perform a partial request of the given URI to obtain information about it +Get and set Apache request notes + + + +* fetch all headers that go out in case of an error or a subrequest +Fetch all HTTP request headers +* fetch all incoming request headers +* fetch all outgoing request headers + + + + +This is a wrapper for ap_sub_run_req and ap_destory_sub_req. It takes sub_request, runs it, destroys it, and returns it's status. + + + + + +Returns sub-request for the specified file. You would need to run it yourself with run(). +Returns sub-request for the specified uri. You would need to run it yourself with run() +Returns sub-request for the specified file. You would need to run it yourself with run(). + +Fetch all HTTP response headers +Set an Apache subprocess_env variable + +Perform an Apache sub-request +Adds a header to the current message. +Add a recipient to the message envelope. +Changes a header's value for the current message. +Removes the named recipient from the current message's envelope. +Returns the value of the given macro or NULL if the macro is not defined. +Replaces the body of the current message. If called more than once, subsequent calls result in data being appended to the new body. +Sets the flags describing the actions the filter may take. +Directly set the SMTP error reply code for this connection. This code will be used on subsequent error replies resulting from actions taken by this filter. +Sets the number of seconds libmilter will wait for an MTA connection before timing out a socket. +Get all headers from the request +Get all headers from the response +Perform an NSAPI sub-request +Dummy function which displays an error when a disabled function is called. +Checks if the class exists +Cause the process to crash by copying data to an inaccesible location +Creates an anonymous function, and returns its name (funny, eh?) +Return backtrace as array +Define a new constant +Check whether a constant exists +Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element +Return the current error_reporting level, and if an argument was passed - change to the new level +Returns true if the named extension is loaded +Get the $arg_num'th argument that was passed to the function +Get an array of the arguments that were passed to the function +Get the number of arguments that were passed to the function +Checks if the function exists +Retrieves the class name +Returns an array of method names for class or class instance. +Returns an array of default properties of the class. +Returns an array of all declared classes. +Returns an array of all declared interfaces. +Return an array containing the names and values of all defined constants +Returns an array of all defined functions +Returns an associative array of names and values of all currently defined variable names (variables in the current scope) +Returns an array with the names of functions belonging to the named extension +Returns an array with the file names that were included (includes require and once varieties) +Return an array containing names of loaded extensions +Returns an array of object properties +Retrieves the parent class name for object or class or current scope. +Get the resource type name for a given resource +Checks if the class exists +Returns true if the object is of this class or has this class as one of its parents +Returns true if the object has this class as one of its parents +Cause an intentional memory leak, for testing/debugging purposes +Checks if the class method exists +Checks if the object or class has a property +Restores the previously defined error handler function +Restores the previously defined exception handler function +Sets a user-defined error handler function. Returns the previously defined error handler, or false on error +Sets a user-defined exception handler function. Returns the previously defined exception handler, or false on error +Binary safe case-insensitive string comparison +Binary safe string comparison +Get string length +Binary safe string comparison +Binary safe string comparison +Generates a user-level error/warning/notice message +Generic test function +Returns a unique identifier for the current thread +Get the version of the Zend Engine +Get the exception severity +Clone the exception object +Obtain the string representation of the Exception object +Get the exception code +Get the file in which the exception occurred +Get the line in which the exception occurred +Get the exception message +Get the stack trace for the location in which the exception occurred +Obtain the backtrace for the exception as a string (instead of an array) +Exception constructor +ErrorException constructor +PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +3.14159265358979323846 +2.7182818284590452354 +1.4426950408889634074 +0.43429448190325182765 +0.69314718055994530942 +2.30258509299404568402 +1.57079632679489661923 +0.78539816339744830962 +0.31830988618379067154 +0.63661977236758134308 +1.77245385090551602729 +1.12837916709551257390 +1.41421356237309504880 +1.73205080756887729352 +0.70710678118654752440 +1.14472988584940017414 +0.57721566490153286061 +1 +2 +3 +4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1 +4 +5 +6 +9 +255 +254 +-1 + +1 +2 +3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur. +Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format. +When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify are used. The supplied certificates can still be used as untrusted CAs however. +Do not verify the signers certificate of a signed message. +Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs. +When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify for example). +Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included. +When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign . If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME. +Don't try and verify the signatures on a message + + + + + +Phar::SHA512 ( integer ) +Phar::PHPS ( integer ) + + + + + + + + + + + + + + + +ERR_NOERR +ERR_DUPLICATE +ERR_EOSCAN +ERR_EMPTY +ERR_CLOSE +ERR_WLOCKED +ERR_LOCKED +ERR_NOLOCK +ERR_READ +ERR_WRITE +ERR_CREATE +ERR_LSEEK +ERR_LENGTH +ERR_OPEN +ERR_WOPEN +ERR_MAGIC +ERR_VERSION +ERR_PGSIZE +ERR_CRC +ERR_PIPE +ERR_NIDX +ERR_MALLOC +ERR_NUSERS +ERR_PREEXIT +ERR_ONTRAP +ERR_PREPROC +ERR_DBPARSE +ERR_DBRUNERR +ERR_DBPREEXIT +ERR_WAIT +ERR_CORRUPT_TUPLE +ERR_WARNING0 +ERR_PANIC +ERR_FIFO +ERR_PERM +ERR_TCL +ERR_RESTRICTED +ERR_USER +ERR_UNKNOWN + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +1 +2 +3 +4 +5 +7 +8 +9 +10 +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Used to turn on-the-fly data compression on with Memcache::set , Memcache::add &listendand; Memcache::replace . +1 if this Memcache session handler is available, 0 otherwise. + + + + + + + + + + + + + + + + + + +Used with stream_filter_append and stream_filter_prepend to indicate that the specified filter should only be applied when reading +Used with stream_filter_append and stream_filter_prepend to indicate that the specified filter should only be applied when writing +This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE +Return Code indicating that the userspace filter returned buckets in $out . +Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available). +Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received). +Flag indicating if the stream used the include path. +Flag indicating if the wrapper is responsible for raising errors using trigger_error during opening of the stream. If this flag is not set, you should not raise any errors. +Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client . +Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client . +Client socket opened with stream_socket_client should remain persistent between page loads. +Tells a stream created with stream_socket_server to bind to the specified target. Server sockets should always include this flag. +Tells a stream created with stream_socket_server and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error. +A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened. +A connection with an external resource has been established. +Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR . +The mime-type of resource has been identified, refer to message for a description of the discovered type. +The size of the resource has been discovered. +The external resource has redirected the stream to an alternate location. Refer to message . +Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well. +There is no more data available on the stream. +A generic error occurred on the stream, consult message and message_code for details. +Authorization has been completed (with or without success). +Normal, non-error related, notification. +Non critical error condition. Processing may continue. +A critical error occurred. Processing cannot continue. +Provides a ICMP socket. +Provides a IP socket. +Provides a RAW socket. +Provides a TCP socket. +Provides a UDP socket. +Internet Protocol Version 4 (IPv4). +Internet Protocol Version 6 (IPv6). +Unix system internal protocols. +Provides datagrams, which are connectionless messages (UDP, for example). +Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user. +Provides a RDM (Reliably-delivered messages) socket. +Provides a sequenced packet stream socket. +Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example). +Used with stream_socket_shutdown to disable further receptions. Added in PHP 5.2.1. +Used with stream_socket_shutdown to disable further transmissions. Added in PHP 5.2.1. +Used with stream_socket_shutdown to disable further receptions and transmissions. Added in PHP 5.2.1. +Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +no color (black) +white +red - supported when terminal is in color mode +green - supported when terminal is in color mode +yellow - supported when terminal is in color mode +blue - supported when terminal is in color mode +cyan - supported when terminal is in color mode +magenta - supported when terminal is in color mode +down arrow +up arrow +left arrow +right arrow +home key (upward+left arrow) +backspace +delete line +insert line +delete character +insert char or enter insert mode +exit insert char mode +clear screen +clear to end of screen +clear to end of line +scroll one line forward +scroll one line backward +next page +previous page +set tab +clear tab +clear all tabs +soft (partial) reset +reset or hard reset +print +lower left +upper left of keypad +upper right of keypad +center of keypad +lower left of keypad +lower right of keypad +back tab +beginning +cancel +close +cmd (command) +copy +create +end +exit +find +help +mark +message +move +next +open +options +previous +redo +ref (reference) +refresh +replace +restart +resume +save +shiftet beg (beginning) +shifted cancel +shifted command +shifted copy +shifted create +shifted delete char +shifted delete line +select +shifted end +shifted end of line +shifted exit +shifted find +shifted help +shifted home +shifted input +shifted left arrow +shifted message +shifted move +shifted next +shifted options +shifted previous +shifted print +shifted redo +shifted replace +shifted right arrow +shifted resume +shifted save +shifted suspend +undo +mouse event has occurred +maximum key value +ctrl pressed during click +shift pressed during click +alt pressed during click +report all mouse events +report mouse position + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +1 +2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases. +Starts a read-only transaction. +Starts a read-write transaction. +Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions. +Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started. +Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION . This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction. +Indicated that a transaction should wait and retry when a conflict occurs. +Indicated that a transaction should fail immediately when a conflict occurs. +Also available as IBASE_TEXT for backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers. +Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available. +Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Unsigned 8-bit PCM. +Signed 8-bit PCM. +Unsigned 16-bit PCM. Little Endian byte order. +Unsigned 16-bit PCM. Big Endian byte order. +Signed 16-bit PCM. Little Endian byte order. +Signed 16-bit PCM. Big Endian byte order. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +if there is an error while sending data to the system logger, write directly to the system console +open the connection to the logger immediately +(default) delay opening the connection until the first message is logged + +print log message also to standard error +include PID with each message +security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined) +security/authorization messages (private) +clock daemon (cron and at) +other system daemons +kernel messages +line printer subsystem +mail subsystem +USENET news subsystem +messages generated internally by syslogd +generic user-level messages +UUCP subsystem +system is unusable +action must be taken immediately +critical conditions +error conditions +warning conditions +normal, but significant, condition +informational message +debug-level message +IPv4 Address Resource +Mail Exchanger Resource +Alias (Canonical Name) Resource +Authoritative Name Server Resource +Pointer Resource +Host Info Resource (See IANA's Operating System Names for the meaning of these values) +Start of Authority Resource +Text Resource +Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead. +IPv6 Address Resource +Iteratively query the name server for each available record type. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Use compression protocol +Allow space after function names +Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection. +Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5. +Columns are returned into the array having the fieldname as the array index. +Columns are returned into the array having both a numerical index and the fieldname as the array index. +Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +string +string +integer +integer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +KRB5_KDB_DISALLOW_FORWARDABLE +KRB5_KDB_DISALLOW_RENEWABLE +KRB5_KDB_DISALLOW_DUP_SKEY +KRB5_KDB_REQUIRES_PRE_AUTH +KRB5_KDB_REQUIRES_PWCHANGE +KRB5_KDB_PWCHANGE_SERVER +KRB5_KDB_NEW_PRINC +long +long +long +long +long +long +string +long +long +string +long +long +long +long +long +long + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +integer +integer +integer +integer +integer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Some value which can be obtained with fstat(1) changed for a file or directory. +A file or directory was deleted or renamed. +A file was created in a directory. +This event never occurs. +An event in response to fam_cancel_monitor . +An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. + + + + + + + + + + + + + + + + + + + + +1 +2 +4 +8 +16 +32 +64 +128 +256 +example: 1.0.2-dev + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +XMLReader::ENTITY_REF ( integer ) +Document Type node +Document Fragment node +Notation node +Whitespace node +Significant Whitespace node +End Element +End Entity +XML Declaration node +Character data with fixed length +Date, number of days since 1.1.0000 +Short integer (2 Bytes) +Long integer (4 Bytes) +same as PX_FIELD_NUMBER +Double +Boolean +Binary large object +Binary large object (not supported) +Binary large object +OLE object (basically a blob, not supported) +Graphic (basically a blob, not supported) +time, number of milli seconds since midnight +timestamp, number of milli seconds since 1.1.0000 +Auto incrementing interger (like PX_FIELD_LONG) +Decimal number stored in bcd format (not supported) +Array of Bytes with not more than 255 bytes (not supported) +Turn all field names into lower case +Turn all field names into upper case +Indexed database +Primary index +None indexed database +None incremental secondary index +Secondary index +Incremental secondary index +Non incremental secondary index +Secondary index +Non incremental secondary index + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The component name used to initialise the SQLDBC runtime environment. +The application to be connected to the database. +The version of the application. +The SQL mode. +TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. +The maximum allowed time of inactivity after which the connection to the database is closed by the system. +Specifies whether and how shared locks and exclusive locks are implicitly requested or released. +The number of different request packets used for the connection. +The number of prepared statements to be cached for the connection for re-use. +The prefix to use for result tables that are automatically named. +Columns are returned into the array having the fieldname as the array index. +Columns are returned into the array having the upper case fieldname as the array index. +Columns are returned into the array having the lower case fieldname as the array index. +Columns are returned into the array having both a numerical index and the fieldname as the array index. +Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. + + + + + + + + + + +TIDY_TAG_A +TIDY_TAG_ACRONYM +TIDY_TAG_APPLET +TIDY_TAG_B +TIDY_TAG_BASEFONT +TIDY_TAG_BGSOUND +TIDY_TAG_BLINK +TIDY_TAG_BODY +TIDY_TAG_BUTTON +TIDY_TAG_CENTER +TIDY_TAG_CODE +TIDY_TAG_COLGROUP +TIDY_TAG_DD +TIDY_TAG_DFN +TIDY_TAG_DIV +TIDY_TAG_DT +TIDY_TAG_EMBED +TIDY_TAG_FONT +TIDY_TAG_FRAME +TIDY_TAG_H1 +TIDY_TAG_H3 +TIDY_TAG_H5 +TIDY_TAG_HEAD +TIDY_TAG_HTML +TIDY_TAG_IFRAME +TIDY_TAG_IMG +TIDY_TAG_INS +TIDY_TAG_KBD +TIDY_TAG_LABEL +TIDY_TAG_LEGEND +TIDY_TAG_LINK +TIDY_TAG_MAP +TIDY_TAG_MENU +TIDY_TAG_MULTICOL +TIDY_TAG_NOEMBED +TIDY_TAG_NOLAYER +TIDY_TAG_NOSCRIPT +TIDY_TAG_OL +TIDY_TAG_OPTION +TIDY_TAG_PARAM +TIDY_TAG_PRE +TIDY_TAG_RP +TIDY_TAG_RTC +TIDY_TAG_S +TIDY_TAG_SCRIPT +TIDY_TAG_SERVER +TIDY_TAG_SMALL +TIDY_TAG_SPAN +TIDY_TAG_STRONG +TIDY_TAG_SUB +TIDY_TAG_TBODY +TIDY_TAG_TEXTAREA +TIDY_TAG_TH +TIDY_TAG_TITLE +TIDY_TAG_TR +TIDY_TAG_U +TIDY_TAG_VAR +TIDY_TAG_XMP +TIDY_ATTR_ABBR +TIDY_ATTR_ACCEPT_CHARSET +TIDY_ATTR_ACTION +TIDY_ATTR_ALIGN +TIDY_ATTR_ALT +TIDY_ATTR_AXIS +TIDY_ATTR_BGCOLOR +TIDY_ATTR_BORDER +TIDY_ATTR_BOTTOMMARGIN +TIDY_ATTR_CELLSPACING +TIDY_ATTR_CHAROFF +TIDY_ATTR_CHECKED +TIDY_ATTR_CLASS +TIDY_ATTR_CLEAR +TIDY_ATTR_CODEBASE +TIDY_ATTR_COLOR +TIDY_ATTR_COLSPAN +TIDY_ATTR_CONTENT +TIDY_ATTR_DATA +TIDY_ATTR_DATAPAGESIZE +TIDY_ATTR_DATETIME +TIDY_ATTR_DEFER +TIDY_ATTR_DISABLED +TIDY_ATTR_ENCTYPE +TIDY_ATTR_FOR +TIDY_ATTR_FRAMEBORDER +TIDY_ATTR_GRIDX +TIDY_ATTR_HEADERS +TIDY_ATTR_HREF +TIDY_ATTR_HSPACE +TIDY_ATTR_ID +TIDY_ATTR_LABEL +TIDY_ATTR_LANGUAGE +TIDY_ATTR_LAST_VISIT +TIDY_ATTR_LINK +TIDY_ATTR_LOWSRC +TIDY_ATTR_MARGINWIDTH +TIDY_ATTR_MEDIA +TIDY_ATTR_MULTIPLE +TIDY_ATTR_NOHREF +TIDY_ATTR_NOSHADE +TIDY_ATTR_OBJECT +TIDY_ATTR_PROMPT +TIDY_ATTR_READONLY +TIDY_ATTR_REV +TIDY_ATTR_ROWS +TIDY_ATTR_RULES +TIDY_ATTR_SCOPE +TIDY_ATTR_SELECTED +TIDY_ATTR_SHOWGRID +TIDY_ATTR_SHOWGRIDY +TIDY_ATTR_SPAN +TIDY_ATTR_STANDBY +TIDY_ATTR_STYLE +TIDY_ATTR_TABINDEX +TIDY_ATTR_TEXT +TIDY_ATTR_TOPMARGIN +TIDY_ATTR_USEMAP +TIDY_ATTR_VALUE +TIDY_ATTR_VERSION +TIDY_ATTR_VSPACE +TIDY_ATTR_WRAP +TIDY_ATTR_XML_SPACE +constant +root node +doctype +HTML comment +Processing Instruction +Text +start tag +end tag +empty tag +CDATA +XML section +ASP code +JSTE code +PHP code +XML declaration +hotkey defined by newt_form_add_hot_key was pressed +some component has caused form to exit +file descriptor specified in newt_form_watch_fd is ready to be read or written to +time specified in newt_form_set_timer has elapsed + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Exit form, when component is activated +Component is hidden +Component is scrollable +Component is disabled + +Wrap text +Don't exit form on pressing F12 + +Component is selected +Component is checkbox +Entry component is password entry +Show cursor + + + + + + + + + + + + + + +Wrap text in the textbox +Scroll text in the textbox +Don't exit form on F12 press + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all . +Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all . +See the description of PREG_SPLIT_OFFSET_CAPTURE . This flag is available since PHP 4.3.0. +This flag tells preg_split to return only non-empty pieces. +This flag tells preg_split to capture parenthesized expression in the delimiter pattern as well. This flag is available since PHP 4.0.5. +If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is available since PHP 4.3.0 and is only used for preg_split . +Returned by preg_last_error if there were no errors. Available since PHP 5.2.0. +Returned by preg_last_error if there was an internal PCRE error. Available since PHP 5.2.0. +Returned by preg_last_error if <link linkend="ini.pcre.backtrack-limit">backtrack limit was exhausted. Available since PHP 5.2.0. +Returned by preg_last_error if <link linkend="ini.pcre.recursion-limit">recursion limit was exhausted. Available since PHP 5.2.0. +Returned by preg_last_error if the last error was caused by malformed UTF-8 data (only when running a regex in <link linkend="reference.pcre.pattern.modifiers">UTF-8 mode ). Available since PHP 5.2.0. +Returned by preg_last_error if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode ). Available since PHP 5.3.0. +PCRE version and release date (e.g. "7.0 18-Dec-2006"). Available since PHP 5.2.4. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1 +2 +4 +8 +16 +32 +64 +-1 +1 +2 +4 +8 +16 +32 +64 +-1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLWordDetector.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java new file mode 100644 index 0000000..89894af --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java @@ -0,0 +1,86 @@ +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ +package net.sourceforge.phpeclipse.phpeditor.util; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Display; + +/** + * Manager for colors used in the Java editor + */ +public class PHPColorProvider { + + public static final RGB MULTI_LINE_COMMENT = new RGB(63, 127, 95); + + public static final RGB SINGLE_LINE_COMMENT = new RGB(63, 127, 95); + + public static final RGB TAG = new RGB(255, 0, 128); + + public static final RGB KEYWORD = new RGB(127, 0, 85); + + public static final RGB VARIABLE = new RGB(127, 159, 191); + + public static final RGB FUNCTION_NAME = new RGB(127, 127, 159); + + public static final RGB STRING_DQ = new RGB(42, 0, 255); + + public static final RGB STRING_SQ = new RGB(42, 0, 255); + + public static final RGB DEFAULT = new RGB(0, 0, 0); + + public static final RGB TYPE = new RGB(127, 0, 85); + + public static final RGB CONSTANT = new RGB(127, 0, 85); + + public static final RGB BACKGROUND = new RGB(255, 255, 255); + + // public static final RGB LINKED_POSITION_COLOR = new RGB(0, 0, 0); + + // public static final RGB LINE_NUMBER_COLOR = new RGB(0, 0, 0); + // public static final RGB BACKGROUND_COLOR = new RGB(255, 255, 255); + + public static final RGB PHPDOC_TAG = new RGB(63, 127, 95); + + public static final RGB PHPDOC_LINK = new RGB(63, 63, 191); + + public static final RGB PHPDOC_DEFAULT = new RGB(63, 95, 191); + + public static final RGB PHPDOC_KEYWORD = new RGB(127, 159, 191); + + protected Map fColorTable = new HashMap(10); + + /** + * Release all of the color resources held onto by the receiver. + */ + public void dispose() { + Iterator e = fColorTable.values().iterator(); + while (e.hasNext()) + ((Color) e.next()).dispose(); + } + + /** + * Return the Color that is stored in the Color table as rgb. + */ + public Color getColor(RGB rgb) { + Color color = (Color) fColorTable.get(rgb); + if (color == null) { + color = new Color(Display.getCurrent(), rgb); + fColorTable.put(rgb, color); + } + return color; + } +} diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPVariableDetector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWhitespaceDetector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPWordDetector.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java new file mode 100644 index 0000000..c088627 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java @@ -0,0 +1,164 @@ +package net.sourceforge.phpeclipse.preferences; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import net.sourceforge.phpdt.internal.core.JavaProject; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTableViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.IContentProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.IStructuredContentProvider; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.Viewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.ide.IDE.SharedImages; + +public class PHPProjectLibraryPage { + protected JavaProject workingProject; + + protected PHPProjectLibraryPage(JavaProject theWorkingProject) { + super(); + workingProject = theWorkingProject; + } + + protected Control getControl(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new FillLayout()); + + Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER + | SWT.MULTI | SWT.FULL_SELECTION); + projectsTable.setHeaderVisible(false); + projectsTable.setLinesVisible(false); + projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); + + TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); + tableColumn.setWidth(200); + tableColumn.setText(PHPPreferencesMessages + .getString("PHPEditorPreferencePageLibraryPage.project")); //$NON-NLS-1$ + + CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer( + projectsTable); + projectsTableViewer.addCheckStateListener(new ICheckStateListener() { + public void checkStateChanged(CheckStateChangedEvent event) { + projectCheckedUnchecked(event); + } + }); + + projectsTableViewer.setContentProvider(getContentProvider()); + projectsTableViewer.setLabelProvider(getLabelProvider()); + + projectsTableViewer.setInput(getWorkspaceProjects()); + projectsTableViewer.setCheckedElements(workingProject + .getReferencedProjects().toArray()); + + return composite; + } + + protected void projectCheckedUnchecked(CheckStateChangedEvent event) { + IProject checkEventProject = (IProject) event.getElement(); + if (event.getChecked()) + getWorkingProject().addLoadPathEntry(checkEventProject); + else + getWorkingProject().removeLoadPathEntry(checkEventProject); + } + + protected JavaProject getWorkingProject() { + return workingProject; + } + + protected List getWorkspaceProjects() { + IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); + return Arrays.asList(root.getProjects()); + } + + protected ITableLabelProvider getLabelProvider() { + ITableLabelProvider labelProvider = new ITableLabelProvider() { + public Image getColumnImage(Object element, int columnIndex) { + IWorkbench workbench = PHPeclipsePlugin.getDefault() + .getWorkbench(); + return workbench.getSharedImages().getImage( + SharedImages.IMG_OBJ_PROJECT); + } + + public String getColumnText(Object element, int columnIndex) { + if (element instanceof IProject) + return ((IProject) element).getName(); + + return PHPPreferencesMessages + .getString("PHPEditorPreferencePageLibraryPage.elementNotIProject"); //$NON-NLS-1$ + } + + public void addListener(ILabelProviderListener listener) { + } + + public void dispose() { + } + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public void removeListener(ILabelProviderListener listener) { + } + }; + + return labelProvider; + } + + protected IContentProvider getContentProvider() { + IStructuredContentProvider contentProvider = new IStructuredContentProvider() { + protected List PHPEditorPreferencePages; + + public Object[] getElements(Object inputElement) { + return PHPEditorPreferencePages.toArray(); + } + + public void dispose() { + } + + public void inputChanged(Viewer viewer, Object oldInput, + Object newInput) { + PHPEditorPreferencePages = new ArrayList(); + + if (!(newInput instanceof List)) + return; + + Iterator workspaceProjectsIterator = ((List) newInput) + .iterator(); + while (workspaceProjectsIterator.hasNext()) { + Object anObject = workspaceProjectsIterator.next(); + if (anObject instanceof IProject) { + IProject project = (IProject) anObject; + if (project.getName() != workingProject.getProject() + .getName()) { + try { + if (project + .hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) + PHPEditorPreferencePages.add(project); + } catch (CoreException e) { + } + } + } + } + } + }; + + return contentProvider; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java new file mode 100644 index 0000000..4f1ae6d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizard.java @@ -0,0 +1,193 @@ +package net.sourceforge.phpeclipse.wizards; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +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.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +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.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWizard; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + +/** + * This wizard creates one file with the extension "html". + */ +public class HTMLFileWizard extends Wizard implements INewWizard { + + private HTMLFileWizardPage page; + + private ISelection selection; + + public HTMLFileWizard() { + super(); + setNeedsProgressMonitor(true); + setWindowTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.html.windowTitle")); + } + + /** + * Adding the page to the wizard. + */ + public void addPages() { + page = new HTMLFileWizardPage(selection); + addPage(page); + } + + /** + * This method is called when 'Finish' button is pressed in the wizard. We + * will create an operation and run it using wizard as execution context. + */ + public boolean performFinish() { + final String containerName = page.getContainerName(); + final String fileName = page.getFileName(); + IRunnableWithProgress op = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) + throws InvocationTargetException { + try { + doFinish(containerName, fileName, monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }; + try { + getContainer().run(true, false, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + Throwable realException = e.getTargetException(); + MessageDialog.openError(getShell(), PHPWizardMessages + .getString("Wizard.error"), realException.getMessage()); + return false; + } + return true; + } + + /** + * The worker method. It will find the container, create the file if missing + * or just replace its contents, and open the editor on the newly created + * file. + */ + private void doFinish(String containerName, String fileName, + IProgressMonitor monitor) throws CoreException { + // create a sample file + monitor.beginTask(PHPWizardMessages + .getString("Wizard.Monitor.creating") + + " " + fileName, 2); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(containerName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + throwCoreException(PHPWizardMessages + .getString("Wizard.Monitor.containerDoesNotExistException")); + } + IContainer container = (IContainer) resource; + final IFile file = container.getFile(new Path(fileName)); + IProject project = file.getProject(); + String projectName = project.getName(); + try { + InputStream stream; + stream = openContentStream(fileName, projectName); + if (file.exists()) { + file.setContents(stream, true, true, monitor); + } else { + file.create(stream, true, monitor); + } + stream.close(); + } catch (IOException e) { + } + monitor.worked(1); + monitor.setTaskName(PHPWizardMessages + .getString("Wizard.Monitor.openingFile")); + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, file, true); + } catch (PartInitException e) { + } + } + }); + monitor.worked(1); + } + + /** + * We will initialize file contents with a sample text. + */ + private InputStream openContentStream(String fileName, String projectname) { + try { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWHTML); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName, projectname); + return new ByteArrayInputStream(StubUtility.evaluateTemplate( + context, template).getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + } + + private void throwCoreException(String message) throws CoreException { + IStatus status = new Status(IStatus.ERROR, + "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); + throw new CoreException(status); + } + + /** + * We will accept the selection in the workbench to see if we can initialize + * from it. + * + * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/HTMLFileWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/NewProjectCreationWizard.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java new file mode 100644 index 0000000..41f06a4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java @@ -0,0 +1,241 @@ +package net.sourceforge.phpeclipse.wizards; + +/********************************************************************** + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + www.phpeclipse.de + **********************************************************************/ + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; + +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +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.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +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.MessageDialog; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWizard; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; + +/** + * This wizard creates one file with the extension "php". + */ +public class PHPFileWizard extends Wizard implements INewWizard { + + private PHPFileWizardPage page; + + private ISelection selection; + + public PHPFileWizard() { + super(); + setNeedsProgressMonitor(true); + setWindowTitle(PHPWizardMessages + .getString("WizardNewProjectCreationPage.windowTitle")); + } + + /** + * Adding the page to the wizard. + */ + public void addPages() { + page = new PHPFileWizardPage(selection); + addPage(page); + } + + /** + * This method is called when 'Finish' button is pressed in the wizard. We + * will create an operation and run it using wizard as execution context. + */ + public boolean performFinish() { + final String containerName = page.getContainerName(); + final String fileName = page.getFileName(); + IRunnableWithProgress op = new IRunnableWithProgress() { + public void run(IProgressMonitor monitor) + throws InvocationTargetException { + try { + doFinish(containerName, fileName, monitor); + } catch (CoreException e) { + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } + } + }; + try { + getContainer().run(true, false, op); + } catch (InterruptedException e) { + return false; + } catch (InvocationTargetException e) { + Throwable realException = e.getTargetException(); + MessageDialog.openError(getShell(), PHPWizardMessages + .getString("Wizard.error"), realException.getMessage()); + return false; + } + return true; + } + + /** + * The worker method. It will find the container, create the file if missing + * or just replace its contents, and open the editor on the newly created + * file. + */ + private void doFinish(String containerName, String fileName, + IProgressMonitor monitor) throws CoreException { + // create a sample file + monitor.beginTask(PHPWizardMessages + .getString("Wizard.Monitor.creating") + + " " + fileName, 2); + IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + IResource resource = root.findMember(new Path(containerName)); + if (!resource.exists() || !(resource instanceof IContainer)) { + throwCoreException(PHPWizardMessages + .getString("Wizard.Monitor.containerDoesNotExistException")); + } + IContainer container = (IContainer) resource; + final IFile file = container.getFile(new Path(fileName)); + IProject project = file.getProject(); + String projectName = project.getName(); + String className = getClassName(fileName); + + try { + InputStream stream; + if (className == null) { + stream = openContentStream(fileName, projectName); + } else { + stream = openContentStreamClass(className); + } + if (file.exists()) { + file.setContents(stream, true, true, monitor); + } else { + file.create(stream, true, monitor); + } + stream.close(); + } catch (IOException e) { + } + monitor.worked(1); + monitor.setTaskName(PHPWizardMessages + .getString("Wizard.Monitor.openingFile")); + getShell().getDisplay().asyncExec(new Runnable() { + public void run() { + IWorkbenchPage page = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); + try { + IDE.openEditor(page, file, true); + } catch (PartInitException e) { + } + } + }); + monitor.worked(1); + } + + /** + * Check if the filename is like this anyname.class.php + * + * @param fFileName + * the filename + * @return the anyname or null + */ + private static final String getClassName(final String fileName) { + final int lastDot = fileName.lastIndexOf('.'); + if (lastDot == -1) + return null; + final int precLastDot = fileName.lastIndexOf('.', lastDot - 1); + if (precLastDot == -1) + return null; + if (!fileName.substring(precLastDot + 1, lastDot).toUpperCase().equals( + "CLASS")) + return null; + return fileName.substring(0, precLastDot); + } + + /** + * We will initialize file contents for a class + * + * @param className + * the classname + */ + private InputStream openContentStreamClass(final String className) { + StringBuffer contents = new StringBuffer(""); + return new ByteArrayInputStream(contents.toString().getBytes()); + } + + /** + * We will initialize file contents with a sample text. + */ + private InputStream openContentStream(String fileName, String projectname) { + try { + Template template = PHPeclipsePlugin.getDefault() + .getCodeTemplateStore().findTemplate( + CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context = new CodeTemplateContext(template + .getContextTypeId(), null, lineDelimiter); + context.setFileNameVariable(fileName, projectname); + String content = StubUtility.evaluateTemplate(context, template); + if (content == null) { + content = ""; + } + return new ByteArrayInputStream(content.getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + + } + + private void throwCoreException(String message) throws CoreException { + IStatus status = new Status(IStatus.ERROR, + "net.sourceforge.phpeclipse.wizards", IStatus.OK, message, null); + throw new CoreException(status); + } + + /** + * We will accept the selection in the workbench to see if we can initialize + * from it. + * + * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection) + */ + public void init(IWorkbench workbench, IStructuredSelection selection) { + this.selection = selection; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPWizardMessages.properties diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/TempnewPHPProject.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizard.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/EditElementWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ElementWriter.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/FormElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/FormElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/FormElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/FormElementWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/HTMLUtilities.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/IPreviewer.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/InsertHTMLElementAction.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/ListElementWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NewElementWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/NumVerifyListener.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/SomeItemInputDialog.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/StringDivider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/StringDivider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/StringDivider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/StringDivider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementCellModifier.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementContentProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementContentProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementContentProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementLabelProvider.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementLabelProvider.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementLabelProvider.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementModel.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementModel.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementModel.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/TableElementWizardPage.java diff --git a/net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java similarity index 100% rename from net.sourceforge.phpeclipse.ui/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java rename to net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/html/UnknownElementWizardPage.java