JBoss Tools SVN: r6152 - trunk.
by jbosstools-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2008-02-07 07:34:33 -0500 (Thu, 07 Feb 2008)
New Revision: 6152
Modified:
trunk/
Log:
Initialized merge tracking via "svnmerge" with revisions "1-6135" from
https://svn.jboss.org/repos/jbosstools/branches/jbosstools-2.0.x
Property changes on: trunk
___________________________________________________________________
Name: svnmerge-integrated
+ /branches/jbosstools-2.0.x:1-6135
16 years, 4 months
JBoss Tools SVN: r6150 - in branches/jbosstools-2.0.x: hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test and 6 other directories.
by jbosstools-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2008-02-07 07:08:40 -0500 (Thu, 07 Feb 2008)
New Revision: 6150
Modified:
branches/jbosstools-2.0.x/
branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/ConsoleConfigurationTest.java
branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/HibernateConsoleTest.java
branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/MappingTestProject.java
branches/jbosstools-2.0.x/jst/plugins/org.jboss.tools.jst.web/resources/meta/web.meta
branches/jbosstools-2.0.x/seam/tests/org.jboss.tools.seam.core.test/src/org/jboss/tools/seam/core/test/SeamValidatorsTest.java
branches/jbosstools-2.0.x/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/BrowserPlugin.java
branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/test/XulRunnerAllTests.java
branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/view/XulRunnerView.java
Log:
Merged revisions 6137-6142 via svnmerge from
https://svn.jboss.org/repos/jbosstools/trunk
........
r6137 | dgolovin | 2008-02-06 23:00:44 +0100 (Wed, 06 Feb 2008) | 1 line
fix errors in testActionHandlers JUnit test
........
r6138 | dgolovin | 2008-02-06 23:16:02 +0100 (Wed, 06 Feb 2008) | 1 line
fix testJiraJbide1631 error: Failure Marker matches the '"foo1" cannot be resolved' pattern wasn't found
........
r6139 | dgolovin | 2008-02-07 02:13:52 +0100 (Thu, 07 Feb 2008) | 1 line
fix for hibernate console tests errors
........
r6140 | dgolovin | 2008-02-07 03:12:11 +0100 (Thu, 07 Feb 2008) | 1 line
Run test only for xulRunner view with about:blank to understand is it started at all? Since it looks like all errors in VPE tests related to XHTML. Now html and struts tests run without errors, but they have html and jsp files.
........
r6141 | dgolovin | 2008-02-07 04:55:39 +0100 (Thu, 07 Feb 2008) | 1 line
rollback code for waitForJobs method
........
r6142 | dgolovin | 2008-02-07 07:15:54 +0100 (Thu, 07 Feb 2008) | 1 line
fix compilation error
........
Property changes on: branches/jbosstools-2.0.x
___________________________________________________________________
Name: svnmerge-integrated
- /trunk:1-6135
+ /trunk:1-6135,6137-6142
Modified: branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/ConsoleConfigurationTest.java
===================================================================
--- branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/ConsoleConfigurationTest.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/ConsoleConfigurationTest.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -1,11 +1,14 @@
package org.hibernate.eclipse.console.test;
import java.io.File;
+import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import junit.framework.TestCase;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.Platform;
import org.hibernate.SessionFactory;
import org.hibernate.console.ConsoleConfiguration;
import org.hibernate.console.ConsoleConfigurationListener;
@@ -13,6 +16,7 @@
import org.hibernate.console.KnownConfigurations;
import org.hibernate.console.QueryPage;
import org.hibernate.console.preferences.ConsoleConfigurationPreferences;
+import org.osgi.framework.Bundle;
import org.w3c.dom.Element;
public class ConsoleConfigurationTest extends TestCase {
@@ -54,7 +58,15 @@
}
public File getConfigXMLFile() {
- return null;
+ File xmlConfig = null;
+ Bundle bundle = HibernateConsoleTestPlugin.getDefault().getBundle();
+ try {
+ URL url = FileLocator.resolve(bundle.getEntry("/res/project/hibernate.cfg.xml"));
+ xmlConfig = new File(url.getFile());
+ } catch (IOException e) {
+ fail("Cannot find /res/project/hibernate.cfg.xml file");
+ }
+ return xmlConfig;
}
public Properties getProperties() {
Modified: branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/HibernateConsoleTest.java
===================================================================
--- branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/HibernateConsoleTest.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/HibernateConsoleTest.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -1,9 +1,13 @@
package org.hibernate.eclipse.console.test;
+import java.util.logging.Logger;
+
import junit.framework.TestCase;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.jobs.IJobManager;
+import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaUI;
@@ -89,7 +93,7 @@
if (!display.readAndDispatch())
display.sleep();
}
- display.update();
+ //display.update();
}
// Otherwise, perform a simple sleep.
@@ -107,9 +111,20 @@
*/
public void waitForJobs() {
while (Platform.getJobManager().currentJob() != null)
- delay(1000);
+ delay(2000);
}
+ public boolean noMoreJobs() {
+ Job[] queuedJobs= Job.getJobManager().find(null);
+ for (int i= 0; i < queuedJobs.length; i++) {
+ Job entry= queuedJobs[i];
+ if (entry.getState() == Job.RUNNING || entry.getState() == Job.WAITING) {
+ return false;
+ }
+ }
+ return true;
+ }
+
protected SimpleTestProject getProject() {
return this.project;
}
Modified: branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/MappingTestProject.java
===================================================================
--- branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/MappingTestProject.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/hibernatetools/tests/org.hibernate.eclipse.console.test/src/org/hibernate/eclipse/console/test/mappingproject/MappingTestProject.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -14,6 +14,8 @@
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -27,6 +29,7 @@
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
@@ -38,6 +41,7 @@
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.PackageFragmentRoot;
+import org.hibernate.eclipse.console.test.HibernateConsoleTestPlugin;
/**
@@ -109,13 +113,16 @@
project.delete(true, true, null);
}
- private void buildBigTestProject() throws JavaModelException, CoreException {
+ private void buildBigTestProject() throws JavaModelException, CoreException, IOException {
project = buildNewProject(PROJECT_NAME);
javaProject = buildJavaProject(project);
-
IPath resourcePath = new Path(RESOURCE_PATH);
File resourceFolder = resourcePath.toFile();
+ URL entry = HibernateConsoleTestPlugin.getDefault().getBundle().getEntry(RESOURCE_PATH);
+ URL resProject = FileLocator.resolve(entry);
+ String tplPrjLcStr= FileLocator.resolve(resProject).getFile();
+ resourceFolder = new File(tplPrjLcStr);
if (!resourceFolder.exists())
throw new RuntimeException("Folder " + RESOURCE_PATH + " not found!");
@@ -340,7 +347,7 @@
StringWriter writer = new StringWriter();
int bytes_read;
while ((bytes_read = reader.read(buffer)) != -1)
- {
+ {resourceFolder.exists()
writer.write(buffer, 0, bytes_read);
}
return (writer.toString());
Modified: branches/jbosstools-2.0.x/jst/plugins/org.jboss.tools.jst.web/resources/meta/web.meta
===================================================================
--- branches/jbosstools-2.0.x/jst/plugins/org.jboss.tools.jst.web/resources/meta/web.meta 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/jst/plugins/org.jboss.tools.jst.web/resources/meta/web.meta 2008-02-07 12:08:40 UTC (rev 6150)
@@ -1063,16 +1063,7 @@
<Editor name="Uneditable"/>
</XModelAttribute>
</XModelAttributes>
- <XActionItem kind="list">
- <XActionItem
- HandlerClassName="org.jboss.tools.struts.webprj.model.handlers.SetLocationHandler"
- ICON="action.webprj.set_location" WizardClassName="%Default%"
- displayName="Set location..." kind="action" name="SetLocation">
- <EntityData EntityName="WebPrjCreateStepDirs">
- <AttributeData AttributeName="location" Mandatory="no"/>
- </EntityData>
- </XActionItem>
- </XActionItem>
+ <XActionItem kind="list"/>
<XDependencies/>
</XModelEntity>
<XModelEntity name="WebPrjRegisterApplication">
@@ -1543,23 +1534,6 @@
HandlerClassName="org.jboss.tools.jst.web.project.handlers.CreateWebPrjHandler"
ICON="main.projects.new" SAVE_REQUIRED="yes"
displayName="Create New Project..." kind="action" name="CreateStrutsProject"/>
- <XActionItem HIDE="always"
- HandlerClassName="org.jboss.tools.struts.webprj.model.handlers.ImportWebPrjHandler"
- ICON="main.projects.item"
- PROPERTIES="support=org.jboss.tools.struts.webprj.model.handlers.ImportWebPrjSupport"
- SAVE_REQUIRED="yes" displayName="Adopt Existing Project..."
- kind="action" name="ImportStrutsProject">
- <EntityData EntityName="WebPrjCreateStepName">
- <AttributeData AttributeName="name"/>
- <AttributeData AttributeName="location"/>
- </EntityData>
- <EntityData EntityName="WebPrjCreateStepDirs">
- <AttributeData AttributeName="webroot"/>
- <AttributeData AttributeName="classes" Mandatory="no"/>
- <AttributeData AttributeName="lib" Mandatory="no"/>
- <AttributeData AttributeName="src" Mandatory="no"/>
- </EntityData>
- </XActionItem>
<XActionItem HandlerClassName="%SpecialWizard%" ICON="action.empty"
PROPERTIES="support=org.jboss.tools.struts.webprj.model.helpers.sync.SyncProjectSupport"
displayName="Modules Configuration" kind="action" name="SynchronizeModules"/>
Modified: branches/jbosstools-2.0.x/seam/tests/org.jboss.tools.seam.core.test/src/org/jboss/tools/seam/core/test/SeamValidatorsTest.java
===================================================================
--- branches/jbosstools-2.0.x/seam/tests/org.jboss.tools.seam.core.test/src/org/jboss/tools/seam/core/test/SeamValidatorsTest.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/seam/tests/org.jboss.tools.seam.core.test/src/org/jboss/tools/seam/core/test/SeamValidatorsTest.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -76,6 +76,13 @@
return seamProject;
}
+ public void testJiraJbide1631() throws CoreException {
+ // Test for http://jira.jboss.com/jira/browse/JBIDE-1631
+ IFile jbide1631XHTMLFile = project.getFile("WebContent/JBIDE-1631.xhtml");
+ assertMarkerIsCreated(jbide1631XHTMLFile, null, "\"foo1\" cannot be resolved", 16 );
+ assertMarkerIsCreated(jbide1631XHTMLFile, null, "\"foo2\" cannot be resolved", 17 );
+ }
+
public void testComponentsValidator() {
ISeamProject seamProject = getSeamProject(project);
@@ -743,13 +750,6 @@
assertTrue("Problem marker has wrong line number", lineNumbers[0] == 22);
}
- public void testJiraJbide1631() throws CoreException {
- // Test for http://jira.jboss.com/jira/browse/JBIDE-1631
- IFile jbide1631XHTMLFile = project.getFile("WebContent/JBIDE-1631.xhtml");
- assertMarkerIsCreated(jbide1631XHTMLFile, null, "\"foo1\" cannot be resolved", 16 );
- assertMarkerIsCreated(jbide1631XHTMLFile, null, "\"foo2\" cannot be resolved", 17 );
- }
-
public void testInheritedMethods() {
ISeamProject seamProject = getSeamProject(project);
Modified: branches/jbosstools-2.0.x/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/BrowserPlugin.java
===================================================================
--- branches/jbosstools-2.0.x/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/BrowserPlugin.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/BrowserPlugin.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -3,6 +3,7 @@
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.jboss.tools.common.log.BaseUIPlugin;
+import org.jboss.tools.common.log.IPluginLog;
import org.osgi.framework.BundleContext;
/**
@@ -64,4 +65,8 @@
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
+
+ public static IPluginLog getPluginLog() {
+ return getDefault();
+ }
}
Modified: branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/test/XulRunnerAllTests.java
===================================================================
--- branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/test/XulRunnerAllTests.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/test/XulRunnerAllTests.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -18,7 +18,7 @@
public static Test suite() {
TestSuite suite = new TestSuite("Test for " + XulRunnerAllTests.class.getName());
//add test cases for dom elements
- suite.addTestSuite(DOMCreatingTest.class);
+ suite.addTestSuite(XulRunnerBrowserTest.class);
return suite;
}
Modified: branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/view/XulRunnerView.java
===================================================================
--- branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/view/XulRunnerView.java 2008-02-07 12:03:04 UTC (rev 6149)
+++ branches/jbosstools-2.0.x/vpe/tests/org.jboss.tools.vpe.xulrunner.test/src/org/jboss/tools/vpe/xulrunner/view/XulRunnerView.java 2008-02-07 12:08:40 UTC (rev 6150)
@@ -1,15 +1,17 @@
package org.jboss.tools.vpe.xulrunner.view;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
+import org.jboss.tools.vpe.xulrunner.BrowserPlugin;
import org.jboss.tools.vpe.xulrunner.XulRunnerException;
import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
public class XulRunnerView extends ViewPart {
- private static final String INIT_URL = "about:buildconfig";
+ private static final String INIT_URL = "about:blank";
private XulRunnerEditor xulrunnerEditor;
@Override
@@ -20,7 +22,7 @@
xulrunnerEditor.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
true, true));
} catch (XulRunnerException e) {
- // Ignore exception
+ BrowserPlugin.getPluginLog().logError(e);
}
}
16 years, 4 months
JBoss Tools SVN: r6149 - branches/jbosstools-2.0.x.
by jbosstools-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2008-02-07 07:03:04 -0500 (Thu, 07 Feb 2008)
New Revision: 6149
Modified:
branches/jbosstools-2.0.x/
Log:
Initialized merge tracking via "svnmerge" with revisions "1-6135" from
https://svn.jboss.org/repos/jbosstools/trunk
Property changes on: branches/jbosstools-2.0.x
___________________________________________________________________
Name: svnmerge-integrated
+ /trunk:1-6135
16 years, 4 months
JBoss Tools SVN: r6148 - trunk/documentation/guides/userguide/GettingStartedGuide/en/modules.
by jbosstools-commits@lists.jboss.org
Author: ykryvinchanka
Date: 2008-02-07 05:58:28 -0500 (Thu, 07 Feb 2008)
New Revision: 6148
Modified:
trunk/documentation/guides/userguide/GettingStartedGuide/en/modules/getting_started.xml
Log:
http://jira.jboss.com/jira/browse/JBDS-235 corrections
Modified: trunk/documentation/guides/userguide/GettingStartedGuide/en/modules/getting_started.xml
===================================================================
--- trunk/documentation/guides/userguide/GettingStartedGuide/en/modules/getting_started.xml 2008-02-07 10:01:53 UTC (rev 6147)
+++ trunk/documentation/guides/userguide/GettingStartedGuide/en/modules/getting_started.xml 2008-02-07 10:58:28 UTC (rev 6148)
@@ -177,7 +177,7 @@
<title>Installing from the downloaded version</title>
<para>Let's start with the JBDS installation.</para>
<para>JBDS comes with a simple installer, bundled with tested/pre-configured versions of Eclipse,
- Webtools, JBossEAP, Seam, and SpringIDE. Thus, to start perform the next steps:</para>
+ WTP, JBossEAP, Seam, and SpringIDE. Thus, to start perform the next steps:</para>
<itemizedlist>
<listitem>
16 years, 4 months
JBoss Tools SVN: r6147 - trunk/jsf/docs/userguide/en/modules.
by jbosstools-commits@lists.jboss.org
Author: ykryvinchanka
Date: 2008-02-07 05:01:53 -0500 (Thu, 07 Feb 2008)
New Revision: 6147
Modified:
trunk/jsf/docs/userguide/en/modules/web_projects.xml
Log:
http://jira.jboss.com/jira/browse/JBDS-226 cale parameter in xml file is defined
Modified: trunk/jsf/docs/userguide/en/modules/web_projects.xml
===================================================================
--- trunk/jsf/docs/userguide/en/modules/web_projects.xml 2008-02-07 10:01:36 UTC (rev 6146)
+++ trunk/jsf/docs/userguide/en/modules/web_projects.xml 2008-02-07 10:01:53 UTC (rev 6147)
@@ -190,7 +190,7 @@
<title>Creating New Navigation Rule</title>
<mediaobject>
<imageobject>
- <imagedata fileref="images/web_projects/web_projects_14.png"/>
+ <imagedata fileref="images/web_projects/web_projects_14.png" scale="90"/>
</imageobject>
</mediaobject>
</figure>
16 years, 4 months
JBoss Tools SVN: r6146 - trunk/common/plugins/org.jboss.tools.common.kb/src/org/jboss/tools/common/kb.
by jbosstools-commits@lists.jboss.org
Author: mareshkau
Date: 2008-02-07 05:01:36 -0500 (Thu, 07 Feb 2008)
New Revision: 6146
Modified:
trunk/common/plugins/org.jboss.tools.common.kb/src/org/jboss/tools/common/kb/KbConnectorFactory.java
Log:
http://jira.jboss.com/jira/browse/JBIDE-1105
Modified: trunk/common/plugins/org.jboss.tools.common.kb/src/org/jboss/tools/common/kb/KbConnectorFactory.java
===================================================================
--- trunk/common/plugins/org.jboss.tools.common.kb/src/org/jboss/tools/common/kb/KbConnectorFactory.java 2008-02-07 09:59:22 UTC (rev 6145)
+++ trunk/common/plugins/org.jboss.tools.common.kb/src/org/jboss/tools/common/kb/KbConnectorFactory.java 2008-02-07 10:01:36 UTC (rev 6146)
@@ -1,108 +1,114 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.common.kb;
-
-import java.util.HashMap;
-
-/**
- * @author eskimo
- */
-public class KbConnectorFactory {
-
- private HashMap<Object,Object> connectorInstances;
-
- private KbConnectorFactory() {
- connectorInstances = new HashMap<Object,Object>();
- }
-
- /**
- *
- * @param type
- * @return
- * @throws ClassNotFoundException
- * @throws InstantiationException
- * @throws IllegalAccessException
- */
- public KbConnector createConnector(KbConnectorType type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
- if(type.isSingleton()) {
- Object o = connectorInstances.get(type.toString());
- if(o!=null) {
- return (KbConnector)o;
- }
- }
- Object newInstance = type.getConnectorClass().newInstance();
- connectorInstances.put(type.toString(), newInstance);
- return (KbConnector) newInstance;
- }
-
- /**
- *
- * @param type
- * @param loader
- * @return
- * @throws InstantiationException
- * @throws IllegalAccessException
- * @throws ClassNotFoundException
- */
- public KbConnector createConnector(KbConnectorType type, ClassLoader loader) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
- if(type.isSingleton()) {
- Object o = connectorInstances.get(type.toString());
- if(o!=null) {
- return (KbConnector)o;
- }
- }
- String className = type.getConnectorClass().getName();
- Class classInstance = Class.forName(className,true,loader);
- Object newInstance = classInstance.newInstance();
- connectorInstances.put(type.toString(), newInstance);
- return (KbConnector) newInstance;
- }
-
- /**
- *
- * @param type
- * @param key
- * @return
- * @throws InstantiationException
- * @throws IllegalAccessException
- * @throws ClassNotFoundException
- */
- public KbConnector createConnector(KbConnectorType type, Object key) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
- Object realKey = key;
- if(type.isSingleton()) {
- Object o = connectorInstances.get(type.toString());
- if(o!=null) {
- return (KbConnector)o;
- } else {
- realKey = type.toString();
- }
- }
- Object o = connectorInstances.get(realKey);
- if(o!=null) {
- return (KbConnector)o;
- }
- Object newInstance = type.getConnectorClass().newInstance();
- connectorInstances.put(realKey, newInstance);
- return (KbConnector) newInstance;
- }
-
- /**
- *
- * @return
- */
- static public KbConnectorFactory getIntstance() {
- return KbConnectionFactoryHolder.INSTANCE;
- }
-
- static class KbConnectionFactoryHolder {
- static final KbConnectorFactory INSTANCE = new KbConnectorFactory();
- }
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.common.kb;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author eskimo
+ */
+public class KbConnectorFactory {
+
+ private Map<Object,Object> connectorInstances;
+
+ private KbConnectorFactory() {
+ connectorInstances = new HashMap<Object,Object>();
+ }
+
+ /**
+ *
+ * @param type
+ * @return
+ * @throws ClassNotFoundException
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ */
+ public KbConnector createConnector(KbConnectorType type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
+ if(type.isSingleton()) {
+ Object o = connectorInstances.get(type.toString());
+ if(o!=null) {
+ return (KbConnector)o;
+ }
+ }
+ Object newInstance = type.getConnectorClass().newInstance();
+ connectorInstances.put(type.toString(), newInstance);
+ return (KbConnector) newInstance;
+ }
+
+ /**
+ *
+ * @param type
+ * @param loader
+ * @return
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ * @throws ClassNotFoundException
+ */
+ public KbConnector createConnector(KbConnectorType type, ClassLoader loader) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
+ if(type.isSingleton()) {
+ Object o = connectorInstances.get(type.toString());
+ if(o!=null) {
+ return (KbConnector)o;
+ }
+ }
+ String className = type.getConnectorClass().getName();
+ Class classInstance = Class.forName(className,true,loader);
+ Object newInstance = classInstance.newInstance();
+ connectorInstances.put(type.toString(), newInstance);
+ return (KbConnector) newInstance;
+ }
+
+ /**
+ *
+ * @param type
+ * @param key
+ * @return
+ * @throws InstantiationException
+ * @throws IllegalAccessException
+ * @throws ClassNotFoundException
+ */
+ public KbConnector createConnector(KbConnectorType type, Object key) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
+ Object realKey = key;
+ if(type.isSingleton()) {
+ Object o = connectorInstances.get(type.toString());
+ if(o!=null) {
+ return (KbConnector)o;
+ } else {
+ realKey = type.toString();
+ }
+ }
+ Object o = connectorInstances.get(realKey);
+ if(o!=null) {
+ return (KbConnector)o;
+ }
+ Object newInstance = type.getConnectorClass().newInstance();
+ connectorInstances.put(realKey, newInstance);
+ return (KbConnector) newInstance;
+ }
+
+ public void removeConnector(KbConnectorType type, Object key) {
+ Object o = connectorInstances.get(key);
+ if (o != null)
+ connectorInstances.remove(key);
+ }
+ /**
+ *
+ * @return
+ */
+ static public KbConnectorFactory getIntstance() {
+ return KbConnectionFactoryHolder.INSTANCE;
+ }
+
+ static class KbConnectionFactoryHolder {
+ static final KbConnectorFactory INSTANCE = new KbConnectorFactory();
+ }
}
\ No newline at end of file
16 years, 4 months
JBoss Tools SVN: r6145 - in trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner: editor and 1 other directory.
by jbosstools-commits@lists.jboss.org
Author: mareshkau
Date: 2008-02-07 04:59:22 -0500 (Thu, 07 Feb 2008)
New Revision: 6145
Modified:
trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/browser/XulRunnerBrowser.java
trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/IXulRunnerVpeResizer.java
trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerEditor.java
trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerVpeResizer.java
Log:
http://jira.jboss.com/jira/browse/JBIDE-1105
Modified: trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/browser/XulRunnerBrowser.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/browser/XulRunnerBrowser.java 2008-02-07 09:57:22 UTC (rev 6144)
+++ trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/browser/XulRunnerBrowser.java 2008-02-07 09:59:22 UTC (rev 6145)
@@ -77,9 +77,9 @@
private static boolean XULRUNNER_LOADING_INDICATOR=false;
static {
- XULRUNNER_BUNDLE = (new StringBuffer("org.mozilla.xulrunner")) //$NON-NLS-1$
- .append(".").append(Platform.getWS()) //$NON-NLS-1$
- .append(".").append(Platform.getOS()) //$NON-NLS-1$
+ XULRUNNER_BUNDLE = (new StringBuffer("org.mozilla.xulrunner")) // $NON-NLS-1$
+ .append(".").append(Platform.getWS()) // $NON-NLS-1$
+ .append(".").append(Platform.getOS()) // $NON-NLS-1$
.append(Platform.OS_MACOSX.equals(Platform.getOS()) ? "" : (new StringBuffer(".")).append(Platform.getOSArch()).toString()) //$NON-NLS-1$ //$NON-NLS-2$
.toString();
@@ -93,7 +93,7 @@
webBrowser = (nsIWebBrowser) browser.getWebBrowser();
if (webBrowser == null) {
- throw new XulRunnerException("nsIWebBrowser is not available"); //$NON-NLS-1$
+ throw new XulRunnerException("nsIWebBrowser is not available"); // $NON-NLS-1$
}
setBoolRootPref(PREFERENCE_DISABLEOPENDURINGLOAD, true);
@@ -108,7 +108,7 @@
// nsIWebProgressListener.NS_IWEBPROGRESSLISTENER_IID);
nsIServiceManager serviceManager = mozilla.getServiceManager();
nsIWebProgress webProgress = (nsIWebProgress) serviceManager
- .getServiceByContractID("@mozilla.org/docloaderservice;1", //$NON-NLS-1$
+ .getServiceByContractID("@mozilla.org/docloaderservice;1", // $NON-NLS-1$
nsIWebProgress.NS_IWEBPROGRESS_IID);
webProgress.addProgressListener(this, nsIWebProgress.NOTIFY_ALL);
@@ -123,7 +123,7 @@
File file = new File(xulRunnerPath);
mozilla.initialize(file);
mozilla.initEmbedding(file, file, new AppFileLocProvider(file));
- System.setProperty(XULRUNNER_INITIALIZED, "true"); //$NON-NLS-1$
+ System.setProperty(XULRUNNER_INITIALIZED, "true"); // $NON-NLS-1$
}
}
@@ -162,12 +162,16 @@
browser.addListener(eventType, listener);
}
+ public void removeListener(int eventType, Listener listener) {
+ browser.removeListener(eventType, listener);
+ }
+
/**
* Decorate Widget.dispose()
*/
public void dispose() {
browser.dispose();
-
+ browser = null;
}
public static String getXulRunnerBundle() {
@@ -219,7 +223,7 @@
URL url1 = FileLocator.resolve(url);
xulRunnerFile = new File(FileLocator.toFileURL(url1).getFile());
} catch (IOException ioe) {
- throw new XulRunnerException("Cannot get path to XULRunner from bundle " + getXulRunnerBundle(), ioe); //$NON-NLS-1$
+ throw new XulRunnerException("Cannot get path to XULRunner from bundle " + getXulRunnerBundle(), ioe); // $NON-NLS-1$
}
}
@@ -426,4 +430,8 @@
public Browser getBrowser() {
return browser;
}
+
+ protected void onDispose() {
+
+ }
}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/IXulRunnerVpeResizer.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/IXulRunnerVpeResizer.java 2008-02-07 09:57:22 UTC (rev 6144)
+++ trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/IXulRunnerVpeResizer.java 2008-02-07 09:59:22 UTC (rev 6145)
@@ -92,4 +92,6 @@
* @param aListener a IVpeResizeListener object
*/
public void removeResizeListener(IVpeResizeListener aListener);
+
+ public void dispose();
}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerEditor.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerEditor.java 2008-02-07 09:57:22 UTC (rev 6144)
+++ trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerEditor.java 2008-02-07 09:59:22 UTC (rev 6145)
@@ -1,516 +1,562 @@
-/*******************************************************************************
- * Copyright (c) 2007 Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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
- *
- * Contributor:
- * Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-
-package org.jboss.tools.vpe.xulrunner.editor;
-
-import java.util.regex.Pattern;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.jboss.tools.vpe.xulrunner.BrowserPlugin;
-import org.jboss.tools.vpe.xulrunner.XPCOM;
-import org.jboss.tools.vpe.xulrunner.XulRunnerException;
-import org.jboss.tools.vpe.xulrunner.browser.XulRunnerBrowser;
-import org.mozilla.interfaces.inIFlasher;
-import org.mozilla.interfaces.nsIBaseWindow;
-import org.mozilla.interfaces.nsIClipboardDragDropHookList;
-import org.mozilla.interfaces.nsIComponentManager;
-import org.mozilla.interfaces.nsIDOMDocument;
-import org.mozilla.interfaces.nsIDOMDocumentRange;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.mozilla.interfaces.nsIDOMRange;
-import org.mozilla.interfaces.nsIDOMWindow;
-import org.mozilla.interfaces.nsIDocShell;
-import org.mozilla.interfaces.nsIDragService;
-import org.mozilla.interfaces.nsIDragSession;
-import org.mozilla.interfaces.nsIInterfaceRequestor;
-import org.mozilla.interfaces.nsISelection;
-import org.mozilla.interfaces.nsIServiceManager;
-import org.mozilla.interfaces.nsISupports;
-import org.mozilla.interfaces.nsITransferable;
-import org.mozilla.xpcom.Mozilla;
-import org.mozilla.xpcom.XPCOMException;
-
-/**
- * @author Sergey Vasilyev (svasilyev(a)exadel.com)
- *
- */
-public class XulRunnerEditor extends XulRunnerBrowser {
- /** IVpeResizeListener */
- private IVpeResizeListener resizeListener;
-
- /** IXulRunnerVpeResizer */
- private IXulRunnerVpeResizer xulRunnerVpeResizer;
-
- /**
- * color which used for highlight elements which user can see
- */
- public static final String flasherVisialElementColor = "blue";
-
- /**
- * color which used for highlight parent elements for elements which user
- * can't see.
- */
- public static final String flasherHiddentElementColor = "red";
-
- /**
- * Contains name of attribute for inIFLasher drawing
- */
- public static String VPEFLASHERCOLORATTRIBUTE="vpeFlasherColorAttribute";
-
- public static final String TRANS_FLAVOR_kHTMLMime = "text/html";
- public static final String TRANS_FLAVOR_kURLDataMime = "text/x-moz-url-data";
- public static final String TRANS_FLAVOR_kFileMime = "application/x-moz-file";
- public static final String TRANS_FLAVOR_kURLMime = "text/x-moz-url";
- public static final String TRANS_FLAVOR_kUnicodeMime = "text/unicode";
- public static final String TRANS_FLAVOR_kNativeHTMLMime = "application/x-moz-nativehtml";
-
- /**
- * xpcom flasher component which used to draw lines
- */
- private inIFlasher iFlasher;
- private nsIDocShell docShell = null;
-
- /**
- * RegExp for find expression 'display : none' in style string
- */
- private static final Pattern PATTERN = Pattern.compile(".*\\s*(display)\\s*:\\s*(none)\\s*;.*",Pattern.CASE_INSENSITIVE+Pattern.DOTALL);
-
- /**
- * Contains attribute name for style
- */
- private static final String STYLE_ATTR="style";
-
- private nsIDOMElement lastSelectedElement;
- private int lastResizerConstrains;
- /**
- * Scroll selection into view flag
- */
- private boolean scrollRegtangleFlag = false;
-
- /**
- * @param parent
- * @throws XulRunnerException
- */
- public XulRunnerEditor(Composite parent) throws XulRunnerException {
- super(parent);
-
- Listener eventListenet = new Listener() {
-
- public void handleEvent(Event event) {
- Display.getCurrent().asyncExec(new Thread(){
- public void run(){
- showSelectionRectangle();
- }
- });
- }};
-// addListener(SWT.Activate, eventListenet);
- addListener(SWT.Paint, eventListenet);
- //Commented by Max Areshkau (bug on Mac OS X10.4
- //when switch from visual to preview selection rectangle doen't disappear
-// addListener(SWT.Resize, eventListenet);
- addListener(SWT.Show, eventListenet);
- addListener(SWT.FocusIn, eventListenet);
- //Commented by Max Areshkau (bug on Mac OS X10.4
- //when switch from visual to preview selection rectangle doen't disappear
-// addListener(SWT.FocusOut, eventListenet);
- addListener(SWT.Selection, eventListenet);
- addListener(SWT.Paint, eventListenet);
-
- resizeListener = new IVpeResizeListener() {
- public void onEndResizing(int usedResizeMarkerHandle, int top,
- int left, int width, int height,
- nsIDOMElement resizedDomElement) {
- endResizing(usedResizeMarkerHandle, top, left, width, height, resizedDomElement);
- }
-
- public nsISupports queryInterface(String uuid) {
- return null;
- }
- };
-
-
- }
-
- public boolean isMozillaDragFlavor() {
-
- nsIDragSession dragSession = getCurrentDragSession();
- if (dragSession != null) {
- nsITransferable transferable = createTransferable();
- if (transferable != null) {
-// transferable.flavorsTransferableCanImport();
-
- transferable.addDataFlavor(TRANS_FLAVOR_kURLDataMime);
- transferable.addDataFlavor(TRANS_FLAVOR_kFileMime);
- transferable.addDataFlavor(TRANS_FLAVOR_kURLMime);
- transferable.addDataFlavor(TRANS_FLAVOR_kUnicodeMime);
- dragSession.getData(transferable, 0);
-
-// transferable.flavorsTransferableCanImport();
- String[] flavors = new String[] {null};
- nsISupports[] data = new nsISupports[] {null};
- long[] length = new long[] {0};
- transferable.getAnyTransferData(flavors, data, length);
-
- return length[0] > 0;
- }
- }
- return false;
- }
-
- public void onElementResize(nsIDOMElement element, int handle, int top, int left, int width, int height) {
- }
-
- public void onLoadWindow() {
- if (getIXulRunnerVpeResizer() != null) {
- getIXulRunnerVpeResizer().init(getDOMDocument());
- getIXulRunnerVpeResizer().addResizeListener(resizeListener);
- }
-
- }
-
- public nsIDragSession getCurrentDragSession() {
- nsIServiceManager serviceManager = getServiceManager();
- nsIDragService dragService = (nsIDragService) serviceManager.getServiceByContractID(XPCOM.NS_DRAGSERVICE_CONTRACTID, nsIDragService.NS_IDRAGSERVICE_IID);
-
- return dragService.getCurrentSession();
- }
-
- public nsIClipboardDragDropHookList getClipboardDragDropHookList() {
- nsIDocShell docShell = getDocShell();
-
- if (docShell != null) {
- nsIClipboardDragDropHookList hookList = (nsIClipboardDragDropHookList) docShell.queryInterface(nsIClipboardDragDropHookList.NS_ICLIPBOARDDRAGDROPHOOKLIST_IID);
- return hookList;
- }
- return null;
- }
-
- public nsIDocShell getDocShell() {
- if (docShell == null) {
- nsIInterfaceRequestor interfaceRequestor = (nsIInterfaceRequestor) getWebBrowser().queryInterface(nsIInterfaceRequestor.NS_IINTERFACEREQUESTOR_IID);
- docShell = (nsIDocShell) interfaceRequestor.getInterface(nsIDocShell.NS_IDOCSHELL_IID);
- }
-
- return docShell;
- }
-
- public nsIDOMDocument getDOMDocument() {
- nsIDOMWindow domWindow = getWebBrowser().getContentDOMWindow();
- return domWindow.getDocument();
- }
-
- public nsIDOMDocumentRange getDOMDocumentRange() {
- return (nsIDOMDocumentRange) getDOMDocument().queryInterface(nsIDOMDocumentRange.NS_IDOMDOCUMENTRANGE_IID);
- }
-
- public nsIDOMRange createDOMRange() {
- return getDOMDocumentRange().createRange();
- }
-
- public void showDragCaret(nsIDOMNode node, long offcet) {
- // TODO Sergey Vasilyev figure out with caret
- System.out.println("Show drag caret for " + node.getNodeName() + ":" + offcet);
- }
-
- public void hideDragCaret() {
- // TODO Sergey Vasilyev figure out with caret
- System.out.println("Hide drag caret");
- }
-
- public nsITransferable createTransferable() {
- nsIComponentManager componentManager = getComponentManager();
- return (nsITransferable) componentManager.createInstanceByContractID(XPCOM.NS_TRANSFERABLE_CONTRACTID, this, nsITransferable.NS_ITRANSFERABLE_IID);
- }
-
- /**
- * Returns selection controller which used in selection functionality
- * @return
- */
- public nsISelection getSelection() {
-
- nsIDOMWindow domWindow = getWebBrowser().getContentDOMWindow();
- nsISelection selection = domWindow.getSelection();
- return selection;
- }
-
- /**
- * Function created to restore functionality of MozillaBrowser
- * @return
- */
- public nsIDOMElement getLastSelectedElement() {
-
- return lastSelectedElement;
- }
- /**
- * Function created to restore functionality of MozillaBrowser
- * @return
- */
- private void setLastSelectedElement(nsIDOMElement lastSelectedElement) {
- this.lastSelectedElement = lastSelectedElement;
- }
-
- /**
- * Draws rectangle around the element.
- * @param element
- * @param resizerConstrains
- * @param scroll
- */
- public void setSelectionRectangle(nsIDOMElement element, int resizerConstrains, boolean scroll) {
- if (getIFlasher() == null) {
-
- return;
- }
- if (getLastSelectedElement() != null) {
-
- scrollRegtangleFlag = scroll && element != null;
-
- if(checkVisability(getLastSelectedElement())){
-
- if((getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
- (!getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
-
- getIFlasher().setColor(flasherVisialElementColor);
- } else{
- getIFlasher().setColor(flasherHiddentElementColor);
- }
-
- getIFlasher().repaintElement(getLastSelectedElement());
-
- }else {
-
- getIFlasher().setColor(flasherHiddentElementColor);
- nsIDOMElement domElement = findVisbleParentElement(getLastSelectedElement());
-
- if(domElement!=null) {
-
- getIFlasher().repaintElement(domElement);
- }
-
- }
-
- } else if (element != null) {
-
- if (scroll) {
- scrollToElement(element);
- scrollRegtangleFlag = true;
- }
- if(checkVisability(element)){
-
-
- if((element.getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
- (!element.getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
-
- getIFlasher().setColor(flasherVisialElementColor);
- }else {
- getIFlasher().setColor(flasherHiddentElementColor);
- }
- getIFlasher().drawElementOutline(element);
- }else {
-
- getIFlasher().setColor(flasherHiddentElementColor);
- nsIDOMElement domElement = findVisbleParentElement(element);
-
- if(domElement!=null) {
-
- getIFlasher().drawElementOutline(domElement);
- }
- }
-
-
- }
-
- if (xulRunnerVpeResizer != null) {
- if (element != null && resizerConstrains != 0) {
- xulRunnerVpeResizer.show(element, resizerConstrains);
- } else {
- xulRunnerVpeResizer.hide();
- }
- }
-
- setLastSelectedElement(element);
- lastResizerConstrains = resizerConstrains;
- }
-
-
- /**
- * @return the iFlasher
- */
- private inIFlasher getIFlasher() {
-
- if(iFlasher==null) {
- nsIServiceManager serviceManager = Mozilla.getInstance().getServiceManager();
- iFlasher = (inIFlasher) serviceManager.getServiceByContractID(XPCOM.IN_FLASHER_CONTRACTID, inIFlasher.INIFLASHER_IID);
- iFlasher.setThickness(2);
- }
- return iFlasher;
- }
-
-
- private IXulRunnerVpeResizer getIXulRunnerVpeResizer() {
-
- if (xulRunnerVpeResizer==null) {
- xulRunnerVpeResizer = new XulRunnerVpeResizer();
- }
- return xulRunnerVpeResizer;
- }
-
-
-
- /**Function created for checking if user can see element or not.
- * Element doesn't shows in VPE if it's has 'display:none;' attribute in style.
- *
- * @param node for checking it's visability
- * @param iFlasher flasher which used for drawning border for elements adn in
- * which was setted color in depends of visability of element
- *
- * @return false for hiddent elements and true for visble elements
- */
- private boolean checkVisability(nsIDOMNode node){
-
- nsIDOMElement domElement;
- try{
-
- domElement = (nsIDOMElement) node.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
-
- } catch(XPCOMException exception) {
- //if we can cast it's is invisible elenebt
- return false;
- }
-
- //TODO add check not inline styles attribute such as styleclass
- String inlineStyle = domElement.getAttribute(STYLE_ATTR);
-
- return inlineStyle==null?true:!PATTERN.matcher(inlineStyle).matches();
- }
-
- /**
- * Finds visible nearest visible node for hidden node
- *
- * @param element
- *
- * @return nearest visible node or null if can't find
- */
- private nsIDOMElement findVisbleParentElement(nsIDOMElement element) {
-
- nsIDOMElement parentElement;
-
- try {
-
- parentElement = (nsIDOMElement) element.getParentNode()
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- } catch (XPCOMException ex) {
- // if parent node isn't nsIDOMElement just return null;
- return null;
- }
- while(parentElement!=null&&!checkVisability(parentElement)) {
- if(checkVisability(parentElement)) {
-
- return parentElement;
- }else {
-
- parentElement = (nsIDOMElement) parentElement.getParentNode()
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
-
- }
- }
- return parentElement;
- }
-
- /**
- * @param usedHandle
- * @param newTop
- * @param newLeft
- * @param newWidth
- * @param newHeight
- * @param aResizedObject
- */
- private void endResizing(int usedHandle, int newTop, int newLeft, int newWidth, int newHeight, nsIDOMElement aResizedObject) {
- onElementResize(aResizedObject, usedHandle, newTop, newLeft, newWidth, newHeight);
- }
-
- /**
- *
- */
- public void showResizer() {
- if (xulRunnerVpeResizer != null && lastSelectedElement != null && lastResizerConstrains != 0) {
- xulRunnerVpeResizer.show(lastSelectedElement, lastResizerConstrains);
- }
- }
-
- /**
- * Hide resizer markers
- */
- public void hideResizer() {
- if(xulRunnerVpeResizer != null) {
- xulRunnerVpeResizer.hide();
- }
- }
-
- public void showSelectionRectangle() {
-
-// ((nsIBaseWindow)getWebBrowser().queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID)).repaint(false);
-
- if (getIFlasher() != null && getLastSelectedElement() != null) {
- if (scrollRegtangleFlag) {
- scrollRegtangleFlag = false;
-
- scrollToElement(getLastSelectedElement());
- }
- //checks visability of element
- if(checkVisability(getLastSelectedElement())){
-
- if((getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
- (!getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
-
- getIFlasher().setColor(flasherVisialElementColor);
- }else{
-
- getIFlasher().setColor(flasherHiddentElementColor);
- }
-
- getIFlasher().drawElementOutline(getLastSelectedElement());
- }else {
-
- getIFlasher().setColor(flasherHiddentElementColor);
- nsIDOMElement domElement = findVisbleParentElement(getLastSelectedElement());
-
- if(domElement!=null) {
- getIFlasher().drawElementOutline(domElement);
- }
- }
- } else if(getIFlasher()!=null&&Platform.getOSArch().equals(Platform.OS_MACOSX)){
- //Max Areshkau (bug on Mac OS X, when we switch to preview from other view, selection rectangle doesn't disappear
- //TODO Max Areshkau (may be exist passability not draw selection on resize event when we switches to other view)
- try {
- ((nsIBaseWindow)getWebBrowser().queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID)).repaint(true);
- } catch(XPCOMException ex) {
- //just ignore its
- BrowserPlugin.getDefault().logInfo("repaint failed", ex);
- }
- }
- }
- /**
- * Scrools viiew to some elements
- * @param element -element to which we should scroll
- */
- private void scrollToElement(nsIDOMElement element){
-
- getIFlasher().scrollElementIntoView(element);
- }
-}
-
-
+/*******************************************************************************
+ * Copyright (c) 2007 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+
+package org.jboss.tools.vpe.xulrunner.editor;
+
+import java.util.regex.Pattern;
+
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.jboss.tools.vpe.xulrunner.BrowserPlugin;
+import org.jboss.tools.vpe.xulrunner.XPCOM;
+import org.jboss.tools.vpe.xulrunner.XulRunnerException;
+import org.jboss.tools.vpe.xulrunner.browser.XulRunnerBrowser;
+import org.mozilla.interfaces.inIFlasher;
+import org.mozilla.interfaces.nsIBaseWindow;
+import org.mozilla.interfaces.nsIClipboardDragDropHookList;
+import org.mozilla.interfaces.nsIComponentManager;
+import org.mozilla.interfaces.nsIDOMDocument;
+import org.mozilla.interfaces.nsIDOMDocumentRange;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.mozilla.interfaces.nsIDOMRange;
+import org.mozilla.interfaces.nsIDOMWindow;
+import org.mozilla.interfaces.nsIDocShell;
+import org.mozilla.interfaces.nsIDragService;
+import org.mozilla.interfaces.nsIDragSession;
+import org.mozilla.interfaces.nsIInterfaceRequestor;
+import org.mozilla.interfaces.nsISelection;
+import org.mozilla.interfaces.nsISelectionListener;
+import org.mozilla.interfaces.nsISelectionPrivate;
+import org.mozilla.interfaces.nsIServiceManager;
+import org.mozilla.interfaces.nsISupports;
+import org.mozilla.interfaces.nsITooltipListener;
+import org.mozilla.interfaces.nsITransferable;
+import org.mozilla.interfaces.nsIWebProgressListener;
+import org.mozilla.xpcom.Mozilla;
+import org.mozilla.xpcom.XPCOMException;
+
+/**
+ * @author Sergey Vasilyev (svasilyev(a)exadel.com)
+ *
+ */
+public class XulRunnerEditor extends XulRunnerBrowser {
+ /** IVpeResizeListener */
+ private IVpeResizeListener resizeListener;
+
+ /** IXulRunnerVpeResizer */
+ private IXulRunnerVpeResizer xulRunnerVpeResizer;
+
+ /**
+ * color which used for highlight elements which user can see
+ */
+ public static final String flasherVisialElementColor = "blue";
+
+ /**
+ * color which used for highlight parent elements for elements which user
+ * can't see.
+ */
+ public static final String flasherHiddentElementColor = "red";
+
+ /**
+ * Contains name of attribute for inIFLasher drawing
+ */
+ public static String VPEFLASHERCOLORATTRIBUTE="vpeFlasherColorAttribute";
+
+ public static final String TRANS_FLAVOR_kHTMLMime = "text/html";
+ public static final String TRANS_FLAVOR_kURLDataMime = "text/x-moz-url-data";
+ public static final String TRANS_FLAVOR_kFileMime = "application/x-moz-file";
+ public static final String TRANS_FLAVOR_kURLMime = "text/x-moz-url";
+ public static final String TRANS_FLAVOR_kUnicodeMime = "text/unicode";
+ public static final String TRANS_FLAVOR_kNativeHTMLMime = "application/x-moz-nativehtml";
+
+ /**
+ * xpcom flasher component which used to draw lines
+ */
+ private inIFlasher iFlasher;
+ private nsIDocShell docShell = null;
+
+ /**
+ * RegExp for find expression 'display : none' in style string
+ */
+ private static final Pattern PATTERN = Pattern.compile(".*\\s*(display)\\s*:\\s*(none)\\s*;.*",Pattern.CASE_INSENSITIVE+Pattern.DOTALL);
+
+ /**
+ * Contains attribute name for style
+ */
+ private static final String STYLE_ATTR="style";
+
+ private nsIDOMElement lastSelectedElement;
+ private int lastResizerConstrains;
+ /**
+ * Scroll selection into view flag
+ */
+ private boolean scrollRegtangleFlag = false;
+
+ private nsISelectionListener selectionListener;
+
+ private Listener eventListenet = new Listener() {
+
+ public void handleEvent(Event event) {
+ Display.getCurrent().asyncExec(new Thread(){
+ public void run(){
+ showSelectionRectangle();
+ }
+ });
+ }};
+ /**
+ * @param parent
+ * @throws XulRunnerException
+ */
+ public XulRunnerEditor(Composite parent) throws XulRunnerException {
+ super(parent);
+ getBrowser().addDisposeListener(new DisposeListener() {
+
+ public void widgetDisposed(DisposeEvent e) {
+ //TODO Max Areshkau this caused en error when we close editor under Mac OS
+// getWebBrowser().removeWebBrowserListener(XulRunnerEditor.this, nsIWebProgressListener.NS_IWEBPROGRESSLISTENER_IID);
+ getWebBrowser().removeWebBrowserListener(XulRunnerEditor.this, nsITooltipListener.NS_ITOOLTIPLISTENER_IID);
+ if (selectionListener != null) {
+ nsISelection selection = getSelection();
+ nsISelectionPrivate selectionPrivate = (nsISelectionPrivate) selection.queryInterface(nsISelectionPrivate.NS_ISELECTIONPRIVATE_IID);
+ selectionPrivate.removeSelectionListener(selectionListener);
+ }
+ if (resizeListener != null)
+ getIXulRunnerVpeResizer().removeResizeListener(resizeListener);
+ xulRunnerVpeResizer.dispose();
+ xulRunnerVpeResizer = null;
+ resizeListener = null;
+ if (eventListenet != null) {
+ removeListener(SWT.Paint, eventListenet);
+ removeListener(SWT.Show, eventListenet);
+ removeListener(SWT.FocusIn, eventListenet);
+ removeListener(SWT.Selection, eventListenet);
+ removeListener(SWT.Paint, eventListenet);
+ eventListenet = null;
+ }
+ getBrowser().removeDisposeListener(this);
+ onDispose();
+ }
+
+ });
+
+// addListener(SWT.Activate, eventListenet);
+ addListener(SWT.Paint, eventListenet);
+ //Commented by Max Areshkau (bug on Mac OS X10.4
+ //when switch from visual to preview selection rectangle doen't disappear
+// addListener(SWT.Resize, eventListenet);
+ addListener(SWT.Show, eventListenet);
+ addListener(SWT.FocusIn, eventListenet);
+ //Commented by Max Areshkau (bug on Mac OS X10.4
+ //when switch from visual to preview selection rectangle doen't disappear
+// addListener(SWT.FocusOut, eventListenet);
+ addListener(SWT.Selection, eventListenet);
+ addListener(SWT.Paint, eventListenet);
+
+ resizeListener = new IVpeResizeListener() {
+ public void onEndResizing(int usedResizeMarkerHandle, int top,
+ int left, int width, int height,
+ nsIDOMElement resizedDomElement) {
+ endResizing(usedResizeMarkerHandle, top, left, width, height, resizedDomElement);
+ }
+
+ public nsISupports queryInterface(String uuid) {
+ return null;
+ }
+ };
+
+
+ }
+
+ public boolean isMozillaDragFlavor() {
+
+ nsIDragSession dragSession = getCurrentDragSession();
+ if (dragSession != null) {
+ nsITransferable transferable = createTransferable();
+ if (transferable != null) {
+// transferable.flavorsTransferableCanImport();
+
+ transferable.addDataFlavor(TRANS_FLAVOR_kURLDataMime);
+ transferable.addDataFlavor(TRANS_FLAVOR_kFileMime);
+ transferable.addDataFlavor(TRANS_FLAVOR_kURLMime);
+ transferable.addDataFlavor(TRANS_FLAVOR_kUnicodeMime);
+ dragSession.getData(transferable, 0);
+
+// transferable.flavorsTransferableCanImport();
+ String[] flavors = new String[] {null};
+ nsISupports[] data = new nsISupports[] {null};
+ long[] length = new long[] {0};
+ transferable.getAnyTransferData(flavors, data, length);
+
+ return length[0] > 0;
+ }
+ }
+ return false;
+ }
+
+ public void onElementResize(nsIDOMElement element, int handle, int top, int left, int width, int height) {
+ }
+
+ public void onLoadWindow() {
+ if (getIXulRunnerVpeResizer() != null) {
+ getIXulRunnerVpeResizer().init(getDOMDocument());
+ getIXulRunnerVpeResizer().addResizeListener(resizeListener);
+ }
+
+ }
+
+ public nsIDragSession getCurrentDragSession() {
+ nsIServiceManager serviceManager = getServiceManager();
+ nsIDragService dragService = (nsIDragService) serviceManager.getServiceByContractID(XPCOM.NS_DRAGSERVICE_CONTRACTID, nsIDragService.NS_IDRAGSERVICE_IID);
+
+ return dragService.getCurrentSession();
+ }
+
+ public nsIClipboardDragDropHookList getClipboardDragDropHookList() {
+ nsIDocShell docShell = getDocShell();
+
+ if (docShell != null) {
+ nsIClipboardDragDropHookList hookList = (nsIClipboardDragDropHookList) docShell.queryInterface(nsIClipboardDragDropHookList.NS_ICLIPBOARDDRAGDROPHOOKLIST_IID);
+ return hookList;
+ }
+ return null;
+ }
+
+ public nsIDocShell getDocShell() {
+ if (docShell == null) {
+ nsIInterfaceRequestor interfaceRequestor = (nsIInterfaceRequestor) getWebBrowser().queryInterface(nsIInterfaceRequestor.NS_IINTERFACEREQUESTOR_IID);
+ docShell = (nsIDocShell) interfaceRequestor.getInterface(nsIDocShell.NS_IDOCSHELL_IID);
+ }
+
+ return docShell;
+ }
+
+ public nsIDOMDocument getDOMDocument() {
+ nsIDOMWindow domWindow = getWebBrowser().getContentDOMWindow();
+ return domWindow.getDocument();
+ }
+
+ public nsIDOMDocumentRange getDOMDocumentRange() {
+ return (nsIDOMDocumentRange) getDOMDocument().queryInterface(nsIDOMDocumentRange.NS_IDOMDOCUMENTRANGE_IID);
+ }
+
+ public nsIDOMRange createDOMRange() {
+ return getDOMDocumentRange().createRange();
+ }
+
+ public void showDragCaret(nsIDOMNode node, long offcet) {
+ // TODO Sergey Vasilyev figure out with caret
+ System.out.println("Show drag caret for " + node.getNodeName() + ":" + offcet);
+ }
+
+ public void hideDragCaret() {
+ // TODO Sergey Vasilyev figure out with caret
+ System.out.println("Hide drag caret");
+ }
+
+ public nsITransferable createTransferable() {
+ nsIComponentManager componentManager = getComponentManager();
+ return (nsITransferable) componentManager.createInstanceByContractID(XPCOM.NS_TRANSFERABLE_CONTRACTID, this, nsITransferable.NS_ITRANSFERABLE_IID);
+ }
+
+ /**
+ * Returns selection controller which used in selection functionality
+ * @return
+ */
+ public nsISelection getSelection() {
+
+ nsIDOMWindow domWindow = getWebBrowser().getContentDOMWindow();
+ nsISelection selection = domWindow.getSelection();
+ return selection;
+ }
+
+ /**
+ * Function created to restore functionality of MozillaBrowser
+ * @return
+ */
+ public nsIDOMElement getLastSelectedElement() {
+
+ return lastSelectedElement;
+ }
+ /**
+ * Function created to restore functionality of MozillaBrowser
+ * @return
+ */
+ private void setLastSelectedElement(nsIDOMElement lastSelectedElement) {
+ this.lastSelectedElement = lastSelectedElement;
+ }
+
+ /**
+ * Draws rectangle around the element.
+ * @param element
+ * @param resizerConstrains
+ * @param scroll
+ */
+ public void setSelectionRectangle(nsIDOMElement element, int resizerConstrains, boolean scroll) {
+ if (getIFlasher() == null) {
+
+ return;
+ }
+ if (getLastSelectedElement() != null) {
+
+ scrollRegtangleFlag = scroll && element != null;
+
+ if(checkVisability(getLastSelectedElement())){
+
+ if((getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
+ (!getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
+
+ getIFlasher().setColor(flasherVisialElementColor);
+ } else{
+ getIFlasher().setColor(flasherHiddentElementColor);
+ }
+
+ getIFlasher().repaintElement(getLastSelectedElement());
+
+ }else {
+
+ getIFlasher().setColor(flasherHiddentElementColor);
+ nsIDOMElement domElement = findVisbleParentElement(getLastSelectedElement());
+
+ if(domElement!=null) {
+
+ getIFlasher().repaintElement(domElement);
+ }
+
+ }
+
+ } else if (element != null) {
+
+ if (scroll) {
+ scrollToElement(element);
+ scrollRegtangleFlag = true;
+ }
+ if(checkVisability(element)){
+
+
+ if((element.getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
+ (!element.getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
+
+ getIFlasher().setColor(flasherVisialElementColor);
+ }else {
+ getIFlasher().setColor(flasherHiddentElementColor);
+ }
+ getIFlasher().drawElementOutline(element);
+ }else {
+
+ getIFlasher().setColor(flasherHiddentElementColor);
+ nsIDOMElement domElement = findVisbleParentElement(element);
+
+ if(domElement!=null) {
+
+ getIFlasher().drawElementOutline(domElement);
+ }
+ }
+
+
+ }
+
+ if (xulRunnerVpeResizer != null) {
+ if (element != null && resizerConstrains != 0) {
+ xulRunnerVpeResizer.show(element, resizerConstrains);
+ } else {
+ xulRunnerVpeResizer.hide();
+ }
+ }
+
+ setLastSelectedElement(element);
+ lastResizerConstrains = resizerConstrains;
+ }
+
+
+ /**
+ * @return the iFlasher
+ */
+ private inIFlasher getIFlasher() {
+
+ if(iFlasher==null) {
+ nsIServiceManager serviceManager = Mozilla.getInstance().getServiceManager();
+ iFlasher = (inIFlasher) serviceManager.getServiceByContractID(XPCOM.IN_FLASHER_CONTRACTID, inIFlasher.INIFLASHER_IID);
+ iFlasher.setThickness(2);
+ }
+ return iFlasher;
+ }
+
+
+ private IXulRunnerVpeResizer getIXulRunnerVpeResizer() {
+
+ if (xulRunnerVpeResizer==null) {
+ xulRunnerVpeResizer = new XulRunnerVpeResizer();
+ }
+ return xulRunnerVpeResizer;
+ }
+
+
+
+ /**Function created for checking if user can see element or not.
+ * Element doesn't shows in VPE if it's has 'display:none;' attribute in style.
+ *
+ * @param node for checking it's visability
+ * @param iFlasher flasher which used for drawning border for elements adn in
+ * which was setted color in depends of visability of element
+ *
+ * @return false for hiddent elements and true for visble elements
+ */
+ private boolean checkVisability(nsIDOMNode node){
+
+ nsIDOMElement domElement;
+ try{
+
+ domElement = (nsIDOMElement) node.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+
+ } catch(XPCOMException exception) {
+ //if we can cast it's is invisible elenebt
+ return false;
+ }
+
+ //TODO add check not inline styles attribute such as styleclass
+ String inlineStyle = domElement.getAttribute(STYLE_ATTR);
+
+ return inlineStyle==null?true:!PATTERN.matcher(inlineStyle).matches();
+ }
+
+ /**
+ * Finds visible nearest visible node for hidden node
+ *
+ * @param element
+ *
+ * @return nearest visible node or null if can't find
+ */
+ private nsIDOMElement findVisbleParentElement(nsIDOMElement element) {
+
+ nsIDOMElement parentElement;
+
+ try {
+
+ parentElement = (nsIDOMElement) element.getParentNode()
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ } catch (XPCOMException ex) {
+ // if parent node isn't nsIDOMElement just return null;
+ return null;
+ }
+ while(parentElement!=null&&!checkVisability(parentElement)) {
+ if(checkVisability(parentElement)) {
+
+ return parentElement;
+ }else {
+
+ parentElement = (nsIDOMElement) parentElement.getParentNode()
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+
+ }
+ }
+ return parentElement;
+ }
+
+ /**
+ * @param usedHandle
+ * @param newTop
+ * @param newLeft
+ * @param newWidth
+ * @param newHeight
+ * @param aResizedObject
+ */
+ private void endResizing(int usedHandle, int newTop, int newLeft, int newWidth, int newHeight, nsIDOMElement aResizedObject) {
+ onElementResize(aResizedObject, usedHandle, newTop, newLeft, newWidth, newHeight);
+ }
+
+ /**
+ *
+ */
+ public void showResizer() {
+ if (xulRunnerVpeResizer != null && lastSelectedElement != null && lastResizerConstrains != 0) {
+ xulRunnerVpeResizer.show(lastSelectedElement, lastResizerConstrains);
+ }
+ }
+
+ /**
+ * Hide resizer markers
+ */
+ public void hideResizer() {
+ if(xulRunnerVpeResizer != null) {
+ xulRunnerVpeResizer.hide();
+ }
+ }
+
+ public void showSelectionRectangle() {
+
+// ((nsIBaseWindow)getWebBrowser().queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID)).repaint(false);
+
+ if (getIFlasher() != null && getLastSelectedElement() != null) {
+ if (scrollRegtangleFlag) {
+ scrollRegtangleFlag = false;
+
+ scrollToElement(getLastSelectedElement());
+ }
+ //checks visability of element
+ if(checkVisability(getLastSelectedElement())){
+
+ if((getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE)==null)||
+ (!getLastSelectedElement().getAttribute(VPEFLASHERCOLORATTRIBUTE).equals(flasherHiddentElementColor))) {
+
+ getIFlasher().setColor(flasherVisialElementColor);
+ }else{
+
+ getIFlasher().setColor(flasherHiddentElementColor);
+ }
+
+ getIFlasher().drawElementOutline(getLastSelectedElement());
+ }else {
+
+ getIFlasher().setColor(flasherHiddentElementColor);
+ nsIDOMElement domElement = findVisbleParentElement(getLastSelectedElement());
+
+ if(domElement!=null) {
+ getIFlasher().drawElementOutline(domElement);
+ }
+ }
+ } else if(getIFlasher()!=null&&Platform.getOSArch().equals(Platform.OS_MACOSX)){
+ //Max Areshkau (bug on Mac OS X, when we switch to preview from other view, selection rectangle doesn't disappear
+ //TODO Max Areshkau (may be exist passability not draw selection on resize event when we switches to other view)
+ try {
+ ((nsIBaseWindow)getWebBrowser().queryInterface(nsIBaseWindow.NS_IBASEWINDOW_IID)).repaint(true);
+ } catch(XPCOMException ex) {
+ //just ignore its
+ BrowserPlugin.getDefault().logInfo("repaint failed", ex);
+ }
+ }
+ }
+ /**
+ * Scrools viiew to some elements
+ * @param element -element to which we should scroll
+ */
+ private void scrollToElement(nsIDOMElement element){
+
+ getIFlasher().scrollElementIntoView(element);
+ }
+
+ public void addSelectionListener (
+ nsISelectionListener selectionListener) {
+ nsISelection selection = getSelection();
+ nsISelectionPrivate selectionPrivate = (nsISelectionPrivate) selection.queryInterface(nsISelectionPrivate.NS_ISELECTIONPRIVATE_IID);
+ selectionPrivate.addSelectionListener(selectionListener);
+ this.selectionListener = selectionListener;
+ }
+
+}
+
+
Modified: trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerVpeResizer.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerVpeResizer.java 2008-02-07 09:57:22 UTC (rev 6144)
+++ trunk/vpe/plugins/org.jboss.tools.vpe.xulrunner/src/org/jboss/tools/vpe/xulrunner/editor/XulRunnerVpeResizer.java 2008-02-07 09:59:22 UTC (rev 6145)
@@ -791,4 +791,15 @@
}
}
+ public void dispose() {
+ if (mouseMotionListener != null) {
+ nsIDOMEventTarget erP = getDOMEventTarget();
+
+ if (erP != null) {
+ erP.removeEventListener(XulRunnerConstants.EVENT_NAME_MOUSEMOVE, mouseMotionListener, true);
+ erP.removeEventListener(XulRunnerConstants.EVENT_NAME_MOUSEUP, mouseListener, true);
+ mouseMotionListener = null;
+ }
+ }
+ }
}
16 years, 4 months
JBoss Tools SVN: r6144 - in trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe: editor/context and 4 other directories.
by jbosstools-commits@lists.jboss.org
Author: mareshkau
Date: 2008-02-07 04:57:22 -0500 (Thu, 07 Feb 2008)
New Revision: 6144
Modified:
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeController.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeDomBuilder.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeEditorPart.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeSourceDomBuilder.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeVisualDomBuilder.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/context/VpePageContext.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaDomEventListener.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaEditor.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaPreview.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/template/VpeIncludeTemplate.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/IVpeToolBarManager.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/VpeToolBarManager.java
trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/selbar/SelectionBar.java
Log:
http://jira.jboss.com/jira/browse/JBIDE-1105
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeController.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeController.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeController.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,2393 +1,2421 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IContributionItem;
-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.bindings.Binding;
-import org.eclipse.jface.bindings.keys.KeySequence;
-import org.eclipse.jface.bindings.keys.KeyStroke;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.LineStyleEvent;
-import org.eclipse.swt.custom.LineStyleListener;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.MenuListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MessageBox;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;
-import org.eclipse.ui.internal.keys.WorkbenchKeyboard;
-import org.eclipse.ui.keys.IBindingService;
-import org.eclipse.ui.progress.UIJob;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent;
-import org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener;
-import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
-import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.internal.view.events.INodeSelectionListener;
-import org.eclipse.wst.sse.ui.internal.view.events.ITextSelectionListener;
-import org.eclipse.wst.sse.ui.internal.view.events.NodeSelectionChangedEvent;
-import org.eclipse.wst.sse.ui.internal.view.events.TextSelectionChangedEvent;
-import org.eclipse.wst.xml.core.internal.document.AttrImpl;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.eclipse.wst.xml.core.internal.document.NodeImpl;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.event.XModelTreeEvent;
-import org.jboss.tools.common.model.event.XModelTreeListener;
-import org.jboss.tools.common.model.options.PreferenceModelUtilities;
-import org.jboss.tools.common.model.ui.dnd.ModelTransfer;
-import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
-import org.jboss.tools.common.model.ui.editors.dnd.DropCommandFactory;
-import org.jboss.tools.common.model.ui.editors.dnd.DropData;
-import org.jboss.tools.common.model.ui.editors.dnd.IDropCommand;
-import org.jboss.tools.common.model.ui.editors.dnd.JSPTagProposalFactory;
-import org.jboss.tools.common.model.ui.editors.dnd.context.InnerDragBuffer;
-import org.jboss.tools.common.model.ui.objecteditor.ExtendedProperties;
-import org.jboss.tools.common.model.ui.objecteditor.ExtendedPropertiesWizard;
-import org.jboss.tools.common.model.ui.util.ModelUtilities;
-import org.jboss.tools.common.model.ui.views.palette.PaletteInsertHelper;
-import org.jboss.tools.common.model.util.EclipseResourceUtil;
-import org.jboss.tools.common.model.util.ModelFeatureFactory;
-import org.jboss.tools.common.model.util.XModelTreeListenerSWTSync;
-import org.jboss.tools.jst.jsp.editor.IJSPTextEditor;
-import org.jboss.tools.jst.jsp.editor.IVisualController;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.jst.web.tld.TLDToPaletteHelper;
-import org.jboss.tools.jst.web.tld.TLDUtil;
-import org.jboss.tools.jst.web.tld.URIConstants;
-import org.jboss.tools.vpe.VpeDebug;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.bundle.BundleMap;
-import org.jboss.tools.vpe.editor.context.VpePageContext;
-import org.jboss.tools.vpe.editor.css.AbsoluteFolderReferenceList;
-import org.jboss.tools.vpe.editor.css.CSSReferenceList;
-import org.jboss.tools.vpe.editor.css.RelativeFolderReferenceList;
-import org.jboss.tools.vpe.editor.css.ResourceReferenceListListener;
-import org.jboss.tools.vpe.editor.css.TaglibReferenceList;
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
-import org.jboss.tools.vpe.editor.menu.NodeActionManager;
-import org.jboss.tools.vpe.editor.menu.BaseActionManager.MyMenuManager;
-import org.jboss.tools.vpe.editor.mozilla.EditorDomEventListener;
-import org.jboss.tools.vpe.editor.mozilla.MozillaDropInfo;
-import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
-import org.jboss.tools.vpe.editor.selection.VpeSelectionController;
-import org.jboss.tools.vpe.editor.selection.VpeSelectionHelper;
-import org.jboss.tools.vpe.editor.template.VpeAnyData;
-import org.jboss.tools.vpe.editor.template.VpeEditAnyDialog;
-import org.jboss.tools.vpe.editor.template.VpeHtmlTemplate;
-import org.jboss.tools.vpe.editor.template.VpeIncludeList;
-import org.jboss.tools.vpe.editor.template.VpeTemplate;
-import org.jboss.tools.vpe.editor.template.VpeTemplateListener;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-import org.jboss.tools.vpe.editor.toolbar.format.FormatControllerManager;
-import org.jboss.tools.vpe.editor.util.HTML;
-import org.jboss.tools.vpe.editor.util.TextUtil;
-import org.jboss.tools.vpe.editor.util.VisualDomUtil;
-import org.jboss.tools.vpe.editor.util.VpeDndUtil;
-import org.jboss.tools.vpe.messages.VpeUIMessages;
-import org.jboss.tools.vpe.selbar.SelectionBar;
-import org.jboss.tools.vpe.xulrunner.browser.util.DOMTreeDumper;
-import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
-import org.mozilla.interfaces.nsIDOMDocument;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMEvent;
-import org.mozilla.interfaces.nsIDOMKeyEvent;
-import org.mozilla.interfaces.nsIDOMMouseEvent;
-import org.mozilla.interfaces.nsIDOMMutationEvent;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.mozilla.interfaces.nsISelection;
-import org.mozilla.interfaces.nsISelectionListener;
-import org.mozilla.interfaces.nsISupports;
-import org.mozilla.xpcom.Mozilla;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
-public class VpeController implements INodeAdapter, IModelLifecycleListener, INodeSelectionListener, ITextSelectionListener, SelectionListener, EditorDomEventListener, VpeTemplateListener, XModelTreeListener, ResourceReferenceListListener, ISelectionChangedListener, IVisualController {
-
- StructuredTextEditor sourceEditor;
- private MozillaEditor visualEditor;
-// MozillaBrowser browser;
- XulRunnerEditor xulRunnerEditor;
- // TODO Sergey Vasilyev figure out with nsIPressShell
-// private nsIPresShell presShell;
- // TODO Max Areshkau figure out with nsISelectionController
- private VpeSelectionController visualSelectionController;
- VpeDomMapping domMapping;
- private VpeTemplateManager templateManager;
- private VpeSourceDomBuilder sourceBuilder;
- public VpeVisualDomBuilder visualBuilder;
- private VpeSelectionBuilder selectionBuilder;
- private VpeVisualKeyHandler visualKeyHandler;
- private ActiveEditorSwitcher switcher = new ActiveEditorSwitcher();
- private Attr lastRemovedAttr;
- private String lastRemovedAttrName;
- private boolean mouseUpSelectionReasonFlag;
- private boolean mouseDownSelectionFlag;
- private boolean sourceChangeFlag;
- private VpePageContext pageContext;
- private BundleMap bundle;
- private VpeEditorPart editPart;
- private static final int AROUND_MENU = 1;
- private static final int BEFORE_MENU = 2;
- private static final int AFTER_MENU = 3;
-
- private CSSReferenceList cssReferenceListListener;
- private TaglibReferenceList taglibReferenceListListener;
- private AbsoluteFolderReferenceList absoluteFolderReferenceListListener;
- private RelativeFolderReferenceList relativeFolderReferenceListListener;
- private VpeIncludeList includeList = new VpeIncludeList();
- private VpeVisualInnerDragInfo innerDragInfo = null;
- private FormatControllerManager toolbarFormatControllerManager = null;
- private SelectionBar selectionBar = null;
- //Added by Max Areshkau Fix for JBIDE-1479
- private UIJob job = null;
- Shell tip;
-
- public final static String MODEL_FLAVOR = ModelTransfer.MODEL; //$NON-NLS-1$
-
- public VpeController(VpeEditorPart editPart){
-
- this.editPart = editPart;
- dropWindow = new VpeDropWindow(editPart.getSite().getShell());
- }
-
- void init(StructuredTextEditor sourceEditor, MozillaEditor visualEditor) throws Exception {
- this.sourceEditor = sourceEditor;
- if(sourceEditor instanceof IJSPTextEditor) {
- ((IJSPTextEditor)sourceEditor).setVPEController(this);
- dropWindow.setEditor((IJSPTextEditor)sourceEditor);
- }
- this.visualEditor = visualEditor;
- visualEditor.setController(this);
- templateManager = VpeTemplateManager.getInstance();
- bundle = new BundleMap();
- bundle.init(sourceEditor);
- pageContext = new VpePageContext(templateManager, bundle, editPart);
- domMapping = new VpeDomMapping(pageContext);
- sourceBuilder = new VpeSourceDomBuilder(domMapping, this, templateManager, sourceEditor, pageContext);
- visualBuilder = new VpeVisualDomBuilder(domMapping, this, templateManager, visualEditor, pageContext);
- pageContext.setSourceDomBuilder(sourceBuilder);
- pageContext.setVisualDomBuilder(visualBuilder);
- IDOMModel sourceModel = (IDOMModel)getModel();
- if (sourceModel == null) {
- return;
- }
- sourceModel.addModelLifecycleListener(this);
- IDOMDocument sourceDocument = sourceModel.getDocument();
- visualBuilder.refreshExternalLinks();
- visualBuilder.buildDom(sourceDocument);
-
- templateManager.addTemplateListener(this);
-
- xulRunnerEditor = visualEditor.getXulRunnerEditor();
- // TODO Sergey Vasilyev figure out with nsIPressShell
-// presShell = browser.getPresShell();
- visualSelectionController = new VpeSelectionController(xulRunnerEditor.getSelection());
- selectionBuilder = new VpeSelectionBuilder(domMapping, sourceBuilder, visualBuilder, visualSelectionController);
- visualKeyHandler = new VpeVisualKeyHandler(sourceEditor, domMapping, pageContext){
- public void doSave(IProgressMonitor monitor){
- editPart.doSave(monitor);
- }
- };
-
-// glory
- ISelectionProvider provider = sourceEditor.getSelectionProvider();
- provider.addSelectionChangedListener(this);
-
-// ViewerSelectionManager selectionManager = sourceEditor.getViewerSelectionManager();
-// selectionManager.addNodeSelectionListener(this);
-// selectionManager.addTextSelectionListener(this);
- StyledText textWidget = VpeSelectionHelper.getSourceTextWidget(sourceEditor);
- if (textWidget != null) {
- textWidget.addSelectionListener(this);
- }
-
- visualEditor.setEditorDomEventListener(this);
- switcher.initActiveEditor();
-
- XModelObject optionsObject = ModelUtilities.getPreferenceModel().getByPath(VpePreference.EDITOR_PATH);
- XModelTreeListenerSWTSync optionsListener = new XModelTreeListenerSWTSync(this);
- optionsObject.getModel().addModelTreeListener(optionsListener);
-
-
- cssReferenceListListener = CSSReferenceList.getInstance();
- cssReferenceListListener.addChangeListener(this);
-
- taglibReferenceListListener = TaglibReferenceList.getInstance();
- taglibReferenceListListener.addChangeListener(this);
-
- absoluteFolderReferenceListListener = AbsoluteFolderReferenceList.getInstance();
- absoluteFolderReferenceListListener.addChangeListener(this);
-
- relativeFolderReferenceListListener = RelativeFolderReferenceList.getInstance();
- relativeFolderReferenceListListener.addChangeListener(this);
-
- pageContext.fireTaglibsChanged();
- }
-
- public void dispose() {
- switcher.destroyActiveEditor();
-
- if (templateManager != null) {
- templateManager.removeTemplateListener(this);
- }
- if (visualBuilder != null) {
- visualBuilder.dispose();
- visualBuilder = null;
- }
- if (sourceEditor != null) {
-//glory
- ISelectionProvider provider = sourceEditor.getSelectionProvider();
- provider.removeSelectionChangedListener(this);
-// ViewerSelectionManager selectionManager = sourceEditor.getViewerSelectionManager();
-// selectionManager.removeNodeSelectionListener(this);
-// selectionManager.removeTextSelectionListener(this);
- StyledText textWidget = VpeSelectionHelper.getSourceTextWidget(sourceEditor);
- if (textWidget != null) {
- textWidget.removeSelectionListener(this);
- }
- }
-
- if (visualEditor != null) {
- visualEditor.setEditorDomEventListener(null);
- if (visualSelectionController != null) {
-// visualSelectionController.Release();
- visualSelectionController = null;
- }
- // TODO Sergey Vasilyev figure out with Press Shell
-// if (presShell != null) {
-// presShell.Release();
-// presShell = null;
-// }
- }
-
- if (cssReferenceListListener != null) {
- cssReferenceListListener.removeChangeListener(this);
- }
- if (taglibReferenceListListener != null) {
- taglibReferenceListListener.removeChangeListener(this);
- }
- if (absoluteFolderReferenceListListener != null) {
- absoluteFolderReferenceListListener.removeChangeListener(this);
- }
- if (relativeFolderReferenceListListener != null) {
- relativeFolderReferenceListListener.removeChangeListener(this);
- }
- }
-
- // INodeAdapter implementation
- public boolean isAdapterForType(Object type) {
- return type == this;
- }
- //FIX Fox JBIDE-1479 added by Max Areshkau
- public void notifyChanged(final INodeNotifier notifier, final int eventType,final Object feature,final Object oldValue,final Object newValue, final int pos) {
-
- //start job when we modify file in ui thread, without this code
- //changes will be applied with 1 second delay
- Display display = null;
- if (PlatformUI.isWorkbenchRunning())
- display= PlatformUI.getWorkbench().getDisplay();
-
- if (display != null && (Thread.currentThread() == display.getThread())) {
- notifyChangedInUiThread(notifier, eventType, feature, oldValue, newValue, pos);
- return;
- }
- //start job when we modify file in non ui thread
- if(job!=null) {
- job.cancel();
- }
-
- job = new UIJob("NotifyChangedJob"){
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- //we checks is job was canceled and if is it true we cancel job
- if(monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- } else {
- notifyChangedInUiThread(notifier, eventType, feature, oldValue, newValue, pos);
- }
- return Status.OK_STATUS;
- }};
- job.setPriority(Job.LONG);
- job.schedule(1000L);
- }
-
- public void notifyChangedInUiThread(INodeNotifier notifier, int eventType, Object feature, Object oldValue, Object newValue, int pos) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (VpeDebug.PRINT_SOURCE_MUTATION_EVENT) {
- printSourceEvent(notifier, eventType, feature, oldValue, newValue, pos);
- }
- if(visualBuilder==null) {
- return;
- }
- visualBuilder.rebuildFlag = false;
-
- switch (eventType) {
- case INodeNotifier.CHANGE:
- sourceChangeFlag = true;
- int type = ((Node)notifier).getNodeType();
- visualEditor.hideResizer();
- visualBuilder.setSelectionRectangle(null);
- if (type == Node.TEXT_NODE) {
- visualBuilder.setText((Node)notifier);
- visualEditor.showResizer();
- //Added by Max Areshkau JBIDE-1554
- visualBuilder.updateNode((Node)notifier);
- } else if (type == Node.COMMENT_NODE) {
- if("yes".equals(VpePreference.SHOW_COMMENTS.getValue())) { //$NON-NLS-1$
- visualBuilder.setSelectionRectangle(null);
- visualBuilder.updateNode((Node)notifier);
- }
- } else if (feature != null && ((Node)feature).getNodeType() == Node.ATTRIBUTE_NODE) {
- if (newValue != null) {
- String attrName = ((Attr)feature).getName();
- if ((Attr)feature == lastRemovedAttr && !attrName.equals(lastRemovedAttrName)) {
- lastRemovedAttr = null;
- visualBuilder.removeAttribute((Element)notifier, lastRemovedAttrName);
- }
- visualBuilder.setAttribute((Element)notifier, ((Attr)feature).getName(), (String)newValue);
- } else {
- lastRemovedAttr = (Attr)feature;
- lastRemovedAttrName = ((Attr)feature).getName();
- visualBuilder.removeAttribute((Element)notifier, lastRemovedAttrName);
- }
- }
- visualEditor.showResizer();
- break;
-
- case INodeNotifier.ADD:
- break;
-
- case INodeNotifier.REMOVE:
- visualBuilder.stopToggle((Node)feature);
- visualBuilder.removeNode((Node)feature);
- break;
-
- case INodeNotifier.STRUCTURE_CHANGED:
- visualEditor.hideResizer();
- visualBuilder.setSelectionRectangle(null);
- visualBuilder.updateNode((Node)notifier);
- break;
- case INodeNotifier.CONTENT_CHANGED:
- if (!sourceChangeFlag) {
- if (feature != null && ((Node)feature).getNodeType() == Node.TEXT_NODE) {
- //if (((Node)notifier).getNodeName().equalsIgnoreCase("style")) {
- visualEditor.hideResizer();
- visualBuilder.setSelectionRectangle(null);
- visualBuilder.setText((Node)feature);
- visualEditor.showResizer();
- //}
- }
- } else {
- sourceChangeFlag = false;
- }
- break;
- }
- if (visualBuilder.rebuildFlag) {
- pageContext.fireTaglibsChanged();
- } else if (pageContext.isTaglibChanged()) {
- visualRefreshImpl();
- pageContext.fireTaglibsChanged();
- }
- switcher.stopActiveEditor();
- }
-
- // INodeSelectionListener implementation
- public void nodeSelectionChanged(NodeSelectionChangedEvent event) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- List<?> nodes = event.getSelectedNodes();
- if (nodes != null && nodes.size() > 0) {
- Node sourceNode = (Node)nodes.get(0);
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println(">>>>>>>>>>>>>> nodeSelectionChanged sourceNode: " + sourceNode.getNodeName() + " " + event.getCaretPosition()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (event.getSource() instanceof IContentOutlinePage) {
- sourceSelectionChanged();
- }
- }
- switcher.stopActiveEditor();
- }
-
- // ITextSelectionListener implementation
- //TODO Max Areshau looks like this method don't used
- public void textSelectionChanged(TextSelectionChangedEvent event) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println(">>>>>>>>>>>>>> textSelectionChanged " + event.getSource()); //$NON-NLS-1$
- }
-// if (event.getSource() instanceof StyledText) {
- sourceSelectionChanged();
-// }
- switcher.stopActiveEditor();
- }
-
- // SelectionListener implementation
- public void widgetSelected(SelectionEvent event) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println(">>>>>>>>>>>>>> widgetSelected"); //$NON-NLS-1$
- }
- if (event.getSource() instanceof StyledText) {
- sourceSelectionChanged();
- }
- switcher.stopActiveEditor();
- }
-
- public void widgetDefaultSelected(SelectionEvent event) {
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println(">>>>>>>>>>>>>> widgetDefaultSelected"); //$NON-NLS-1$
- }
- }
-
- public void sourceSelectionChanged() {
- sourceSelectionChanged(false);
- }
-
- public void sourceSelectionChanged(boolean showCaret) {
- Point range = sourceEditor.getTextViewer().getSelectedRange();
- int anchorPosition = range.x;
- int focusPosition = range.x + range.y;
- boolean extendFlag = range.y != 0;
- boolean reversionFlag = extendFlag && anchorPosition == VpeSelectionHelper.getCaretOffset(sourceEditor);
- if (reversionFlag) {
- anchorPosition = focusPosition;
- focusPosition = range.x;
- }
- Node focusNode = getSourceNodeAt(focusPosition);
- if (focusNode == null) {
- return;
- }
- int focusOffset = getSourceNodeOffset(focusNode, focusPosition, extendFlag && !reversionFlag);
- Node anchorNode = null;
- int anchorOffset = 0;
- if (extendFlag) {
- anchorNode = getSourceNodeAt(anchorPosition);
- anchorOffset = getSourceNodeOffset(anchorNode, anchorPosition, reversionFlag);
- } else {
- anchorNode = focusNode;
- anchorOffset = focusOffset;
- }
-
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println("sourceSelectionChanged"); //$NON-NLS-1$
- System.out.println(" anchorNode: " + anchorNode.getNodeName() + " anchorOffset: " + anchorOffset); //$NON-NLS-1$ //$NON-NLS-2$
- System.out.println(" focusNode: " + focusNode.getNodeName() + " focusOffset: " + focusOffset + " focusPosition: " + focusPosition); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- try{
- if(anchorNode.getNodeType() == Node.TEXT_NODE || anchorNode.getNodeType() == Node.ATTRIBUTE_NODE){
- String text;
- if (anchorNode.getNodeType() == Node.TEXT_NODE) {
- IndexedRegion region = (IndexedRegion)anchorNode;
- text = sourceEditor.getTextViewer().getDocument().get(region.getStartOffset(), region.getEndOffset()-region.getStartOffset());
- } else {
- text = ((AttrImpl)anchorNode).getValueRegionText();
- }
- anchorOffset = TextUtil.visualPosition(text, anchorOffset);
- }
- if(focusNode.getNodeType() == Node.TEXT_NODE || focusNode.getNodeType() == Node.ATTRIBUTE_NODE){
- IndexedRegion region = (IndexedRegion)focusNode;
- String text;
- if (focusNode.getNodeType() == Node.TEXT_NODE) {
- text = sourceEditor.getTextViewer().getDocument().get(region.getStartOffset(), region.getEndOffset()-region.getStartOffset());
- } else {
- text = ((AttrImpl)focusNode).getValueRegionText();
- }
- focusOffset = TextUtil.visualPosition(text, focusOffset);
- }
- }catch(Exception ex){
- VpePlugin.reportProblem(ex);
- }
-
- selectionBuilder.setVisualSelection(anchorNode, anchorOffset, focusNode, focusOffset, reversionFlag, showCaret);
- }
-
- public void sourceSelectionToVisualSelection(boolean showCaret) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- sourceSelectionChanged(showCaret);
- switcher.stopActiveEditor();
- }
-
- // IModelLifecycleListener implementation
- public void processPreModelEvent(ModelLifecycleEvent event) {
- }
-
- public void processPostModelEvent(ModelLifecycleEvent event) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (event.getType() == ModelLifecycleEvent.MODEL_RELEASED) {
- if (VpeDebug.PRINT_SOURCE_MODEL_LIFECYCLE_EVENT) {
- System.out.println(">>> processPostModelEvent: " + event.toString()); //$NON-NLS-1$
- }
- visualBuilder.setSelectionRectangle(null);
- IStructuredModel model = event.getModel();
- model.removeModelLifecycleListener(this);
- IDOMModel sourceModel = (IDOMModel)getModel();
- sourceModel.addModelLifecycleListener(this);
- bundle.clearAll();
- bundle.refresh();
- visualBuilder.setSelectionRectangle(null);
- IDOMDocument sourceDocument = sourceModel.getDocument();
- visualBuilder.rebuildDom(sourceDocument);
- pageContext.fireTaglibsChanged();
- }
- switcher.stopActiveEditor();
- }
-
- // EditorDomEventListener implementation
- public void subtreeModified(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void nodeInserted(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- nsIDOMNode targetNode = mutationEvent.getRelatedNode();
- if (!VpeVisualDomBuilder.isAnonElement(targetNode)) {
- sourceBuilder.addNode(targetNode);
- visualBuilder.resetPseudoElement(targetNode);
- }
- switcher.stopActiveEditor();
- }
-
- public void nodeRemoved(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
- if (!VpeVisualDomBuilder.isAnonElement(targetNode)) {
- visualBuilder.setSelectionRectangle(null);
- sourceBuilder.removeNode(targetNode);
- visualBuilder.resetPseudoElement(targetNode);
- }
- switcher.stopActiveEditor();
- }
-
- public void nodeRemovedFromDocument(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void nodeInsertedIntoDocument(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void attrModified(nsIDOMMutationEvent mutationEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void characterDataModified(nsIDOMMutationEvent mutationEvent) {
-
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
- printVisualEvent(mutationEvent);
- }
- nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
- sourceBuilder.setText(targetNode);
- visualBuilder.resetPseudoElement(targetNode);
- switcher.stopActiveEditor();
- }
-
- public void notifySelectionChanged(nsIDOMDocument doc, nsISelection selection, short reason) {
- if (switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- mouseUpSelectionReasonFlag = (reason & nsISelectionListener.MOUSEUP_REASON) > 0;
- if (mouseUpSelectionReasonFlag || reason == nsISelectionListener.NO_REASON || reason == nsISelectionListener.KEYPRESS_REASON || reason == nsISelectionListener.SELECTALL_REASON || (reason & nsISelectionListener.MOUSEDOWN_REASON) > 0) {
- if (VpeDebug.PRINT_VISUAL_SELECTION_EVENT) {
- System.out.println("<<< notifySelectionChanged: " + reason); //$NON-NLS-1$
- }
- selectionBuilder.setSelection(selection);
- }
- switcher.stopActiveEditor();
- }
- }
-
-
- public void mouseDown(nsIDOMMouseEvent mouseEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- nsIDOMElement visualDragElement = selectionBuilder.getDragElement(mouseEvent);
- if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
- System.out.println("<<< mouseDown targetNode: " + visualNode.getNodeName() + " (" + visualNode + ") selectedElement: " + (visualDragElement != null ? visualDragElement.getNodeName() + " (" + visualDragElement + ")" : null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
- mouseDownSelectionFlag = false;
-
- if (visualDragElement != null) {
-
- //we shouldn't change selection when we click on <input type="text" /> element,
- //because if we change after resizing the input element lost selection
- if(!(HTML.TAG_INPUT.equalsIgnoreCase(visualDragElement.getNodeName())&&
- HTML.ATTR_TEXT.equalsIgnoreCase(visualDragElement.getAttribute(HTML.ATTR_TYPE))
- &&visualDragElement.getAttribute(HTML.ATTR_TYPE)!=null)) {
-
- selectionBuilder.setVisualElementSelection(visualDragElement);
- mouseDownSelectionFlag = true;
- }
- } else {
- selectionBuilder.setCaretAtMouse(mouseEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void mouseUp(nsIDOMMouseEvent mouseEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
- System.out.println("<<< mouseUp"); //$NON-NLS-1$
- }
- if (mouseDownSelectionFlag) {
- mouseEvent.preventDefault();
- mouseEvent.stopPropagation();
- mouseDownSelectionFlag = false;
- }
- switcher.stopActiveEditor();
- }
-
- public void mouseClick(nsIDOMMouseEvent mouseEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
-
- if (visualNode != null) {
- if (!mouseUpSelectionReasonFlag) {
- if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
- System.out.println("<<< mouseClick visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- if (visualBuilder.isContentArea(visualNode)) {
- selectionBuilder.setClickContentAreaSelection();
- }
- } else {
- mouseUpSelectionReasonFlag = false;
- }
-
- if (visualBuilder.doToggle(VisualDomUtil.getTargetNode(mouseEvent))) {
- selectionBuilder.setClickContentAreaSelection();
- }
- }
- switcher.stopActiveEditor();
- }
-
- public void mouseDblClick(nsIDOMMouseEvent mouseEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
- if (visualNode != null) {
- if (!sourceBuilder.openBundleEditors(visualNode)) {
- sourceBuilder.openIncludeEditor(visualNode);
- }
- if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
- System.out.println("<<< mouseDblClick visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
- switcher.stopActiveEditor();
- }
-
- public void mouseMove(nsIDOMMouseEvent mouseEvent) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
- if (visualNode != null) {
- if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
- System.out.println("<<< mouseMove visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")");
- }
- visualBuilder.setMoveCursor(mouseEvent);
- }
- switcher.stopActiveEditor();
- }
-
- public void keyPress(nsIDOMKeyEvent keyEvent) {
- if (VpeDebug.PRINT_VISUAL_KEY_EVENT) {
- System.out.println("<<< keyPress type: " + keyEvent.getType() + " Ctrl: " + keyEvent.getCtrlKey() + " Shift: " + keyEvent.getShiftKey() + " CharCode: " + keyEvent.getCharCode() + " KeyCode: " + keyEvent.getKeyCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- switcher.stopActiveEditor();
- return;
- }
-
- visualEditor.hideResizer();
- switcher.stopActiveEditor();
-
-
- try {
- if (visualKeyHandler.keyPressHandler(keyEvent)) {
- switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL);
- // Edward
- sourceSelectionChanged(true);
- visualSelectionController.setCaretEnabled(true);
- switcher.stopActiveEditor();
- } else {
- //adding calls of core event handlers, for example 'CTR+H' or 'CTRL+M' event handler dialog
- Event keyboardEvent = new Event ();
- //widget where event occur
- keyboardEvent.widget = xulRunnerEditor.getBrowser();
-
- keyboardEvent.stateMask = (keyEvent.getAltKey() ? SWT.ALT : 0) | (keyEvent.getCtrlKey() ? SWT.CTRL : 0) | (keyEvent.getShiftKey() ? SWT.SHIFT : 0) | (keyEvent.getMetaKey() ? SWT.MOD1 : 0);
- keyboardEvent.x=0;
- keyboardEvent.y=0;
- keyboardEvent.type=SWT.KeyDown;
-
- if(keyEvent.getKeyCode()==0) {
- keyboardEvent.keyCode=(int)keyEvent.getCharCode();
- } else{
- keyboardEvent.keyCode=(int)keyEvent.getKeyCode();
- }
-
- // JBIDE-1627
- List<KeyStroke> possibleKeyStrokes = WorkbenchKeyboard.generatePossibleKeyStrokes(keyboardEvent);
- IWorkbench iWorkbench = VpePlugin.getDefault().getWorkbench();
- if(iWorkbench.hasService(IBindingService.class)){
- IBindingService iBindingService = (IBindingService) iWorkbench.getService(IBindingService.class);
-
- KeySequence sequenceBeforeKeyStroke = KeySequence.getInstance();
- for (Iterator<KeyStroke> iterator = possibleKeyStrokes.iterator(); iterator
- .hasNext();){
- KeySequence sequenceAfterKeyStroke = KeySequence.getInstance(
- sequenceBeforeKeyStroke, iterator.next());
- if(iBindingService.isPerfectMatch(sequenceAfterKeyStroke)){
- final Binding binding = iBindingService.getPerfectMatch(sequenceAfterKeyStroke);
-
- if((binding!=null)
- && (binding.getParameterizedCommand()!=null)
- && (binding.getParameterizedCommand().getCommand()!=null)
- && ContentAssistCommandAdapter.CONTENT_PROPOSAL_COMMAND.equals(binding.getParameterizedCommand().getCommand().getId())){
- keyboardEvent.type = SWT.NONE;
- }
- }
- }
- }
-
- //sends xulrunner event to eclipse environment
- getXulRunnerEditor().getBrowser().notifyListeners(keyboardEvent.type, keyboardEvent);
-
- }
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- visualRefresh();
- }
-
- }
-
- public void elementResized(nsIDOMElement element, int resizerConstrains, int top, int left, int width, int height) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- visualEditor.hideResizer();
- switcher.stopActiveEditor();
-
- visualBuilder.resize(element, resizerConstrains, top, left, width, height);
- sourceSelectionChanged();
- }
-
- public void dragGesture(nsIDOMEvent domEvent) {
-
- nsIDOMMouseEvent mouseEvent = (nsIDOMMouseEvent) domEvent.queryInterface(nsIDOMMouseEvent.NS_IDOMMOUSEEVENT_IID);
- boolean canDragFlag = canInnerDrag(mouseEvent);
- //start drag sessionvpe-element
- if(canDragFlag) {
- startDragSession(domEvent);
- }
- }
-
- private void createMenuForNode(Node node, MenuManager manager) {
- createMenuForNode(node, manager, false);
- }
-
- private void createMenuForNode(Node node, MenuManager manager, boolean topLevelFlag) {
- NodeActionManager.setTextNodeSplitter(null);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(node);
- if (elementMapping != null && elementMapping.getTemplate() != null) {
- manager.add(new VpeAction("<"+node.getNodeName()+"> Attributes", node) { //$NON-NLS-1$ //$NON-NLS-2$
- public void run() {
- showProperties(actionNode);
- }
- });
-
- if (!topLevelFlag) {
- manager.add(new VpeAction("Select This Tag", node) { //$NON-NLS-1$
- public void run() {
- selectionBuilder.setVisualSelection(actionNode,0,actionNode,0,false,true);
-
- }
- });
- }
- Node parent = node.getParentNode();
- if(parent != null && parent.getNodeType() == Node.ELEMENT_NODE){
- MenuManager menuManager = new MenuManager("Parent Tag"); //$NON-NLS-1$
- menuManager.setParent(manager);
- manager.add(menuManager);
- createMenuForNode(parent, menuManager);
- }
-
- manager.add(new Separator());
- }
- }
- NodeActionManager actionManager = new NodeActionManager(getModel(), null);
-
- if (node.getNodeType() == Node.TEXT_NODE) {
- Point range = sourceEditor.getTextViewer().getSelectedRange();
- TextNodeSplitterImpl splitter = new TextNodeSplitterImpl(range, (Text)node);
- NodeActionManager.setTextNodeSplitter(splitter);
- }
-
-
- if (actionManager != null) {
- StructuredSelection structuredSelection = new StructuredSelection(node);
- actionManager.fillContextMenuForVpe(manager, structuredSelection);
-
- }
-
- IContributionItem[] items = manager.getItems();
-
- for(int i=0;i< items.length;i++){
- if(items[i] instanceof MenuManager){
- MenuManager mm = (MenuManager)items[i];
- if(NodeActionManager.INSERT_AROUND_MENU.equals(mm.getMenuText())){
- listenContextMenu(mm, (IndexedRegion)node, AROUND_MENU);
- }else if(NodeActionManager.INSERT_BEFORE_MENU.equals(mm.getMenuText())){
- listenContextMenu(mm, (IndexedRegion)node, BEFORE_MENU);
- }else if(NodeActionManager.INSERT_AFTER_MENU.equals(mm.getMenuText())){
- listenContextMenu(mm, (IndexedRegion)node, AFTER_MENU);
- }
- }
- }
-
- manager.add(new Separator());
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(node);
- if (elementMapping != null && elementMapping.getTemplate() != null && elementMapping.getTemplate().getType() == VpeHtmlTemplate.TYPE_ANY) {
- final VpeTemplate selectedTemplate = elementMapping.getTemplate();
-
- manager.add(new VpeAction("Template", node) { //$NON-NLS-1$
- public void run() {
- boolean isCorrectNS = pageContext.isCorrectNS(actionNode);
- VpeAnyData data = null;
- if (isCorrectNS) {
- data = selectedTemplate.getAnyData();
- data.setUri(pageContext.getSourceTaglibUri(actionNode));
- data.setName(actionNode.getNodeName());
- }
- data = editAnyData(sourceEditor, isCorrectNS, data);
- if (data != null && data.isChanged()) templateManager.setAnyTemplate(data);
- }
- });
-
- manager.add(new Separator());
- }
-
-
- manager.add(new VpeTextOperationAction("Cut", ActionFactory.CUT.getId(), (IndexedRegion)node)); //$NON-NLS-1$
- manager.add(new VpeTextOperationAction("Copy", ActionFactory.COPY.getId(), (IndexedRegion)node)); //$NON-NLS-1$
- manager.add(new VpeTextOperationAction("Paste", ActionFactory.PASTE.getId(), (IndexedRegion)node)); //$NON-NLS-1$
- }else if(node.getNodeType() == Node.TEXT_NODE){
- manager.add(new Action("Cut") { //$NON-NLS-1$
- public void run() {
- sourceEditor.getAction(ActionFactory.CUT.getId()).run();
- }
- });
- manager.add(new Action("Copy") { //$NON-NLS-1$
- public void run() {
- sourceEditor.getAction(ActionFactory.COPY.getId()).run();
- }
- });
- manager.add(new Action("Paste") { //$NON-NLS-1$
- public void run() {
- sourceEditor.getAction(ActionFactory.PASTE.getId()).run();
- }
- });
- }
- manager.add(new Separator());
-
- if (actionManager != null) {
- StructuredSelection structuredSelection = node.getNodeType() == Node.ELEMENT_NODE ? new StructuredSelection(node) : null;
- actionManager.addContextMenuForVpe(manager, structuredSelection);
- }
-
- if(node.getNodeType() == Node.ELEMENT_NODE){
- boolean stripEnable = false;
- NodeImpl impl = (NodeImpl)node;
- if(impl.isContainer()){
- NodeList list = impl.getChildNodes();
- if(list.getLength() > 0){
- if(list.getLength() == 1){
- Node child = list.item(0);
- if(child.getNodeType() == Node.TEXT_NODE){
- if("".equals(child.getNodeValue().trim()))stripEnable = false; //$NON-NLS-1$
- else stripEnable = true;
- }else stripEnable = true;
- }else stripEnable = true;
- }
- }
- if(stripEnable)
- manager.add(new VpeAction("Strip Tag", node) { //$NON-NLS-1$
- public void run() {
- Node parent = actionNode.getParentNode();
- if(parent != null){
- int index = ((NodeImpl)actionNode).getIndex();
- parent.removeChild(actionNode);
- NodeList children = actionNode.getChildNodes();
- int lengh = children.getLength();
- Node child;
- for(int i=0; i < lengh; i++){
- child = children.item(0);
- actionNode.removeChild(child);
- insertNode(parent, child, index++);
- }
- }
- }
-
- private void insertNode(Node parent, Node node, int index){
- Node oldNode=null;
- int childSize = parent.getChildNodes().getLength();
-
- if(index <= (childSize-1))oldNode = parent.getChildNodes().item(index);
- if(oldNode != null)parent.insertBefore(node, oldNode);
- else parent.appendChild(node);
- }
- });
- }
- if(node.getNodeType() == Node.TEXT_NODE){
- manager.add(new Action("Delete") { //$NON-NLS-1$
- public void run() {
- sourceEditor.getAction(ActionFactory.DELETE.getId()).run();
- }
- });
- }
-
- if (VpeDebug.VISUAL_CONTEXTMENU_DUMP_SOURCE) {
- manager.add(new Action("Dump Source") { //$NON-NLS-1$
- public void run() {
- DOMTreeDumper dumper = new DOMTreeDumper();
- dumper.dumpToStream(System.out, visualEditor.getDomDocument());
- }
- });
- }
-
- if (VpeDebug.VISUAL_CONTEXTMENU_DUMP_MAPPING) {
- manager.add(new Action("Dump Mapping") { //$NON-NLS-1$
- public void run() {
- printMapping();
- }
- });
- }
-
- if (VpeDebug.VISUAL_CONTEXTMENU_TEST) {
- manager.add(new VpeAction("Test", node) { //$NON-NLS-1$
- public void run() {
- test(actionNode);
- }
- });
- }
- }
-
- /**
- * Calls when on when browser receive context menu event.
- *
- * @param contextFlags -not used in this function, just for becouse this parametr
- * exist in nsIContextMenuListener
- * @param event event from browser used here
- * @param node where this event are occur
- */
- public void onShowContextMenu(long contextFlags, nsIDOMEvent event, nsIDOMNode node) {
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(event);
-
- if (visualNode != null) {
- Node selectedSourceNode = null;
- selectedSourceNode = selectionBuilder.setContextMenuSelection(visualNode);
- if (selectedSourceNode != null) {
-
- MenuManager menuManager = new MenuManager("#popup"); //$NON-NLS-1$
- final Menu contextMenu = menuManager.createContextMenu(visualEditor.getControl());
- contextMenu.addMenuListener(
- new MenuListener(){
- Menu menu = contextMenu;
- public void menuHidden(MenuEvent e) {
- Display.getCurrent().asyncExec(
- new Runnable() {
- public void run() {
- menu.dispose();
- }
- }
- );
- }
- public void menuShown(MenuEvent e) {
- }
- }
- );
- createMenuForNode(selectedSourceNode, menuManager, true);
-
- contextMenu.setVisible(true);
-
- }
- }
- }
-
-
- private VpeAnyData editAnyData(StructuredTextEditor sourceEditor, boolean isCorrectNS, VpeAnyData data) {
- Shell shell = sourceEditor.getEditorPart().getSite().getShell();
- if (isCorrectNS) {
- VpeEditAnyDialog editDialog = new VpeEditAnyDialog(shell, data);
- editDialog.open();
- } else {
- MessageBox message = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
- message.setMessage(VpeUIMessages.NAMESPACE_NOT_DEFINED);
- message.open();
- }
- return data;
- }
-
- // VpeTemplateListener implementation
- public void templateReloaded() {
- visualRefresh();
- }
-
- // VpeTaglibListener implementation
-// public void taglibPrefixChanged(String[] prefixs) {
-// if (VpeDebug.printSourceMutationEvent) {
-// String s = ""; //$NON-NLS-1$
-// for (int i = 0; i < prefixs.length; i++) {
-// if (i > 0) {
-// s += ", "; //$NON-NLS-1$
-// }
-// s += prefixs[i];
-// }
-// }
-// queryVisualRefresh = true;
-//// visualRefreshImpl();
-// }
-
- public void visualRefresh() {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- visualRefreshImpl();
- pageContext.fireTaglibsChanged();
-
- switcher.stopActiveEditor();
- }
-
- void visualRefreshImpl() {
- visualEditor.hideResizer();
- visualBuilder.setSelectionRectangle(null);
- IDOMModel sourceModel = (IDOMModel)getModel();
- if (sourceModel != null) {
- IDOMDocument sourceDocument = sourceModel.getDocument();
- visualBuilder.rebuildDom(sourceDocument);
- } else {
- visualBuilder.rebuildDom(null);
- }
- }
-
- public void preLongOperation() {
- switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL);
- }
-
- public void postLongOperation() {
- switcher.stopActiveEditor();
- visualRefresh();
- }
-
- // for debug
- private void printSourceEvent(INodeNotifier notifier, int eventType, Object feature, Object oldValue, Object newValue, int pos) {
- System.out.println(">>> eventType: " + INodeNotifier.EVENT_TYPE_STRINGS[eventType] + " pos: " + pos + " notifier: " + ((Node)notifier).getNodeName() + " hashCode: " + notifier.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- if (feature != null) {
- if (feature instanceof Node) {
- System.out.println(" feature: " + ((Node)feature).getNodeType() + " " + ((Node)feature).getNodeName() + " hashCode: " + feature.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- } else {
- System.out.println(" feature: " + feature); //$NON-NLS-1$
- }
- }
- if (oldValue != null) {
- if (oldValue instanceof Node) {
- System.out.println(" oldValue: " + ((Node)oldValue).getNodeName() + " hashCode: " + oldValue.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- System.out.println(" oldValue: " + oldValue); //$NON-NLS-1$
- }
- }
- if (newValue != null) {
- if (newValue instanceof Node) {
- System.out.println(" newValue: " + ((Node)newValue).getNodeName() + " hashCode: " + newValue.hashCode() + " " + ((Node)newValue).getNodeType()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- } else {
- System.out.println(" newValue: " + newValue); //$NON-NLS-1$
- }
- }
- }
-
- private void printVisualEvent(nsIDOMEvent event) {
- System.out.print("<<< " + event.getType()); //$NON-NLS-1$
-
- if (event instanceof nsIDOMMutationEvent) {
- nsIDOMMutationEvent mutationEvent = (nsIDOMMutationEvent)event;
-
- System.out.print(" EventPhase: " + mutationEvent.getEventPhase()); //$NON-NLS-1$
-
- nsIDOMNode relatedNode = mutationEvent.getRelatedNode();
- System.out.print(" RelatedNode: " + (relatedNode == null ? null : relatedNode.getNodeName())); //$NON-NLS-1$
-
- nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
- String name = targetNode != null ? targetNode.getNodeName() : null;
- System.out.print(" TargetNode: " + name + " (" + targetNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- System.out.print(" PrevValue: " + mutationEvent.getPrevValue().trim()); //$NON-NLS-1$
- System.out.print(" NewValue: " + mutationEvent.getNewValue().trim()); //$NON-NLS-1$
- }
- System.out.println();
- }
-
- private void printMapping() {
- domMapping.printMapping();
- }
-
- private class ActiveEditorSwitcher {
- private static final int ACTIVE_EDITOR_CANNOT = 0;
- private static final int ACTIVE_EDITOR_NONE = 1;
- private static final int ACTIVE_EDITOR_SOURCE = 2;
- private static final int ACTIVE_EDITOR_VISUAL = 3;
-
- private int type = ACTIVE_EDITOR_CANNOT;
-
- private void initActiveEditor() {
- type = ACTIVE_EDITOR_NONE;
- }
-
- private void destroyActiveEditor() {
- type = ACTIVE_EDITOR_CANNOT;
- }
-
- private boolean startActiveEditor(int newType) {
- if (type == ACTIVE_EDITOR_NONE) {
- if( newType == ACTIVE_EDITOR_SOURCE &&
- editPart.getVisualMode() == VpeEditorPart.SOURCE_MODE) {
- return false;
- }
- type = newType;
- return true;
- } else {
- return false;
- }
- }
-
- private void stopActiveEditor() {
- onRefresh();
- type = ACTIVE_EDITOR_NONE;
- }
- }
-
- private void showProperties(Node node){
- ExtendedProperties p = createExtendedProperties(node);
- if(p != null) ExtendedPropertiesWizard.run(p);
- }
-
- ExtendedProperties createExtendedProperties(Node node) {
- try {
- Class c = ModelFeatureFactory.getInstance().getFeatureClass("org.jboss.tools.jst.jsp.outline.VpeProperties"); //$NON-NLS-1$
- return (ExtendedProperties)c.getDeclaredConstructor(new Class[]{Node.class}).newInstance(new Object[]{node});
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- return null;
- }
- }
-
-
- private void test(Node node) {
- }
-
- void refreshBundleValues() {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (bundle != null) {
- bundle.refresh();
- if (pageContext != null) {
- pageContext.refreshBundleValues();
- }
- }
- switcher.stopActiveEditor();
- }
-
- void refreshTemplates() {
- if (includeList.includesRefresh()) {
- visualRefresh();
- }
- if (templateManager != null) {
- templateManager.reload();
- }
- if (bundle != null) {
- bundle.refresh();
- if (pageContext != null) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- pageContext.refreshBundleValues();
- switcher.stopActiveEditor();
- }
- }
- }
-
- // implements XModelTreeListener
- public void nodeChanged(XModelTreeEvent event) {
- visualRefresh();
- }
-
- public void structureChanged(XModelTreeEvent event) {
- }
-
- private Node getSourceNodeAt(int offset) {
- if (sourceEditor != null && getModel() != null) {
- IndexedRegion node = getModel().getIndexedRegion(offset);
- if (node instanceof IDOMElement) {
- IDOMElement element = (IDOMElement)node;
- if (offset < element.getEndStartOffset()) {
- NamedNodeMap attrs = element.getAttributes();
- if (attrs != null) {
- for (int i = 0; i < attrs.getLength(); i++) {
- if (attrs.item(i) instanceof AttrImpl) {
- AttrImpl attr = (AttrImpl)attrs.item(i);
- if (getSourceAttributeOffset(attr, offset) != -1) {
- VpeElementMapping elementMapping = domMapping.getNearElementMapping(attr.getOwnerElement());
- if (elementMapping != null) {
- String[] atributeNames = elementMapping.getTemplate().getOutputAtributeNames();
- if (atributeNames != null && atributeNames.length > 0 && attr.getName().equalsIgnoreCase(atributeNames[0])) {
- return attr;
- }
- }
- }
- }
- }
- }
- }
- }
- if (node == null) {
- node = getModel().getIndexedRegion(offset - 1);
- }
- if (node instanceof Node) {
- return (Node) node;
- }
- }
- return null;
- }
-
- private int getSourceNodeOffset(Node node, int pos, boolean endFlag) {
- if (node == null) return 0;
- int start = ((IndexedRegion)node).getStartOffset();
- int end = ((IndexedRegion)node).getEndOffset();
-
- switch (node.getNodeType()) {
- case Node.ATTRIBUTE_NODE:
- if (node instanceof AttrImpl) {
- return getSourceAttributeOffset((AttrImpl)node, pos);
- }
- case Node.TEXT_NODE:
- if (pos < start) {
- return 0;
- } else if (pos > end) {
- return end - start;
- } else {
- return pos - start;
- }
- case Node.COMMENT_NODE:
- if (pos > end) {
- pos = end;
- }
- int offset = pos - start - 4;
- return offset < 0 ? 0 : offset;
- case Node.ELEMENT_NODE:
- ElementImpl element = (ElementImpl)node;
- if (element.isContainer()) {
- if (pos < element.getStartEndOffset()) {
- return 0;
- } else {
- return 1;
- }
- } else {
- return endFlag ? 1 : 0;
- }
- default:
- return endFlag ? 1 : 0;
- }
- }
-
- private int getSourceAttributeOffset(AttrImpl attr, int pos) {
- if (attr.getValueRegion() != null) {
- int start = attr.getValueRegionStartOffset();
- String value = attr.getValueRegionText();
- int len = value.length();
- if (pos >= start && pos <= start + len) {
- int offset = pos - start;
- if (len > 1 && value.charAt(0) == '"' && value.charAt(len - 1) == '"') {
- if (offset <= 0 || offset >= len) {
- return -1;
- }
- offset--;
- }
- return offset;
- }
- }
- return -1;
- }
-
- private int getSourceNodeOffset1(Node node, int pos, boolean endFlag) {
- if (node == null) return 0;
- int start = ((IndexedRegion)node).getStartOffset();
- int end = ((IndexedRegion)node).getEndOffset();
-
- switch (node.getNodeType()) {
- case Node.ATTRIBUTE_NODE:
- if (node instanceof AttrImpl) {
- AttrImpl attr = (AttrImpl)node;
- start = attr.getValueRegionStartOffset();
- end = start + attr.getValueRegion().getLength();
- int ret = 0;
- if (pos > end) {
- ret = end - start;
- } else {
- ret = pos - start;
- }
- if (ret > 0 && attr.getValueRegionText().charAt(0) == '"') {
- ret--;
- }
- return ret;
- }
- case Node.TEXT_NODE:
- if (pos < start) {
- return 0;
- } else if (pos > end) {
- return end - start;
- } else {
- return pos - start;
- }
- case Node.COMMENT_NODE:
- if (pos > end) {
- pos = end;
- }
- int offset = pos - start - 4;
- return offset < 0 ? 0 : offset;
- case Node.ELEMENT_NODE:
- ElementImpl element = (ElementImpl)node;
- if (element.isContainer()) {
- if (pos < element.getStartEndOffset()) {
- return 0;
- } else if (pos < element.getStartEndOffset()) {
- return 1;
- } else if (pos == element.getStartEndOffset()) {
- return 2;
- }
- } else {
- return endFlag ? 1 : 0;
- }
- default:
- return endFlag ? 1 : 0;
- }
- }
-
- private void listenContextMenu(MenuManager manager, IndexedRegion region, int type){
- MenuManager mm = new MyMenuManager("From Palette",true); //$NON-NLS-1$
- manager.add(mm);
- manager.addMenuListener(new VpeMenuListener(mm, region, type));
- }
-
- class VpeMenuListener implements IMenuListener{
- private MenuManager manager;
- private IndexedRegion region;
- private int type;
- private boolean loaded=false;
-
- public VpeMenuListener(MenuManager manager, IndexedRegion region, int type){
- this.manager = manager;
- this.region = region;
- this.type = type;
- }
- public void menuAboutToShow(IMenuManager m) {
- if(loaded)return;
- loaded=true;
- fillContextMenuFromPalette(manager, region, type);
- manager.getParent().update(true);
- }
- }
- private MenuManager fillContextMenuFromPalette(MenuManager manager, IndexedRegion region, int type){
- XModelObject model = ModelUtilities.getPreferenceModel().getByPath("%Palette%"); //$NON-NLS-1$
-
- XModelObject[] folders = model.getChildren();
- for(int i=0;i<folders.length;i++){
- if ("yes".equals(folders[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
- MenuManager mm = new MenuManager(folders[i].getAttributeValue("name")); //$NON-NLS-1$
- manager.add(mm);
- fillPaletteFolder(mm, region, folders[i], type);
- }
- return manager;
- }
-
- private void fillPaletteFolder(MenuManager menu, IndexedRegion region, XModelObject folder, int type){
- XModelObject[] groups = folder.getChildren();
- for(int i=0;i<groups.length;i++){
- if ("yes".equals(groups[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
- MenuManager mm = new MenuManager(groups[i].getAttributeValue("name")); //$NON-NLS-1$
- menu.add(mm);
- fillPaletteGroup(mm, region, groups[i], type);
- }
- }
-
- private void fillPaletteGroup(MenuManager menu, IndexedRegion region, XModelObject group, int type){
- XModelObject[] items = group.getChildren();
- String endText;
-
- for(int i=0;i<items.length;i++){
- if ("yes".equals(items[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
- endText = items[i].getAttributeValue("end text"); //$NON-NLS-1$
-
- if(type == AROUND_MENU && (endText == null || "".equals(endText))) continue; //$NON-NLS-1$
- createInsertAction(menu, region, items[i], type);
- }
- }
-
- private void createInsertAction(MenuManager menu, IndexedRegion region, XModelObject item, int type){
-
-
- XModelObject parent = item.getParent();
- String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
- String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
- String tagName = item.getAttributeValue("name"); //$NON-NLS-1$
- String[] texts = new String[]{"<"+tagName+">"}; //$NON-NLS-1$ //$NON-NLS-2$
- if(tagName.indexOf("taglib") < 0) //$NON-NLS-1$
- PaletteInsertHelper.applyPrefix(texts, sourceEditor, tagName, uri, defaultPrefix);
- tagName = texts[0];
-
- menu.add(new InsertAction(tagName, region, item, type));
- }
-
- class InsertAction extends Action{
- private XModelObject item;
- private int type;
- private IndexedRegion region;
-
- public InsertAction(String title, IndexedRegion region, XModelObject item, int type){
- super(title);
- this.item = item;
- this.type = type;
- this.region = region;
- }
- public void run(){
- try {
- String tagName = item.getAttributeValue("name"); //$NON-NLS-1$
-
- XModelObject parent = item.getParent();
- String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
- String libraryVersion = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_VERSION); //$NON-NLS-1$
- String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
- VpeSelectionProvider selProvider = new VpeSelectionProvider(region);
-
- String startText = "" + item.getAttributeValue("start text"); //$NON-NLS-1$ //$NON-NLS-2$
- String endText = "" + item.getAttributeValue("end text"); //$NON-NLS-1$ //$NON-NLS-2$
- if(type == AROUND_MENU){
- }else if(type == BEFORE_MENU){
- selProvider = new VpeSelectionProvider(region.getStartOffset());
- }else if(type == AFTER_MENU){
- selProvider = new VpeSelectionProvider(region.getEndOffset());
- }
-
- Properties p = new Properties();
- p.setProperty("tag name", tagName); //$NON-NLS-1$
- p.setProperty("start text", startText); //$NON-NLS-1$
- p.setProperty("end text", endText); //$NON-NLS-1$
- p.setProperty("automatically reformat tag body", "" + item.getAttributeValue("automatically reformat tag body")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- p.setProperty(URIConstants.LIBRARY_URI, uri);
- p.setProperty(URIConstants.LIBRARY_VERSION, libraryVersion);
- String addTaglib = item.getParent().getAttributeValue(TLDToPaletteHelper.ADD_TAGLIB);
- p.setProperty(URIConstants.DEFAULT_PREFIX, defaultPrefix);
- p.setProperty(PaletteInsertHelper.PROPOPERTY_ADD_TAGLIB, addTaglib);
- if(((Node)region).getNodeType() == Node.ELEMENT_NODE)
- p.put("selectionProvider", selProvider); //$NON-NLS-1$
- PaletteInsertHelper.insertIntoEditor(sourceEditor.getTextViewer(), p);
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- }
-
- }
-
- }
-
- class VpeSelectionProvider implements ISelectionProvider{
- VpeSelection selection;
-
- public VpeSelectionProvider(IndexedRegion region){
- selection = new VpeSelection(region);
- }
- public VpeSelectionProvider(int position){
- selection = new VpeSelection(position);
- }
- public VpeSelectionProvider(int offset, int length){
- selection = new VpeSelection(offset, length);
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- }
- public ISelection getSelection() {
- return selection;
- }
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
-
- }
- public void setSelection(ISelection selection) {
- }
- }
-
- class VpeSelection implements ITextSelection{
- String text=""; //$NON-NLS-1$
- int offset, length;
-
- public VpeSelection(int position){
- offset = position;
- length = 0;
- }
-
- public VpeSelection(int offset, int length){
- this.offset = offset;
- this.length = length;
- if (length > 0) {
- try{
- text = sourceEditor.getTextViewer().getDocument().get(offset, length);
- }catch(Exception ex){
- VpePlugin.reportProblem(ex);
- }
- }
- }
-
- public VpeSelection(IndexedRegion region){
- offset = region.getStartOffset();
- length = region.getEndOffset() - offset;
- try{
- text = sourceEditor.getTextViewer().getDocument().get(offset, length);
- }catch(Exception ex){
- VpePlugin.reportProblem(ex);
- }
- }
-
- public int getEndLine() {
- return 0;
- }
- public int getLength() {
- return length;
- }
- public int getOffset() {
- return offset;
- }
- public int getStartLine() {
- return 0;
- }
- public String getText() {
- return text;
- }
- public boolean isEmpty() {
- return false;
- }
-}
-
- class VpeAction extends Action{
- public Node actionNode;
- public VpeAction(String name, Node node){
- super(name);
- this.actionNode = node;
- }
- }
-
- class VpeTextOperationAction extends Action{
- private String id;
- private IndexedRegion region;
- public VpeTextOperationAction(String name, String id, IndexedRegion region){
- super(name);
- this.id = id;
- this.region = region;
- }
- public void run(){
- sourceEditor.getSelectionProvider().setSelection(new VpeSelection(region));
- sourceEditor.getAction(id).run();
- }
- }
-
- public void refreshExternalLinks() {
- pageContext.getVisualBuilder().refreshExternalLinks();
- }
-
- public IPath getPath() {
- if (editPart != null) {
- IEditorInput input = editPart.getEditorInput();
- if (input != null && input instanceof IFileEditorInput) {
- return ((IFileEditorInput)input).getFile().getFullPath();
- }
- }
- return null;
- }
-
- public void changed(Object source) {
- if(cssReferenceListListener == source) {
- pageContext.getVisualBuilder().refreshExternalLinks();
- } else if (absoluteFolderReferenceListListener == source ||
- relativeFolderReferenceListListener == source ||
- taglibReferenceListListener == source) {
- visualRefresh();
- }
- }
-
- public void dragEnter(nsIDOMEvent event) {
- if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
- System.out.println("<<<<<<<<<<<<<<<<<<<< DragEnter"); //$NON-NLS-1$
- }
- }
-
- public void dragExit(nsIDOMEvent event) {
- if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
- System.out.println("<<<<<<<<<<<<<<<<<<<< dragExit"); //$NON-NLS-1$
- }
- // TODO Sergey Vasilyev figure out with drag caret
-// xulRunnerEditor.hideDragCaret();
- }
-
- public void dragOver(nsIDOMEvent event) {
-
- visualBuilder.getDnd().dragOver(event, this);
-
- }
-
- public void _dragOver(nsIDOMEvent event) {
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
- return;
- }
- if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
- System.out.println("<<<<<<<<<<<<<<<<<<<< dragOver"); //$NON-NLS-1$
- }
-
-// browser.computeDropPosition(event);
-
- boolean canDrop = !xulRunnerEditor.isMozillaDragFlavor();
- if (canDrop) {
- Clipboard clipboard = new Clipboard(Display.getCurrent());
- canDrop = clipboard.getContents(ModelTransfer.getInstance()) != null;
- }
- if (canDrop) {
- canDrop = VpeDndUtil.isDropEnabled((IModelObjectEditorInput)sourceEditor.getEditorInput());
- }
- if (canDrop) {
- VpeVisualCaretInfo caretInfo = selectionBuilder.getVisualCaretInfo(event);
- canDrop = caretInfo.exist();
- if (canDrop) {
- caretInfo.showCaret();
- } else {
- caretInfo.hideCaret();
- }
- }
- if (!canDrop) {
- event.stopPropagation();
- event.preventDefault();
- }
- switcher.stopActiveEditor();
- }
-
- public void drop(nsIDOMEvent event) {
- if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
- System.out.println("<<< outerDrop"); //$NON-NLS-1$
- }
- event.preventDefault();
- }
-
- public boolean canInnerDrag(nsIDOMMouseEvent event) {
- onHideTooltip();
-
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print("<<<<<< canInnerDrag"); //$NON-NLS-1$
- }
- if (innerDragInfo != null) {
- innerDragInfo.Release();
- innerDragInfo = null;
- }
- boolean canDrag = false;
- VpeVisualInnerDragInfo dragInfo = selectionBuilder.getInnerDragInfo(event);
- if (dragInfo != null) {
- nsIDOMNode dragNode = dragInfo.getNode();
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print(" dragNode: " + dragNode.getNodeName() + "(" + dragNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- switch (dragNode.getNodeType()) {
- case nsIDOMNode.ELEMENT_NODE:
- canDrag = visualBuilder.canInnerDrag((nsIDOMElement)dragNode);
- case nsIDOMNode.TEXT_NODE:
- canDrag = visualBuilder.isTextEditable(dragNode);
- }
- if (canDrag) {
- VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(dragInfo);
- if (sourceInnerDragInfo.getNode() != null) {
- innerDragInfo = dragInfo;
- InnerDragBuffer.object = sourceInnerDragInfo.getNode();
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- InnerDragBuffer.object = null;
- }
- });
- } else {
- canDrag = false;
- }
- }
- if (!canDrag) {
- dragInfo.Release();
- }
- }
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println(" canDrag: " + canDrag); //$NON-NLS-1$
- }
- return canDrag;
- }
-
- VpeDropWindow dropWindow = null;
-
- public MozillaDropInfo canInnerDrop(nsIDOMMouseEvent event) {
- onHideTooltip();
-
- if(dropWindow.active) {
- if(!event.getAltKey()) {
- dropWindow.close();
- } else {
- return null;
- }
- }
- if(event.getAltKey()) {
- nsIDOMNode visualNode = VisualDomUtil.getTargetNode(event);
- Node sourceNode = domMapping.getNearSourceNode(visualNode);
- if(sourceNode != null) {
- dropWindow.active = true;
- dropWindow.setEventPosition(event.getScreenX(), event.getScreenY());
- dropWindow.setInitialTargetNode(sourceNode);
- dropWindow.open();
- event.stopPropagation();
- event.preventDefault();
- return null;
- }
- }
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print("<<<<<< canInnerDrop"); //$NON-NLS-1$
- }
- boolean canDrop = false;;
- nsIDOMNode caretParent = null;
- long caretOffset = 0;
- if (innerDragInfo != null) {
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(event);
- if (visualDropInfo.getDropContainer() != null) {
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print(" x: " + visualDropInfo.getMouseX() + " y: " + visualDropInfo.getMouseY() + //$NON-NLS-1$ //$NON-NLS-2$
- " container: " + visualDropInfo.getDropContainer().getNodeName() + //$NON-NLS-1$
- "(" + visualDropInfo.getDropContainer() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
- " parent: " + visualDropInfo.getDropContainer().getParentNode().getNodeName() + //$NON-NLS-1$
- "(" + visualDropInfo.getDropContainer().getParentNode() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
- " offset: " + visualDropInfo.getDropOffset()); //$NON-NLS-1$
- }
- VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(innerDragInfo);
- VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceInnerDragInfo.getNode(), visualDropInfo, true);
- canDrop = sourceDropInfo.canDrop();
- if (canDrop) {
- VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
- if (newVisualDropInfo != null) {
- visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
- caretParent = newVisualDropInfo.getDropContainer();
- caretOffset = newVisualDropInfo.getDropOffset();
- }
- }
- }
- visualDropInfo.Release();
- }
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println(" canDrop: " + canDrop); //$NON-NLS-1$
- }
- return new MozillaDropInfo(canDrop, caretParent, caretOffset);
- }
-
- public void innerDrop(nsIDOMMouseEvent event) {
- onHideTooltip();
-
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print("<<<<<< innerDrop"); //$NON-NLS-1$
- }
- if (innerDragInfo != null) {
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(event);
- if (visualDropInfo.getDropContainer() != null) {
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.print(" container: " + visualDropInfo.getDropContainer().getNodeName() + //$NON-NLS-1$
- "(" + visualDropInfo.getDropContainer() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
- " offset: " + visualDropInfo.getDropOffset()); //$NON-NLS-1$
- }
-
- VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(innerDragInfo);
- VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceInnerDragInfo.getNode(), visualDropInfo, true);
- if(sourceDropInfo.canDrop()){
- VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
- if (newVisualDropInfo != null) {
- visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
- sourceDropInfo.setTop(visualDropInfo.getMouseY());
- sourceDropInfo.setLeft(visualDropInfo.getMouseX());
- visualBuilder.innerDrop(sourceInnerDragInfo, sourceDropInfo);
- if (innerDragInfo != null) {
- innerDragInfo.Release();
- innerDragInfo = null;
- }
- }
- }
- }
- }
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println();
- }
- }
-
- public MozillaDropInfo canExternalDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
- InnerDragBuffer.object = null;
- onHideTooltip();
-
- if(dropWindow.active) {
- if(!mouseEvent.getAltKey()) {
- dropWindow.close();
- } else {
- return new MozillaDropInfo(false, null, 0);
- }
- }
- if(mouseEvent.getAltKey()) {
- nsIDOMEvent event = (nsIDOMEvent) mouseEvent.queryInterface(nsIDOMEvent.NS_IDOMEVENT_IID);
- nsIDOMNode visualNode = (nsIDOMNode) event.getTarget().queryInterface(nsIDOMNode.NS_IDOMNODE_IID);
- Node sourceNode = domMapping.getNearSourceNode(visualNode);
- if(sourceNode != null) {
- if(ModelTransfer.MODEL.equals(flavor)){ //$NON-NLS-1$
-// XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
-// InnerDragBuffer.object = object;
- } else {
- dropWindow.flavor = flavor;
- }
- dropWindow.active = true;
- dropWindow.setEventPosition(mouseEvent.getScreenX(), mouseEvent.getScreenY());
- dropWindow.setInitialTargetNode(sourceNode);
- dropWindow.open();
- mouseEvent.stopPropagation();
- mouseEvent.preventDefault();
- return new MozillaDropInfo(false, null, 0);
- }
- }
- boolean canDrop = false;
- nsIDOMNode caretParent = null;
- long caretOffset = 0;
-
- if(MODEL_FLAVOR.equals(flavor)){
- XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
- if(object.getFileType() == XModelObject.FILE && !TLDUtil.isTaglib(object)) {
- IFile f = (IFile)EclipseResourceUtil.getResource(object);
- canDrop = f != null;
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
- caretParent = visualDropInfo.getDropContainer();
- caretOffset = visualDropInfo.getDropOffset();
- } else {
- String tagname = getTagName(object);
- if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
- Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
- if (visualDropInfo.getDropContainer() != null) {
- VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
- canDrop = sourceDropInfo.canDrop();
- if (canDrop) {
- VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
- if (newVisualDropInfo != null) {
- visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
- caretParent = newVisualDropInfo.getDropContainer();
- caretOffset = newVisualDropInfo.getDropOffset();
- }
- }
- }
- visualDropInfo.Release();
- }
- }else if(XulRunnerEditor.TRANS_FLAVOR_kFileMime.equals(flavor) ||
- XulRunnerEditor.TRANS_FLAVOR_kURLMime.equals(flavor)) {
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
- caretParent = visualDropInfo.getDropContainer();
- caretOffset = visualDropInfo.getDropOffset();
- try {
- canDrop = true;
- } catch (Exception ex) {
- VpePlugin.reportProblem(ex);
- }
- }
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println(" canDrop: " + canDrop + (canDrop ? " container: " + caretParent.getNodeName() + " offset: " + caretOffset : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- return new MozillaDropInfo(canDrop, caretParent, caretOffset);
-
- }
-
- public VpeSourceInnerDropInfo canExternalDropMacro(XModelObject object, Node parentNode, int offset) {
- String tagname = getTagName(object);
- Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
- return visualBuilder.getSourceInnerDropInfo(sourceDragNode, parentNode, offset, false);
- }
-
- public void externalDropAny(final String flavor, final String data, final Point range, Node container) {
- if(flavor == null || flavor.length() == 0) return;
- IDropCommand dropCommand = DropCommandFactory.getInstance().getDropCommand(flavor, JSPTagProposalFactory.getInstance());
-
- boolean promptAttributes = "yes".equals(VpePreference.ALWAYS_REQUEST_FOR_ATTRIBUTE.getValue());
- dropCommand.getDefaultModel().setPromptForTagAttributesRequired(promptAttributes);
-
- dropCommand.execute(
- new DropData(
- flavor,
- data,
- getPageContext(),
- sourceEditor.getEditorInput(),
- (ISourceViewer)sourceEditor.getAdapter(ISourceViewer.class),
- new VpeSelectionProvider(range.x,range.y),
- container
- )
- );
- }
-
- private String getTagName(XModelObject object) {
- String tagname = object.getAttributeValue("name"); //$NON-NLS-1$
-
- XModelObject parent = object.getParent();
- String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
- String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
-
- String[] texts = new String[]{"<"+tagname+">"}; //$NON-NLS-1$ //$NON-NLS-2$
- PaletteInsertHelper.applyPrefix(texts, sourceEditor, tagname, uri, defaultPrefix);
- tagname = texts[0].substring(1,texts[0].length()-1);
-
- return tagname;
- }
-
- public void externalDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
- onHideTooltip();
-
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
- Point range = selectionBuilder.getSourceSelectionRangeAtVisualNode(visualDropInfo.getDropContainer(), (int)visualDropInfo.getDropOffset());
- VpeSourceInnerDropInfo sourceDropInfo = null;
-
- if(MODEL_FLAVOR.equals(flavor)){
- XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
- if(object.getFileType() == XModelObject.FILE && !TLDUtil.isTaglib(object)) {
- flavor = "application/x-moz-file"; //$NON-NLS-1$
- IFile f = (IFile)EclipseResourceUtil.getResource(object);
- try {
- data = f.getLocation().toFile().toURL().toString();
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- }
- } else {
- String tagname = getTagName(object);
- if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
- Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
- if (visualDropInfo.getDropContainer() != null) {
- sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
- range = selectionBuilder.getSourceSelectionRange(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
- }
- }
- }
-
- if (visualDropInfo.getDropContainer() != null) {
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println(" drop! container: " + visualDropInfo.getDropContainer().getNodeName()); //$NON-NLS-1$
- }
- externalDropAny(flavor, data, range, sourceDropInfo == null?null:sourceDropInfo.getContainer());
- }
- }
-
- public void onShowTooltip(int x, int y, final String text) {
-
- if (tip != null && !tip.isDisposed()) tip.dispose();
-
- Display display = visualEditor.getControl().getDisplay();
- Shell parent = visualEditor.getControl().getShell();
-
- tip = new Shell(parent, SWT.NO_FOCUS| SWT.ON_TOP);
- Color bckgColor = new Color(tip.getDisplay(), 255, 250, 236);
- tip.setBackground(bckgColor);
-
- Composite composite = tip;
- GridLayout layout= new GridLayout();
- layout.numColumns = 2;
- layout.marginHeight= 0;
- layout.marginWidth= 0;
- layout.verticalSpacing= 0;
- layout.horizontalSpacing= 0;
- composite.setLayout(layout);
- GridData gd= new GridData(GridData.FILL_BOTH);
- composite.setLayoutData(gd);
-
-
- final StyledText tipControlHeaderText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY);
-
- tipControlHeaderText.setForeground(bckgColor);
- tipControlHeaderText.setBackground(bckgColor);
-
- String formatText = text.trim();
-
- /** attributeString string containing the pairs attribute and it's value as one string*/
- String[] attributeString = formatText.split("\n"); //$NON-NLS-1$
- /** buffer string containing the attribute and the value in the different succeding string*/
- String[] buffer = attributeString[0].split(" "); //$NON-NLS-1$
-
- tipControlHeaderText.setText(buffer[0].toString());
-
- tipControlHeaderText.addLineStyleListener(
- new LineStyleListener() {
- public void lineGetStyle(LineStyleEvent event){
- Color color = new Color(tipControlHeaderText.getDisplay(), 201, 51, 40);
- if (event.lineOffset == 0) {
- StyleRange st = new StyleRange();
- st.fontStyle = SWT.BOLD;
- st.foreground = color;
- event.styles = new StyleRange[]{st};
- st.start = event.lineOffset;
- st.length = event.lineText.length();
- }
- }
- }
- );
-
- GridData gridData = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
- gridData.horizontalAlignment = GridData.FILL;
- gridData.horizontalSpan = 2;
- tipControlHeaderText.setLayoutData(gridData);
-
- StringBuffer tempAttr = new StringBuffer();
- StringBuffer tempValue = new StringBuffer();
-
- if (attributeString.length >= 2) {
- for (int i = 1; i < attributeString.length; i++) {
- buffer = attributeString[i].split(" ", 2); //$NON-NLS-1$
- if (i == 1) {
- tempAttr.append(buffer[0] + " "); //$NON-NLS-1$
- tempValue.append((buffer.length>=2?buffer[1]:"") + " "); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- tempAttr.append("\n" + buffer[0] + " "); //$NON-NLS-1$ //$NON-NLS-2$
- tempValue.append(" \n" + (buffer.length>=2?buffer[1]:"") + " "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
-
- final StyledText tipControlAttributeText = new StyledText(composite,
- SWT.MULTI | SWT.READ_ONLY);
-
- tipControlAttributeText.setForeground(bckgColor);
- tipControlAttributeText.setBackground(bckgColor);
-
- tipControlAttributeText.setText(tempAttr.toString());
- tipControlAttributeText
- .addLineStyleListener(new LineStyleListener() {
- public void lineGetStyle(LineStyleEvent event) {
- Color color = new Color(tipControlHeaderText
- .getDisplay(), 42, 148, 0);
- StyleRange st = new StyleRange();
- st.start = event.lineOffset;
- st.length = event.lineText.length();
- st.foreground = color;
- st.fontStyle = SWT.NORMAL;
- event.styles = new StyleRange[] { st };
- }
- });
- GridData gridData1 = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
- gridData1.horizontalAlignment = GridData.FILL;
- tipControlAttributeText.setLayoutData(gridData1);
-
- final StyledText tipControlValueText = new StyledText(composite,
- SWT.MULTI | SWT.READ_ONLY);
-
- tipControlValueText.setBackground(bckgColor);
-
- tipControlValueText.setText(tempValue.toString());
-
-
-
- GridData gridData2 = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
- gridData2.horizontalAlignment = GridData.FILL;
- tipControlValueText.setLayoutData(gridData2);
- }
- /*
- * Bug in Mozilla embedded API. Tooltip coordinates are wrong for
- * elements inside an inline frame (IFrame tag). The workaround is
- * to position the tooltip based on the mouse cursor location.
- */
- Point point = display.getCursorLocation();
- /* Assuming cursor is 21x21 because this is the size of
- * the arrow cursor on Windows
- */
- point.y += 21;
- tip.setLocation(point);
- tip.pack();
- tip.setVisible(true);
- }
-
- public void onHideTooltip() {
- if (tip != null && !tip.isDisposed()) tip.dispose();
- tip = null;
- }
-
- public VpePageContext getPageContext() {
- return pageContext;
- }
-
- public StructuredTextEditor getSourceEditor() {
- return sourceEditor;
- }
-
- public FormatControllerManager getToolbarFormatControllerManager() {
- return toolbarFormatControllerManager;
- }
-
- public void setToolbarFormatControllerManager(FormatControllerManager formatControllerManager) {
- toolbarFormatControllerManager = formatControllerManager;
- }
- public void setSelectionBarController(SelectionBar selectionBar) {
- this.selectionBar = selectionBar;
- }
-
- public IStructuredModel getModel() {
- return sourceEditor.getModel();
- }
-
- public VpeDomMapping getDomMapping() {
- return domMapping;
- }
-
- public VpeIncludeList getIncludeList(){
- try {
- if(includeList == null)
- throw new Exception("includeList - NULL!!!"); //$NON-NLS-1$
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- }
- return includeList;
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- if (editPart.getVisualMode() != VpeEditorPart.SOURCE_MODE) {
- if(toolbarFormatControllerManager != null) toolbarFormatControllerManager.selectionChanged();
- }
-
- if(selectionBar != null) selectionBar.selectionChanged();
-
- if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
- return;
- }
- if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
- System.out.println(">>>>>>>>>>>>>> selectionChanged " + event.getSource()); //$NON-NLS-1$
- }
- sourceSelectionChanged();
- switcher.stopActiveEditor();
- }
-
- // nsIClipboardDragDropHooks implementation
- public void onPasteOrDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
- onHideTooltip();
-
- VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
- Point range = selectionBuilder.getSourceSelectionRangeAtVisualNode(visualDropInfo.getDropContainer(), (int)visualDropInfo.getDropOffset());
- VpeSourceInnerDropInfo sourceDropInfo = null;
-
- XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
-
- String tagname = getTagName(object);
- if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
- Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
- if (visualDropInfo.getDropContainer() != null) {
- sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
- range = selectionBuilder.getSourceSelectionRange(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
- }
-
- if (visualDropInfo.getDropContainer() != null) {
- if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
- System.out.println(" drop! container: " + visualDropInfo.getDropContainer().getNodeName()); //$NON-NLS-1$
- }
- final String finalFlavor = flavor;
- final String finalData = data;
- final Point finalRange = range;
- final Node finalDropContainer = sourceDropInfo == null ? null : sourceDropInfo.getContainer();
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- externalDropAny(finalFlavor, finalData, finalRange, finalDropContainer);
- }
- });
- }
- }
-
- public void drop(Node node, Node parentNode, int offset) {
- visualBuilder.innerDrop(node, parentNode, offset);
- }
-
- /* (non-Javadoc)
- * @see org.mozilla.interfaces.nsISupports#queryInterface(java.lang.String)
- */
- public nsISupports queryInterface(String arg0) {
- return Mozilla.getInstance().queryInterface(this, arg0);
- }
- /**
- * Calls when editor content should be refreshed
- */
- public void onRefresh() {
- //when we using separate thread to display selection rectangle
- //it's working better than without
- /*
- * HACK
- * We need wait some time while standart event will be handled
- * and in process event handles some components are repainted(like buttons)
- * and flasher are not repainted, so we should paint flasher
- */
-
-
- Display.getDefault().asyncExec(new Thread(){
- public void run(){
-
- getXulRunnerEditor().showSelectionRectangle();
- }
- });
-
- }
-
- /**
- * @return the xulRunnerEditor
- */
- public XulRunnerEditor getXulRunnerEditor() {
- return xulRunnerEditor;
- }
-
- /**
- * @param xulRunnerEditor the xulRunnerEditor to set
- */
- public void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
- this.xulRunnerEditor = xulRunnerEditor;
- }
-
- /**
- * Start drag session
- */
- public void startDragSession(nsIDOMEvent domEvent) {
-
- visualBuilder.getDnd().startDragSession(domEvent);
- }
-
- public void dragDrop(nsIDOMEvent domEvent) {
-
- visualBuilder.getDnd().dragDrop(domEvent,this);
- }
-
- /**
- * @return the selectionBuilder
- */
- public VpeSelectionBuilder getSelectionBuilder() {
- return selectionBuilder;
- }
-
- /**
- * @param selectionBuilder the selectionBuilder to set
- */
- public void setSelectionBuilder(VpeSelectionBuilder selectionBuilder) {
- this.selectionBuilder = selectionBuilder;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IContributionItem;
+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.bindings.Binding;
+import org.eclipse.jface.bindings.keys.KeySequence;
+import org.eclipse.jface.bindings.keys.KeyStroke;
+import org.eclipse.jface.text.ITextSelection;
+import org.eclipse.jface.text.source.ISourceViewer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.LineStyleEvent;
+import org.eclipse.swt.custom.LineStyleListener;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.dnd.Clipboard;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.MenuListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;
+import org.eclipse.ui.internal.keys.WorkbenchKeyboard;
+import org.eclipse.ui.keys.IBindingService;
+import org.eclipse.ui.progress.UIJob;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+import org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent;
+import org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener;
+import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
+import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
+import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
+import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.eclipse.wst.sse.ui.internal.view.events.INodeSelectionListener;
+import org.eclipse.wst.sse.ui.internal.view.events.ITextSelectionListener;
+import org.eclipse.wst.sse.ui.internal.view.events.NodeSelectionChangedEvent;
+import org.eclipse.wst.sse.ui.internal.view.events.TextSelectionChangedEvent;
+import org.eclipse.wst.xml.core.internal.document.AttrImpl;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.eclipse.wst.xml.core.internal.document.NodeImpl;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.event.XModelTreeEvent;
+import org.jboss.tools.common.model.event.XModelTreeListener;
+import org.jboss.tools.common.model.options.PreferenceModelUtilities;
+import org.jboss.tools.common.model.ui.dnd.ModelTransfer;
+import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
+import org.jboss.tools.common.model.ui.editors.dnd.DropCommandFactory;
+import org.jboss.tools.common.model.ui.editors.dnd.DropData;
+import org.jboss.tools.common.model.ui.editors.dnd.IDropCommand;
+import org.jboss.tools.common.model.ui.editors.dnd.JSPTagProposalFactory;
+import org.jboss.tools.common.model.ui.editors.dnd.context.InnerDragBuffer;
+import org.jboss.tools.common.model.ui.objecteditor.ExtendedProperties;
+import org.jboss.tools.common.model.ui.objecteditor.ExtendedPropertiesWizard;
+import org.jboss.tools.common.model.ui.util.ModelUtilities;
+import org.jboss.tools.common.model.ui.views.palette.PaletteInsertHelper;
+import org.jboss.tools.common.model.util.EclipseResourceUtil;
+import org.jboss.tools.common.model.util.ModelFeatureFactory;
+import org.jboss.tools.common.model.util.XModelTreeListenerSWTSync;
+import org.jboss.tools.jst.jsp.editor.IJSPTextEditor;
+import org.jboss.tools.jst.jsp.editor.IVisualController;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.jst.web.tld.TLDToPaletteHelper;
+import org.jboss.tools.jst.web.tld.TLDUtil;
+import org.jboss.tools.jst.web.tld.URIConstants;
+import org.jboss.tools.vpe.VpeDebug;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.bundle.BundleMap;
+import org.jboss.tools.vpe.editor.context.VpePageContext;
+import org.jboss.tools.vpe.editor.css.AbsoluteFolderReferenceList;
+import org.jboss.tools.vpe.editor.css.CSSReferenceList;
+import org.jboss.tools.vpe.editor.css.RelativeFolderReferenceList;
+import org.jboss.tools.vpe.editor.css.ResourceReferenceListListener;
+import org.jboss.tools.vpe.editor.css.TaglibReferenceList;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
+import org.jboss.tools.vpe.editor.menu.NodeActionManager;
+import org.jboss.tools.vpe.editor.menu.BaseActionManager.MyMenuManager;
+import org.jboss.tools.vpe.editor.mozilla.EditorDomEventListener;
+import org.jboss.tools.vpe.editor.mozilla.MozillaDropInfo;
+import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
+import org.jboss.tools.vpe.editor.selection.VpeSelectionController;
+import org.jboss.tools.vpe.editor.selection.VpeSelectionHelper;
+import org.jboss.tools.vpe.editor.template.VpeAnyData;
+import org.jboss.tools.vpe.editor.template.VpeEditAnyDialog;
+import org.jboss.tools.vpe.editor.template.VpeHtmlTemplate;
+import org.jboss.tools.vpe.editor.template.VpeIncludeList;
+import org.jboss.tools.vpe.editor.template.VpeTemplate;
+import org.jboss.tools.vpe.editor.template.VpeTemplateListener;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.jboss.tools.vpe.editor.toolbar.format.FormatControllerManager;
+import org.jboss.tools.vpe.editor.util.HTML;
+import org.jboss.tools.vpe.editor.util.TextUtil;
+import org.jboss.tools.vpe.editor.util.VisualDomUtil;
+import org.jboss.tools.vpe.editor.util.VpeDndUtil;
+import org.jboss.tools.vpe.messages.VpeUIMessages;
+import org.jboss.tools.vpe.selbar.SelectionBar;
+import org.jboss.tools.vpe.xulrunner.browser.util.DOMTreeDumper;
+import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
+import org.mozilla.interfaces.nsIDOMDocument;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMEvent;
+import org.mozilla.interfaces.nsIDOMKeyEvent;
+import org.mozilla.interfaces.nsIDOMMouseEvent;
+import org.mozilla.interfaces.nsIDOMMutationEvent;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.mozilla.interfaces.nsISelection;
+import org.mozilla.interfaces.nsISelectionListener;
+import org.mozilla.interfaces.nsISupports;
+import org.mozilla.xpcom.Mozilla;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+public class VpeController implements INodeAdapter, IModelLifecycleListener, INodeSelectionListener, ITextSelectionListener, SelectionListener, EditorDomEventListener, VpeTemplateListener, XModelTreeListener, ResourceReferenceListListener, ISelectionChangedListener, IVisualController {
+
+ StructuredTextEditor sourceEditor;
+ private MozillaEditor visualEditor;
+// MozillaBrowser browser;
+ XulRunnerEditor xulRunnerEditor;
+ // TODO Sergey Vasilyev figure out with nsIPressShell
+// private nsIPresShell presShell;
+ // TODO Max Areshkau figure out with nsISelectionController
+ private VpeSelectionController visualSelectionController;
+ VpeDomMapping domMapping;
+ private VpeTemplateManager templateManager;
+ private VpeSourceDomBuilder sourceBuilder;
+ public VpeVisualDomBuilder visualBuilder;
+ private VpeSelectionBuilder selectionBuilder;
+ private VpeVisualKeyHandler visualKeyHandler;
+ private ActiveEditorSwitcher switcher = new ActiveEditorSwitcher();
+ private Attr lastRemovedAttr;
+ private String lastRemovedAttrName;
+ private boolean mouseUpSelectionReasonFlag;
+ private boolean mouseDownSelectionFlag;
+ private boolean sourceChangeFlag;
+ private VpePageContext pageContext;
+ private BundleMap bundle;
+ private VpeEditorPart editPart;
+ private static final int AROUND_MENU = 1;
+ private static final int BEFORE_MENU = 2;
+ private static final int AFTER_MENU = 3;
+
+ private CSSReferenceList cssReferenceListListener;
+ private TaglibReferenceList taglibReferenceListListener;
+ private AbsoluteFolderReferenceList absoluteFolderReferenceListListener;
+ private RelativeFolderReferenceList relativeFolderReferenceListListener;
+ private VpeIncludeList includeList = new VpeIncludeList();
+ private VpeVisualInnerDragInfo innerDragInfo = null;
+ private FormatControllerManager toolbarFormatControllerManager = null;
+ private SelectionBar selectionBar = null;
+ private XModelTreeListenerSWTSync optionsListener;
+ //Added by Max Areshkau Fix for JBIDE-1479
+ private UIJob job = null;
+ Shell tip;
+
+ public final static String MODEL_FLAVOR = ModelTransfer.MODEL; //$NON-NLS-1$
+
+ public VpeController(VpeEditorPart editPart){
+
+ this.editPart = editPart;
+ dropWindow = new VpeDropWindow(editPart.getSite().getShell());
+ }
+
+ void init(StructuredTextEditor sourceEditor, MozillaEditor visualEditor) throws Exception {
+ this.sourceEditor = sourceEditor;
+ if(sourceEditor instanceof IJSPTextEditor) {
+ ((IJSPTextEditor)sourceEditor).setVPEController(this);
+ dropWindow.setEditor((IJSPTextEditor)sourceEditor);
+ }
+ this.visualEditor = visualEditor;
+ visualEditor.setController(this);
+ templateManager = VpeTemplateManager.getInstance();
+ bundle = new BundleMap();
+ bundle.init(sourceEditor);
+ pageContext = new VpePageContext(templateManager, bundle, editPart);
+ domMapping = new VpeDomMapping(pageContext);
+ sourceBuilder = new VpeSourceDomBuilder(domMapping, this, templateManager, sourceEditor, pageContext);
+ visualBuilder = new VpeVisualDomBuilder(domMapping, this, templateManager, visualEditor, pageContext);
+ pageContext.setSourceDomBuilder(sourceBuilder);
+ pageContext.setVisualDomBuilder(visualBuilder);
+ IDOMModel sourceModel = (IDOMModel)getModel();
+ if (sourceModel == null) {
+ return;
+ }
+ sourceModel.addModelLifecycleListener(this);
+ IDOMDocument sourceDocument = sourceModel.getDocument();
+ visualBuilder.refreshExternalLinks();
+ visualBuilder.buildDom(sourceDocument);
+
+ templateManager.addTemplateListener(this);
+
+ xulRunnerEditor = visualEditor.getXulRunnerEditor();
+ // TODO Sergey Vasilyev figure out with nsIPressShell
+// presShell = browser.getPresShell();
+ visualSelectionController = new VpeSelectionController(xulRunnerEditor.getSelection());
+ selectionBuilder = new VpeSelectionBuilder(domMapping, sourceBuilder, visualBuilder, visualSelectionController);
+ visualKeyHandler = new VpeVisualKeyHandler(sourceEditor, domMapping, pageContext){
+ public void doSave(IProgressMonitor monitor){
+ editPart.doSave(monitor);
+ }
+ };
+
+// glory
+ ISelectionProvider provider = sourceEditor.getSelectionProvider();
+ //Max Areshkau JBIDE-1105 If selection event received after selection in
+ //visual part we lost focus of selection, so we should process selection event
+ //in time of selection
+// if (provider instanceof IPostSelectionProvider)
+// ((IPostSelectionProvider) provider).addPostSelectionChangedListener(this);
+// else
+ provider.addSelectionChangedListener(this);
+
+// ViewerSelectionManager selectionManager = sourceEditor.getViewerSelectionManager();
+// selectionManager.addNodeSelectionListener(this);
+// selectionManager.addTextSelectionListener(this);
+ StyledText textWidget = VpeSelectionHelper.getSourceTextWidget(sourceEditor);
+ if (textWidget != null) {
+ textWidget.addSelectionListener(this);
+ }
+
+ visualEditor.setEditorDomEventListener(this);
+ switcher.initActiveEditor();
+
+ if (optionsListener == null) {
+ XModelObject optionsObject = ModelUtilities.getPreferenceModel().getByPath(VpePreference.EDITOR_PATH);
+ optionsListener = new XModelTreeListenerSWTSync(this);
+ optionsObject.getModel().addModelTreeListener(optionsListener);
+ }
+
+
+ cssReferenceListListener = CSSReferenceList.getInstance();
+ cssReferenceListListener.addChangeListener(this);
+
+ taglibReferenceListListener = TaglibReferenceList.getInstance();
+ taglibReferenceListListener.addChangeListener(this);
+
+ absoluteFolderReferenceListListener = AbsoluteFolderReferenceList.getInstance();
+ absoluteFolderReferenceListListener.addChangeListener(this);
+
+ relativeFolderReferenceListListener = RelativeFolderReferenceList.getInstance();
+ relativeFolderReferenceListListener.addChangeListener(this);
+
+ pageContext.fireTaglibsChanged();
+ }
+
+ public void dispose() {
+ if (optionsListener != null) {
+ XModelObject optionsObject = ModelUtilities.getPreferenceModel().getByPath(VpePreference.EDITOR_PATH);
+ optionsObject.getModel().removeModelTreeListener(optionsListener);
+ optionsListener.dispose();
+ optionsListener = null;
+ }
+ IDOMModel sourceModel = (IDOMModel)getModel();
+ if (sourceModel != null) {
+ sourceModel.removeModelLifecycleListener(this);
+ }
+ switcher.destroyActiveEditor();
+ switcher=null;
+
+ if (templateManager != null) {
+ templateManager.removeTemplateListener(this);
+ templateManager=null;
+ }
+ if (visualBuilder != null) {
+ visualBuilder.dispose();
+ visualBuilder = null;
+ }
+ sourceBuilder=null;
+ if (sourceEditor != null) {
+//glory
+ ISelectionProvider provider = sourceEditor.getSelectionProvider();
+ provider.removeSelectionChangedListener(this);
+// ViewerSelectionManager selectionManager = sourceEditor.getViewerSelectionManager();
+// selectionManager.removeNodeSelectionListener(this);
+// selectionManager.removeTextSelectionListener(this);
+ StyledText textWidget = VpeSelectionHelper.getSourceTextWidget(sourceEditor);
+ if (textWidget != null) {
+ textWidget.removeSelectionListener(this);
+ }
+ ((IJSPTextEditor)sourceEditor).setVPEController(null);
+
+ }
+ if (dropWindow != null) {
+ dropWindow.setEditor(null);
+ }
+ if (visualEditor != null) {
+ visualEditor.setEditorDomEventListener(null);
+ if (visualSelectionController != null) {
+// visualSelectionController.Release();
+ visualSelectionController = null;
+ }
+ // TODO Sergey Vasilyev figure out with Press Shell
+// if (presShell != null) {
+// presShell.Release();
+// presShell = null;
+// }
+ visualEditor = null;
+ }
+
+ if (cssReferenceListListener != null) {
+ cssReferenceListListener.removeChangeListener(this);
+ }
+ if (taglibReferenceListListener != null) {
+ taglibReferenceListListener.removeChangeListener(this);
+ }
+ if (absoluteFolderReferenceListListener != null) {
+ absoluteFolderReferenceListListener.removeChangeListener(this);
+ }
+ if (relativeFolderReferenceListListener != null) {
+ relativeFolderReferenceListListener.removeChangeListener(this);
+ }
+ toolbarFormatControllerManager = null;
+ }
+
+ // INodeAdapter implementation
+ public boolean isAdapterForType(Object type) {
+ return type == this;
+ }
+ //FIX Fox JBIDE-1479 added by Max Areshkau
+ public void notifyChanged(final INodeNotifier notifier, final int eventType,final Object feature,final Object oldValue,final Object newValue, final int pos) {
+
+ //start job when we modify file in ui thread, without this code
+ //changes will be applied with 1 second delay
+ Display display = null;
+ if (PlatformUI.isWorkbenchRunning())
+ display= PlatformUI.getWorkbench().getDisplay();
+
+ if (display != null && (Thread.currentThread() == display.getThread())) {
+ notifyChangedInUiThread(notifier, eventType, feature, oldValue, newValue, pos);
+ return;
+ }
+ //start job when we modify file in non ui thread
+ if(job!=null) {
+ job.cancel();
+ }
+
+ job = new UIJob("NotifyChangedJob"){
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ //we checks is job was canceled and if is it true we cancel job
+ if(monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ } else {
+ notifyChangedInUiThread(notifier, eventType, feature, oldValue, newValue, pos);
+ }
+ return Status.OK_STATUS;
+ }};
+ job.setPriority(Job.LONG);
+ job.schedule(1000L);
+ }
+
+ public void notifyChangedInUiThread(INodeNotifier notifier, int eventType, Object feature, Object oldValue, Object newValue, int pos) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (VpeDebug.PRINT_SOURCE_MUTATION_EVENT) {
+ printSourceEvent(notifier, eventType, feature, oldValue, newValue, pos);
+ }
+ if(visualBuilder==null) {
+ return;
+ }
+ visualBuilder.rebuildFlag = false;
+
+ switch (eventType) {
+ case INodeNotifier.CHANGE:
+ sourceChangeFlag = true;
+ int type = ((Node)notifier).getNodeType();
+ visualEditor.hideResizer();
+ visualBuilder.setSelectionRectangle(null);
+ if (type == Node.TEXT_NODE) {
+ visualBuilder.setText((Node)notifier);
+ visualEditor.showResizer();
+ //Added by Max Areshkau JBIDE-1554
+ visualBuilder.updateNode((Node)notifier);
+ } else if (type == Node.COMMENT_NODE) {
+ if("yes".equals(VpePreference.SHOW_COMMENTS.getValue())) { //$NON-NLS-1$
+ visualBuilder.setSelectionRectangle(null);
+ visualBuilder.updateNode((Node)notifier);
+ }
+ } else if (feature != null && ((Node)feature).getNodeType() == Node.ATTRIBUTE_NODE) {
+ if (newValue != null) {
+ String attrName = ((Attr)feature).getName();
+ if ((Attr)feature == lastRemovedAttr && !attrName.equals(lastRemovedAttrName)) {
+ lastRemovedAttr = null;
+ visualBuilder.removeAttribute((Element)notifier, lastRemovedAttrName);
+ }
+ visualBuilder.setAttribute((Element)notifier, ((Attr)feature).getName(), (String)newValue);
+ } else {
+ lastRemovedAttr = (Attr)feature;
+ lastRemovedAttrName = ((Attr)feature).getName();
+ visualBuilder.removeAttribute((Element)notifier, lastRemovedAttrName);
+ }
+ }
+ visualEditor.showResizer();
+ break;
+
+ case INodeNotifier.ADD:
+ break;
+
+ case INodeNotifier.REMOVE:
+ visualBuilder.stopToggle((Node)feature);
+ visualBuilder.removeNode((Node)feature);
+ break;
+
+ case INodeNotifier.STRUCTURE_CHANGED:
+ visualEditor.hideResizer();
+ visualBuilder.setSelectionRectangle(null);
+ visualBuilder.updateNode((Node)notifier);
+ break;
+ case INodeNotifier.CONTENT_CHANGED:
+ if (!sourceChangeFlag) {
+ if (feature != null && ((Node)feature).getNodeType() == Node.TEXT_NODE) {
+ //if (((Node)notifier).getNodeName().equalsIgnoreCase("style")) {
+ visualEditor.hideResizer();
+ visualBuilder.setSelectionRectangle(null);
+ visualBuilder.setText((Node)feature);
+ visualEditor.showResizer();
+ //}
+ }
+ } else {
+ sourceChangeFlag = false;
+ }
+ break;
+ }
+ if (visualBuilder.rebuildFlag) {
+ pageContext.fireTaglibsChanged();
+ } else if (pageContext.isTaglibChanged()) {
+ visualRefreshImpl();
+ pageContext.fireTaglibsChanged();
+ }
+ switcher.stopActiveEditor();
+ }
+
+ // INodeSelectionListener implementation
+ public void nodeSelectionChanged(NodeSelectionChangedEvent event) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ List<?> nodes = event.getSelectedNodes();
+ if (nodes != null && nodes.size() > 0) {
+ Node sourceNode = (Node)nodes.get(0);
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println(">>>>>>>>>>>>>> nodeSelectionChanged sourceNode: " + sourceNode.getNodeName() + " " + event.getCaretPosition()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (event.getSource() instanceof IContentOutlinePage) {
+ sourceSelectionChanged();
+ }
+ }
+ switcher.stopActiveEditor();
+ }
+
+ // ITextSelectionListener implementation
+ //TODO Max Areshau looks like this method don't used
+ public void textSelectionChanged(TextSelectionChangedEvent event) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println(">>>>>>>>>>>>>> textSelectionChanged " + event.getSource()); //$NON-NLS-1$
+ }
+// if (event.getSource() instanceof StyledText) {
+ sourceSelectionChanged();
+// }
+ switcher.stopActiveEditor();
+ }
+
+ // SelectionListener implementation
+ public void widgetSelected(SelectionEvent event) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println(">>>>>>>>>>>>>> widgetSelected"); //$NON-NLS-1$
+ }
+ if (event.getSource() instanceof StyledText) {
+ sourceSelectionChanged();
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void widgetDefaultSelected(SelectionEvent event) {
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println(">>>>>>>>>>>>>> widgetDefaultSelected"); //$NON-NLS-1$
+ }
+ }
+
+ public void sourceSelectionChanged() {
+ sourceSelectionChanged(false);
+ }
+
+ public void sourceSelectionChanged(boolean showCaret) {
+ Point range = sourceEditor.getTextViewer().getSelectedRange();
+ int anchorPosition = range.x;
+ int focusPosition = range.x + range.y;
+ boolean extendFlag = range.y != 0;
+ boolean reversionFlag = extendFlag && anchorPosition == VpeSelectionHelper.getCaretOffset(sourceEditor);
+ if (reversionFlag) {
+ anchorPosition = focusPosition;
+ focusPosition = range.x;
+ }
+ Node focusNode = getSourceNodeAt(focusPosition);
+ if (focusNode == null) {
+ return;
+ }
+ int focusOffset = getSourceNodeOffset(focusNode, focusPosition, extendFlag && !reversionFlag);
+ Node anchorNode = null;
+ int anchorOffset = 0;
+ if (extendFlag) {
+ anchorNode = getSourceNodeAt(anchorPosition);
+ anchorOffset = getSourceNodeOffset(anchorNode, anchorPosition, reversionFlag);
+ } else {
+ anchorNode = focusNode;
+ anchorOffset = focusOffset;
+ }
+
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println("sourceSelectionChanged"); //$NON-NLS-1$
+ System.out.println(" anchorNode: " + anchorNode.getNodeName() + " anchorOffset: " + anchorOffset); //$NON-NLS-1$ //$NON-NLS-2$
+ System.out.println(" focusNode: " + focusNode.getNodeName() + " focusOffset: " + focusOffset + " focusPosition: " + focusPosition); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ try{
+ if(anchorNode.getNodeType() == Node.TEXT_NODE || anchorNode.getNodeType() == Node.ATTRIBUTE_NODE){
+ String text;
+ if (anchorNode.getNodeType() == Node.TEXT_NODE) {
+ IndexedRegion region = (IndexedRegion)anchorNode;
+ text = sourceEditor.getTextViewer().getDocument().get(region.getStartOffset(), region.getEndOffset()-region.getStartOffset());
+ } else {
+ text = ((AttrImpl)anchorNode).getValueRegionText();
+ }
+ anchorOffset = TextUtil.visualPosition(text, anchorOffset);
+ }
+ if(focusNode.getNodeType() == Node.TEXT_NODE || focusNode.getNodeType() == Node.ATTRIBUTE_NODE){
+ IndexedRegion region = (IndexedRegion)focusNode;
+ String text;
+ if (focusNode.getNodeType() == Node.TEXT_NODE) {
+ text = sourceEditor.getTextViewer().getDocument().get(region.getStartOffset(), region.getEndOffset()-region.getStartOffset());
+ } else {
+ text = ((AttrImpl)focusNode).getValueRegionText();
+ }
+ focusOffset = TextUtil.visualPosition(text, focusOffset);
+ }
+ }catch(Exception ex){
+ VpePlugin.reportProblem(ex);
+ }
+
+ selectionBuilder.setVisualSelection(anchorNode, anchorOffset, focusNode, focusOffset, reversionFlag, showCaret);
+ }
+
+ public void sourceSelectionToVisualSelection(boolean showCaret) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ sourceSelectionChanged(showCaret);
+ switcher.stopActiveEditor();
+ }
+
+ // IModelLifecycleListener implementation
+ public void processPreModelEvent(ModelLifecycleEvent event) {
+ }
+
+ public void processPostModelEvent(ModelLifecycleEvent event) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (event.getType() == ModelLifecycleEvent.MODEL_RELEASED) {
+ if (VpeDebug.PRINT_SOURCE_MODEL_LIFECYCLE_EVENT) {
+ System.out.println(">>> processPostModelEvent: " + event.toString()); //$NON-NLS-1$
+ }
+ visualBuilder.setSelectionRectangle(null);
+ IStructuredModel model = event.getModel();
+ model.removeModelLifecycleListener(this);
+ IDOMModel sourceModel = (IDOMModel)getModel();
+ sourceModel.addModelLifecycleListener(this);
+ bundle.clearAll();
+ bundle.refresh();
+ visualBuilder.setSelectionRectangle(null);
+ IDOMDocument sourceDocument = sourceModel.getDocument();
+ visualBuilder.rebuildDom(sourceDocument);
+ pageContext.fireTaglibsChanged();
+ }
+ switcher.stopActiveEditor();
+ }
+
+ // EditorDomEventListener implementation
+ public void subtreeModified(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void nodeInserted(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ nsIDOMNode targetNode = mutationEvent.getRelatedNode();
+ if (!VpeVisualDomBuilder.isAnonElement(targetNode)) {
+ sourceBuilder.addNode(targetNode);
+ visualBuilder.resetPseudoElement(targetNode);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void nodeRemoved(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
+ if (!VpeVisualDomBuilder.isAnonElement(targetNode)) {
+ visualBuilder.setSelectionRectangle(null);
+ sourceBuilder.removeNode(targetNode);
+ visualBuilder.resetPseudoElement(targetNode);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void nodeRemovedFromDocument(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void nodeInsertedIntoDocument(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void attrModified(nsIDOMMutationEvent mutationEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void characterDataModified(nsIDOMMutationEvent mutationEvent) {
+
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MUTATION_EVENT) {
+ printVisualEvent(mutationEvent);
+ }
+ nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
+ sourceBuilder.setText(targetNode);
+ visualBuilder.resetPseudoElement(targetNode);
+ switcher.stopActiveEditor();
+ }
+
+ public void notifySelectionChanged(nsIDOMDocument doc, nsISelection selection, short reason) {
+ if (switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ mouseUpSelectionReasonFlag = (reason & nsISelectionListener.MOUSEUP_REASON) > 0;
+ if (mouseUpSelectionReasonFlag || reason == nsISelectionListener.NO_REASON || reason == nsISelectionListener.KEYPRESS_REASON || reason == nsISelectionListener.SELECTALL_REASON || (reason & nsISelectionListener.MOUSEDOWN_REASON) > 0) {
+ if (VpeDebug.PRINT_VISUAL_SELECTION_EVENT) {
+ System.out.println("<<< notifySelectionChanged: " + reason); //$NON-NLS-1$
+ }
+ selectionBuilder.setSelection(selection);
+ }
+ switcher.stopActiveEditor();
+ }
+ }
+
+
+ public void mouseDown(nsIDOMMouseEvent mouseEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ nsIDOMElement visualDragElement = selectionBuilder.getDragElement(mouseEvent);
+ if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
+ System.out.println("<<< mouseDown targetNode: " + visualNode.getNodeName() + " (" + visualNode + ") selectedElement: " + (visualDragElement != null ? visualDragElement.getNodeName() + " (" + visualDragElement + ")" : null)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+ mouseDownSelectionFlag = false;
+
+ if (visualDragElement != null) {
+
+ //we shouldn't change selection when we click on <input type="text" /> element,
+ //because if we change after resizing the input element lost selection
+ if(!(HTML.TAG_INPUT.equalsIgnoreCase(visualDragElement.getNodeName())&&
+ HTML.ATTR_TEXT.equalsIgnoreCase(visualDragElement.getAttribute(HTML.ATTR_TYPE))
+ &&visualDragElement.getAttribute(HTML.ATTR_TYPE)!=null)) {
+
+ selectionBuilder.setVisualElementSelection(visualDragElement);
+ mouseDownSelectionFlag = true;
+ }
+ } else {
+ selectionBuilder.setCaretAtMouse(mouseEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void mouseUp(nsIDOMMouseEvent mouseEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
+ System.out.println("<<< mouseUp"); //$NON-NLS-1$
+ }
+ if (mouseDownSelectionFlag) {
+ mouseEvent.preventDefault();
+ mouseEvent.stopPropagation();
+ mouseDownSelectionFlag = false;
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void mouseClick(nsIDOMMouseEvent mouseEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
+
+ if (visualNode != null) {
+ if (!mouseUpSelectionReasonFlag) {
+ if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
+ System.out.println("<<< mouseClick visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ if (visualBuilder.isContentArea(visualNode)) {
+ selectionBuilder.setClickContentAreaSelection();
+ }
+ } else {
+ mouseUpSelectionReasonFlag = false;
+ }
+
+ if (visualBuilder.doToggle(VisualDomUtil.getTargetNode(mouseEvent))) {
+ selectionBuilder.setClickContentAreaSelection();
+ }
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void mouseDblClick(nsIDOMMouseEvent mouseEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
+ if (visualNode != null) {
+ if (!sourceBuilder.openBundleEditors(visualNode)) {
+ sourceBuilder.openIncludeEditor(visualNode);
+ }
+ if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
+ System.out.println("<<< mouseDblClick visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void mouseMove(nsIDOMMouseEvent mouseEvent) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(mouseEvent);
+ if (visualNode != null) {
+ if (VpeDebug.PRINT_VISUAL_MOUSE_EVENT) {
+ System.out.println("<<< mouseMove visualNode: " + visualNode.getNodeName() + " (" + visualNode + ")");
+ }
+ visualBuilder.setMoveCursor(mouseEvent);
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void keyPress(nsIDOMKeyEvent keyEvent) {
+ if (VpeDebug.PRINT_VISUAL_KEY_EVENT) {
+ System.out.println("<<< keyPress type: " + keyEvent.getType() + " Ctrl: " + keyEvent.getCtrlKey() + " Shift: " + keyEvent.getShiftKey() + " CharCode: " + keyEvent.getCharCode() + " KeyCode: " + keyEvent.getKeyCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ switcher.stopActiveEditor();
+ return;
+ }
+
+ visualEditor.hideResizer();
+ switcher.stopActiveEditor();
+
+
+ try {
+ if (visualKeyHandler.keyPressHandler(keyEvent)) {
+ switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL);
+ // Edward
+ sourceSelectionChanged(true);
+ visualSelectionController.setCaretEnabled(true);
+ switcher.stopActiveEditor();
+ } else {
+ //adding calls of core event handlers, for example 'CTR+H' or 'CTRL+M' event handler dialog
+ Event keyboardEvent = new Event ();
+ //widget where event occur
+ keyboardEvent.widget = xulRunnerEditor.getBrowser();
+
+ keyboardEvent.stateMask = (keyEvent.getAltKey() ? SWT.ALT : 0) | (keyEvent.getCtrlKey() ? SWT.CTRL : 0) | (keyEvent.getShiftKey() ? SWT.SHIFT : 0) | (keyEvent.getMetaKey() ? SWT.MOD1 : 0);
+ keyboardEvent.x=0;
+ keyboardEvent.y=0;
+ keyboardEvent.type=SWT.KeyDown;
+
+ if(keyEvent.getKeyCode()==0) {
+ keyboardEvent.keyCode=(int)keyEvent.getCharCode();
+ } else{
+ keyboardEvent.keyCode=(int)keyEvent.getKeyCode();
+ }
+
+ // JBIDE-1627
+ List<KeyStroke> possibleKeyStrokes = WorkbenchKeyboard.generatePossibleKeyStrokes(keyboardEvent);
+ IWorkbench iWorkbench = VpePlugin.getDefault().getWorkbench();
+ if(iWorkbench.hasService(IBindingService.class)){
+ IBindingService iBindingService = (IBindingService) iWorkbench.getService(IBindingService.class);
+
+ KeySequence sequenceBeforeKeyStroke = KeySequence.getInstance();
+ for (Iterator<KeyStroke> iterator = possibleKeyStrokes.iterator(); iterator
+ .hasNext();){
+ KeySequence sequenceAfterKeyStroke = KeySequence.getInstance(
+ sequenceBeforeKeyStroke, iterator.next());
+ if(iBindingService.isPerfectMatch(sequenceAfterKeyStroke)){
+ final Binding binding = iBindingService.getPerfectMatch(sequenceAfterKeyStroke);
+
+ if((binding!=null)
+ && (binding.getParameterizedCommand()!=null)
+ && (binding.getParameterizedCommand().getCommand()!=null)
+ && ContentAssistCommandAdapter.CONTENT_PROPOSAL_COMMAND.equals(binding.getParameterizedCommand().getCommand().getId())){
+ keyboardEvent.type = SWT.NONE;
+ }
+ }
+ }
+ }
+
+ //sends xulrunner event to eclipse environment
+ getXulRunnerEditor().getBrowser().notifyListeners(keyboardEvent.type, keyboardEvent);
+
+ }
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ visualRefresh();
+ }
+
+ }
+
+ public void elementResized(nsIDOMElement element, int resizerConstrains, int top, int left, int width, int height) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ visualEditor.hideResizer();
+ switcher.stopActiveEditor();
+
+ visualBuilder.resize(element, resizerConstrains, top, left, width, height);
+ sourceSelectionChanged();
+ }
+
+ public void dragGesture(nsIDOMEvent domEvent) {
+
+ nsIDOMMouseEvent mouseEvent = (nsIDOMMouseEvent) domEvent.queryInterface(nsIDOMMouseEvent.NS_IDOMMOUSEEVENT_IID);
+ boolean canDragFlag = canInnerDrag(mouseEvent);
+ //start drag sessionvpe-element
+ if(canDragFlag) {
+ startDragSession(domEvent);
+ }
+ }
+
+ private void createMenuForNode(Node node, MenuManager manager) {
+ createMenuForNode(node, manager, false);
+ }
+
+ private void createMenuForNode(Node node, MenuManager manager, boolean topLevelFlag) {
+ NodeActionManager.setTextNodeSplitter(null);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(node);
+ if (elementMapping != null && elementMapping.getTemplate() != null) {
+ manager.add(new VpeAction("<"+node.getNodeName()+"> Attributes", node) { //$NON-NLS-1$ //$NON-NLS-2$
+ public void run() {
+ showProperties(actionNode);
+ }
+ });
+
+ if (!topLevelFlag) {
+ manager.add(new VpeAction("Select This Tag", node) { //$NON-NLS-1$
+ public void run() {
+ selectionBuilder.setVisualSelection(actionNode,0,actionNode,0,false,true);
+
+ }
+ });
+ }
+ Node parent = node.getParentNode();
+ if(parent != null && parent.getNodeType() == Node.ELEMENT_NODE){
+ MenuManager menuManager = new MenuManager("Parent Tag"); //$NON-NLS-1$
+ menuManager.setParent(manager);
+ manager.add(menuManager);
+ createMenuForNode(parent, menuManager);
+ }
+
+ manager.add(new Separator());
+ }
+ }
+ NodeActionManager actionManager = new NodeActionManager(getModel(), null);
+
+ if (node.getNodeType() == Node.TEXT_NODE) {
+ Point range = sourceEditor.getTextViewer().getSelectedRange();
+ TextNodeSplitterImpl splitter = new TextNodeSplitterImpl(range, (Text)node);
+ NodeActionManager.setTextNodeSplitter(splitter);
+ }
+
+
+ if (actionManager != null) {
+ StructuredSelection structuredSelection = new StructuredSelection(node);
+ actionManager.fillContextMenuForVpe(manager, structuredSelection);
+
+ }
+
+ IContributionItem[] items = manager.getItems();
+
+ for(int i=0;i< items.length;i++){
+ if(items[i] instanceof MenuManager){
+ MenuManager mm = (MenuManager)items[i];
+ if(NodeActionManager.INSERT_AROUND_MENU.equals(mm.getMenuText())){
+ listenContextMenu(mm, (IndexedRegion)node, AROUND_MENU);
+ }else if(NodeActionManager.INSERT_BEFORE_MENU.equals(mm.getMenuText())){
+ listenContextMenu(mm, (IndexedRegion)node, BEFORE_MENU);
+ }else if(NodeActionManager.INSERT_AFTER_MENU.equals(mm.getMenuText())){
+ listenContextMenu(mm, (IndexedRegion)node, AFTER_MENU);
+ }
+ }
+ }
+
+ manager.add(new Separator());
+
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(node);
+ if (elementMapping != null && elementMapping.getTemplate() != null && elementMapping.getTemplate().getType() == VpeHtmlTemplate.TYPE_ANY) {
+ final VpeTemplate selectedTemplate = elementMapping.getTemplate();
+
+ manager.add(new VpeAction("Template", node) { //$NON-NLS-1$
+ public void run() {
+ boolean isCorrectNS = pageContext.isCorrectNS(actionNode);
+ VpeAnyData data = null;
+ if (isCorrectNS) {
+ data = selectedTemplate.getAnyData();
+ data.setUri(pageContext.getSourceTaglibUri(actionNode));
+ data.setName(actionNode.getNodeName());
+ }
+ data = editAnyData(sourceEditor, isCorrectNS, data);
+ if (data != null && data.isChanged()) templateManager.setAnyTemplate(data);
+ }
+ });
+
+ manager.add(new Separator());
+ }
+
+
+ manager.add(new VpeTextOperationAction("Cut", ActionFactory.CUT.getId(), (IndexedRegion)node)); //$NON-NLS-1$
+ manager.add(new VpeTextOperationAction("Copy", ActionFactory.COPY.getId(), (IndexedRegion)node)); //$NON-NLS-1$
+ manager.add(new VpeTextOperationAction("Paste", ActionFactory.PASTE.getId(), (IndexedRegion)node)); //$NON-NLS-1$
+ }else if(node.getNodeType() == Node.TEXT_NODE){
+ manager.add(new Action("Cut") { //$NON-NLS-1$
+ public void run() {
+ sourceEditor.getAction(ActionFactory.CUT.getId()).run();
+ }
+ });
+ manager.add(new Action("Copy") { //$NON-NLS-1$
+ public void run() {
+ sourceEditor.getAction(ActionFactory.COPY.getId()).run();
+ }
+ });
+ manager.add(new Action("Paste") { //$NON-NLS-1$
+ public void run() {
+ sourceEditor.getAction(ActionFactory.PASTE.getId()).run();
+ }
+ });
+ }
+ manager.add(new Separator());
+
+ if (actionManager != null) {
+ StructuredSelection structuredSelection = node.getNodeType() == Node.ELEMENT_NODE ? new StructuredSelection(node) : null;
+ actionManager.addContextMenuForVpe(manager, structuredSelection);
+ }
+
+ if(node.getNodeType() == Node.ELEMENT_NODE){
+ boolean stripEnable = false;
+ NodeImpl impl = (NodeImpl)node;
+ if(impl.isContainer()){
+ NodeList list = impl.getChildNodes();
+ if(list.getLength() > 0){
+ if(list.getLength() == 1){
+ Node child = list.item(0);
+ if(child.getNodeType() == Node.TEXT_NODE){
+ if("".equals(child.getNodeValue().trim()))stripEnable = false; //$NON-NLS-1$
+ else stripEnable = true;
+ }else stripEnable = true;
+ }else stripEnable = true;
+ }
+ }
+ if(stripEnable)
+ manager.add(new VpeAction("Strip Tag", node) { //$NON-NLS-1$
+ public void run() {
+ Node parent = actionNode.getParentNode();
+ if(parent != null){
+ int index = ((NodeImpl)actionNode).getIndex();
+ parent.removeChild(actionNode);
+ NodeList children = actionNode.getChildNodes();
+ int lengh = children.getLength();
+ Node child;
+ for(int i=0; i < lengh; i++){
+ child = children.item(0);
+ actionNode.removeChild(child);
+ insertNode(parent, child, index++);
+ }
+ }
+ }
+
+ private void insertNode(Node parent, Node node, int index){
+ Node oldNode=null;
+ int childSize = parent.getChildNodes().getLength();
+
+ if(index <= (childSize-1))oldNode = parent.getChildNodes().item(index);
+ if(oldNode != null)parent.insertBefore(node, oldNode);
+ else parent.appendChild(node);
+ }
+ });
+ }
+ if(node.getNodeType() == Node.TEXT_NODE){
+ manager.add(new Action("Delete") { //$NON-NLS-1$
+ public void run() {
+ sourceEditor.getAction(ActionFactory.DELETE.getId()).run();
+ }
+ });
+ }
+
+ if (VpeDebug.VISUAL_CONTEXTMENU_DUMP_SOURCE) {
+ manager.add(new Action("Dump Source") { //$NON-NLS-1$
+ public void run() {
+ DOMTreeDumper dumper = new DOMTreeDumper();
+ dumper.dumpToStream(System.out, visualEditor.getDomDocument());
+ }
+ });
+ }
+
+ if (VpeDebug.VISUAL_CONTEXTMENU_DUMP_MAPPING) {
+ manager.add(new Action("Dump Mapping") { //$NON-NLS-1$
+ public void run() {
+ printMapping();
+ }
+ });
+ }
+
+ if (VpeDebug.VISUAL_CONTEXTMENU_TEST) {
+ manager.add(new VpeAction("Test", node) { //$NON-NLS-1$
+ public void run() {
+ test(actionNode);
+ }
+ });
+ }
+ }
+
+ /**
+ * Calls when on when browser receive context menu event.
+ *
+ * @param contextFlags -not used in this function, just for becouse this parametr
+ * exist in nsIContextMenuListener
+ * @param event event from browser used here
+ * @param node where this event are occur
+ */
+ public void onShowContextMenu(long contextFlags, nsIDOMEvent event, nsIDOMNode node) {
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(event);
+
+ if (visualNode != null) {
+ Node selectedSourceNode = null;
+ selectedSourceNode = selectionBuilder.setContextMenuSelection(visualNode);
+ if (selectedSourceNode != null) {
+
+ MenuManager menuManager = new MenuManager("#popup"); //$NON-NLS-1$
+ final Menu contextMenu = menuManager.createContextMenu(visualEditor.getControl());
+ contextMenu.addMenuListener(
+ new MenuListener(){
+ Menu menu = contextMenu;
+ public void menuHidden(MenuEvent e) {
+ Display.getCurrent().asyncExec(
+ new Runnable() {
+ public void run() {
+ menu.dispose();
+ }
+ }
+ );
+ }
+ public void menuShown(MenuEvent e) {
+ }
+ }
+ );
+ createMenuForNode(selectedSourceNode, menuManager, true);
+
+ contextMenu.setVisible(true);
+
+ }
+ }
+ }
+
+
+ private VpeAnyData editAnyData(StructuredTextEditor sourceEditor, boolean isCorrectNS, VpeAnyData data) {
+ Shell shell = sourceEditor.getEditorPart().getSite().getShell();
+ if (isCorrectNS) {
+ VpeEditAnyDialog editDialog = new VpeEditAnyDialog(shell, data);
+ editDialog.open();
+ } else {
+ MessageBox message = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
+ message.setMessage(VpeUIMessages.NAMESPACE_NOT_DEFINED);
+ message.open();
+ }
+ return data;
+ }
+
+ // VpeTemplateListener implementation
+ public void templateReloaded() {
+ visualRefresh();
+ }
+
+ // VpeTaglibListener implementation
+// public void taglibPrefixChanged(String[] prefixs) {
+// if (VpeDebug.printSourceMutationEvent) {
+// String s = ""; //$NON-NLS-1$
+// for (int i = 0; i < prefixs.length; i++) {
+// if (i > 0) {
+// s += ", "; //$NON-NLS-1$
+// }
+// s += prefixs[i];
+// }
+// }
+// queryVisualRefresh = true;
+//// visualRefreshImpl();
+// }
+
+ public void visualRefresh() {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ visualRefreshImpl();
+ pageContext.fireTaglibsChanged();
+
+ switcher.stopActiveEditor();
+ }
+
+ void visualRefreshImpl() {
+ visualEditor.hideResizer();
+ visualBuilder.setSelectionRectangle(null);
+ IDOMModel sourceModel = (IDOMModel)getModel();
+ if (sourceModel != null) {
+ IDOMDocument sourceDocument = sourceModel.getDocument();
+ visualBuilder.rebuildDom(sourceDocument);
+ } else {
+ visualBuilder.rebuildDom(null);
+ }
+ }
+
+ public void preLongOperation() {
+ switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL);
+ }
+
+ public void postLongOperation() {
+ switcher.stopActiveEditor();
+ visualRefresh();
+ }
+
+ // for debug
+ private void printSourceEvent(INodeNotifier notifier, int eventType, Object feature, Object oldValue, Object newValue, int pos) {
+ System.out.println(">>> eventType: " + INodeNotifier.EVENT_TYPE_STRINGS[eventType] + " pos: " + pos + " notifier: " + ((Node)notifier).getNodeName() + " hashCode: " + notifier.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ if (feature != null) {
+ if (feature instanceof Node) {
+ System.out.println(" feature: " + ((Node)feature).getNodeType() + " " + ((Node)feature).getNodeName() + " hashCode: " + feature.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ } else {
+ System.out.println(" feature: " + feature); //$NON-NLS-1$
+ }
+ }
+ if (oldValue != null) {
+ if (oldValue instanceof Node) {
+ System.out.println(" oldValue: " + ((Node)oldValue).getNodeName() + " hashCode: " + oldValue.hashCode()); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ System.out.println(" oldValue: " + oldValue); //$NON-NLS-1$
+ }
+ }
+ if (newValue != null) {
+ if (newValue instanceof Node) {
+ System.out.println(" newValue: " + ((Node)newValue).getNodeName() + " hashCode: " + newValue.hashCode() + " " + ((Node)newValue).getNodeType()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ } else {
+ System.out.println(" newValue: " + newValue); //$NON-NLS-1$
+ }
+ }
+ }
+
+ private void printVisualEvent(nsIDOMEvent event) {
+ System.out.print("<<< " + event.getType()); //$NON-NLS-1$
+
+ if (event instanceof nsIDOMMutationEvent) {
+ nsIDOMMutationEvent mutationEvent = (nsIDOMMutationEvent)event;
+
+ System.out.print(" EventPhase: " + mutationEvent.getEventPhase()); //$NON-NLS-1$
+
+ nsIDOMNode relatedNode = mutationEvent.getRelatedNode();
+ System.out.print(" RelatedNode: " + (relatedNode == null ? null : relatedNode.getNodeName())); //$NON-NLS-1$
+
+ nsIDOMNode targetNode = VisualDomUtil.getTargetNode(mutationEvent);
+ String name = targetNode != null ? targetNode.getNodeName() : null;
+ System.out.print(" TargetNode: " + name + " (" + targetNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ System.out.print(" PrevValue: " + mutationEvent.getPrevValue().trim()); //$NON-NLS-1$
+ System.out.print(" NewValue: " + mutationEvent.getNewValue().trim()); //$NON-NLS-1$
+ }
+ System.out.println();
+ }
+
+ private void printMapping() {
+ domMapping.printMapping();
+ }
+
+ private class ActiveEditorSwitcher {
+ private static final int ACTIVE_EDITOR_CANNOT = 0;
+ private static final int ACTIVE_EDITOR_NONE = 1;
+ private static final int ACTIVE_EDITOR_SOURCE = 2;
+ private static final int ACTIVE_EDITOR_VISUAL = 3;
+
+ private int type = ACTIVE_EDITOR_CANNOT;
+
+ private void initActiveEditor() {
+ type = ACTIVE_EDITOR_NONE;
+ }
+
+ private void destroyActiveEditor() {
+ type = ACTIVE_EDITOR_CANNOT;
+ }
+
+ private boolean startActiveEditor(int newType) {
+ if (type == ACTIVE_EDITOR_NONE) {
+ if( newType == ACTIVE_EDITOR_SOURCE &&
+ editPart.getVisualMode() == VpeEditorPart.SOURCE_MODE) {
+ return false;
+ }
+ type = newType;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private void stopActiveEditor() {
+ onRefresh();
+ type = ACTIVE_EDITOR_NONE;
+ }
+ }
+
+ private void showProperties(Node node){
+ ExtendedProperties p = createExtendedProperties(node);
+ if(p != null) ExtendedPropertiesWizard.run(p);
+ }
+
+ ExtendedProperties createExtendedProperties(Node node) {
+ try {
+ Class c = ModelFeatureFactory.getInstance().getFeatureClass("org.jboss.tools.jst.jsp.outline.VpeProperties"); //$NON-NLS-1$
+ return (ExtendedProperties)c.getDeclaredConstructor(new Class[]{Node.class}).newInstance(new Object[]{node});
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ return null;
+ }
+ }
+
+
+ private void test(Node node) {
+ }
+
+ void refreshBundleValues() {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (bundle != null) {
+ bundle.refresh();
+ if (pageContext != null) {
+ pageContext.refreshBundleValues();
+ }
+ }
+ switcher.stopActiveEditor();
+ }
+
+ void refreshTemplates() {
+ if (includeList.includesRefresh()) {
+ visualRefresh();
+ }
+ if (templateManager != null) {
+ templateManager.reload();
+ }
+ if (bundle != null) {
+ bundle.refresh();
+ if (pageContext != null) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ pageContext.refreshBundleValues();
+ switcher.stopActiveEditor();
+ }
+ }
+ }
+
+ // implements XModelTreeListener
+ public void nodeChanged(XModelTreeEvent event) {
+ visualRefresh();
+ }
+
+ public void structureChanged(XModelTreeEvent event) {
+ }
+
+ private Node getSourceNodeAt(int offset) {
+ if (sourceEditor != null && getModel() != null) {
+ IndexedRegion node = getModel().getIndexedRegion(offset);
+ if (node instanceof IDOMElement) {
+ IDOMElement element = (IDOMElement)node;
+ if (offset < element.getEndStartOffset()) {
+ NamedNodeMap attrs = element.getAttributes();
+ if (attrs != null) {
+ for (int i = 0; i < attrs.getLength(); i++) {
+ if (attrs.item(i) instanceof AttrImpl) {
+ AttrImpl attr = (AttrImpl)attrs.item(i);
+ if (getSourceAttributeOffset(attr, offset) != -1) {
+ VpeElementMapping elementMapping = domMapping.getNearElementMapping(attr.getOwnerElement());
+ if (elementMapping != null) {
+ String[] atributeNames = elementMapping.getTemplate().getOutputAtributeNames();
+ if (atributeNames != null && atributeNames.length > 0 && attr.getName().equalsIgnoreCase(atributeNames[0])) {
+ return attr;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if (node == null) {
+ node = getModel().getIndexedRegion(offset - 1);
+ }
+ if (node instanceof Node) {
+ return (Node) node;
+ }
+ }
+ return null;
+ }
+
+ private int getSourceNodeOffset(Node node, int pos, boolean endFlag) {
+ if (node == null) return 0;
+ int start = ((IndexedRegion)node).getStartOffset();
+ int end = ((IndexedRegion)node).getEndOffset();
+
+ switch (node.getNodeType()) {
+ case Node.ATTRIBUTE_NODE:
+ if (node instanceof AttrImpl) {
+ return getSourceAttributeOffset((AttrImpl)node, pos);
+ }
+ case Node.TEXT_NODE:
+ if (pos < start) {
+ return 0;
+ } else if (pos > end) {
+ return end - start;
+ } else {
+ return pos - start;
+ }
+ case Node.COMMENT_NODE:
+ if (pos > end) {
+ pos = end;
+ }
+ int offset = pos - start - 4;
+ return offset < 0 ? 0 : offset;
+ case Node.ELEMENT_NODE:
+ ElementImpl element = (ElementImpl)node;
+ if (element.isContainer()) {
+ if (pos < element.getStartEndOffset()) {
+ return 0;
+ } else {
+ return 1;
+ }
+ } else {
+ return endFlag ? 1 : 0;
+ }
+ default:
+ return endFlag ? 1 : 0;
+ }
+ }
+
+ private int getSourceAttributeOffset(AttrImpl attr, int pos) {
+ if (attr.getValueRegion() != null) {
+ int start = attr.getValueRegionStartOffset();
+ String value = attr.getValueRegionText();
+ int len = value.length();
+ if (pos >= start && pos <= start + len) {
+ int offset = pos - start;
+ if (len > 1 && value.charAt(0) == '"' && value.charAt(len - 1) == '"') {
+ if (offset <= 0 || offset >= len) {
+ return -1;
+ }
+ offset--;
+ }
+ return offset;
+ }
+ }
+ return -1;
+ }
+
+ private int getSourceNodeOffset1(Node node, int pos, boolean endFlag) {
+ if (node == null) return 0;
+ int start = ((IndexedRegion)node).getStartOffset();
+ int end = ((IndexedRegion)node).getEndOffset();
+
+ switch (node.getNodeType()) {
+ case Node.ATTRIBUTE_NODE:
+ if (node instanceof AttrImpl) {
+ AttrImpl attr = (AttrImpl)node;
+ start = attr.getValueRegionStartOffset();
+ end = start + attr.getValueRegion().getLength();
+ int ret = 0;
+ if (pos > end) {
+ ret = end - start;
+ } else {
+ ret = pos - start;
+ }
+ if (ret > 0 && attr.getValueRegionText().charAt(0) == '"') {
+ ret--;
+ }
+ return ret;
+ }
+ case Node.TEXT_NODE:
+ if (pos < start) {
+ return 0;
+ } else if (pos > end) {
+ return end - start;
+ } else {
+ return pos - start;
+ }
+ case Node.COMMENT_NODE:
+ if (pos > end) {
+ pos = end;
+ }
+ int offset = pos - start - 4;
+ return offset < 0 ? 0 : offset;
+ case Node.ELEMENT_NODE:
+ ElementImpl element = (ElementImpl)node;
+ if (element.isContainer()) {
+ if (pos < element.getStartEndOffset()) {
+ return 0;
+ } else if (pos < element.getStartEndOffset()) {
+ return 1;
+ } else if (pos == element.getStartEndOffset()) {
+ return 2;
+ }
+ } else {
+ return endFlag ? 1 : 0;
+ }
+ default:
+ return endFlag ? 1 : 0;
+ }
+ }
+
+ private void listenContextMenu(MenuManager manager, IndexedRegion region, int type){
+ MenuManager mm = new MyMenuManager("From Palette",true); //$NON-NLS-1$
+ manager.add(mm);
+ manager.addMenuListener(new VpeMenuListener(mm, region, type));
+ }
+
+ class VpeMenuListener implements IMenuListener{
+ private MenuManager manager;
+ private IndexedRegion region;
+ private int type;
+ private boolean loaded=false;
+
+ public VpeMenuListener(MenuManager manager, IndexedRegion region, int type){
+ this.manager = manager;
+ this.region = region;
+ this.type = type;
+ }
+ public void menuAboutToShow(IMenuManager m) {
+ if(loaded)return;
+ loaded=true;
+ fillContextMenuFromPalette(manager, region, type);
+ manager.getParent().update(true);
+ }
+ }
+ private MenuManager fillContextMenuFromPalette(MenuManager manager, IndexedRegion region, int type){
+ XModelObject model = ModelUtilities.getPreferenceModel().getByPath("%Palette%"); //$NON-NLS-1$
+
+ XModelObject[] folders = model.getChildren();
+ for(int i=0;i<folders.length;i++){
+ if ("yes".equals(folders[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
+ MenuManager mm = new MenuManager(folders[i].getAttributeValue("name")); //$NON-NLS-1$
+ manager.add(mm);
+ fillPaletteFolder(mm, region, folders[i], type);
+ }
+ return manager;
+ }
+
+ private void fillPaletteFolder(MenuManager menu, IndexedRegion region, XModelObject folder, int type){
+ XModelObject[] groups = folder.getChildren();
+ for(int i=0;i<groups.length;i++){
+ if ("yes".equals(groups[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
+ MenuManager mm = new MenuManager(groups[i].getAttributeValue("name")); //$NON-NLS-1$
+ menu.add(mm);
+ fillPaletteGroup(mm, region, groups[i], type);
+ }
+ }
+
+ private void fillPaletteGroup(MenuManager menu, IndexedRegion region, XModelObject group, int type){
+ XModelObject[] items = group.getChildren();
+ String endText;
+
+ for(int i=0;i<items.length;i++){
+ if ("yes".equals(items[i].getAttributeValue("hidden"))) continue; //$NON-NLS-1$ //$NON-NLS-2$
+ endText = items[i].getAttributeValue("end text"); //$NON-NLS-1$
+
+ if(type == AROUND_MENU && (endText == null || "".equals(endText))) continue; //$NON-NLS-1$
+ createInsertAction(menu, region, items[i], type);
+ }
+ }
+
+ private void createInsertAction(MenuManager menu, IndexedRegion region, XModelObject item, int type){
+
+
+ XModelObject parent = item.getParent();
+ String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
+ String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
+ String tagName = item.getAttributeValue("name"); //$NON-NLS-1$
+ String[] texts = new String[]{"<"+tagName+">"}; //$NON-NLS-1$ //$NON-NLS-2$
+ if(tagName.indexOf("taglib") < 0) //$NON-NLS-1$
+ PaletteInsertHelper.applyPrefix(texts, sourceEditor, tagName, uri, defaultPrefix);
+ tagName = texts[0];
+
+ menu.add(new InsertAction(tagName, region, item, type));
+ }
+
+ class InsertAction extends Action{
+ private XModelObject item;
+ private int type;
+ private IndexedRegion region;
+
+ public InsertAction(String title, IndexedRegion region, XModelObject item, int type){
+ super(title);
+ this.item = item;
+ this.type = type;
+ this.region = region;
+ }
+ public void run(){
+ try {
+ String tagName = item.getAttributeValue("name"); //$NON-NLS-1$
+
+ XModelObject parent = item.getParent();
+ String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
+ String libraryVersion = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_VERSION); //$NON-NLS-1$
+ String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
+ VpeSelectionProvider selProvider = new VpeSelectionProvider(region);
+
+ String startText = "" + item.getAttributeValue("start text"); //$NON-NLS-1$ //$NON-NLS-2$
+ String endText = "" + item.getAttributeValue("end text"); //$NON-NLS-1$ //$NON-NLS-2$
+ if(type == AROUND_MENU){
+ }else if(type == BEFORE_MENU){
+ selProvider = new VpeSelectionProvider(region.getStartOffset());
+ }else if(type == AFTER_MENU){
+ selProvider = new VpeSelectionProvider(region.getEndOffset());
+ }
+
+ Properties p = new Properties();
+ p.setProperty("tag name", tagName); //$NON-NLS-1$
+ p.setProperty("start text", startText); //$NON-NLS-1$
+ p.setProperty("end text", endText); //$NON-NLS-1$
+ p.setProperty("automatically reformat tag body", "" + item.getAttributeValue("automatically reformat tag body")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ p.setProperty(URIConstants.LIBRARY_URI, uri);
+ p.setProperty(URIConstants.LIBRARY_VERSION, libraryVersion);
+ String addTaglib = item.getParent().getAttributeValue(TLDToPaletteHelper.ADD_TAGLIB);
+ p.setProperty(URIConstants.DEFAULT_PREFIX, defaultPrefix);
+ p.setProperty(PaletteInsertHelper.PROPOPERTY_ADD_TAGLIB, addTaglib);
+ if(((Node)region).getNodeType() == Node.ELEMENT_NODE)
+ p.put("selectionProvider", selProvider); //$NON-NLS-1$
+ PaletteInsertHelper.insertIntoEditor(sourceEditor.getTextViewer(), p);
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ }
+
+ }
+
+ }
+
+ class VpeSelectionProvider implements ISelectionProvider{
+ VpeSelection selection;
+
+ public VpeSelectionProvider(IndexedRegion region){
+ selection = new VpeSelection(region);
+ }
+ public VpeSelectionProvider(int position){
+ selection = new VpeSelection(position);
+ }
+ public VpeSelectionProvider(int offset, int length){
+ selection = new VpeSelection(offset, length);
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ }
+ public ISelection getSelection() {
+ return selection;
+ }
+ public void removeSelectionChangedListener(ISelectionChangedListener listener) {
+
+ }
+ public void setSelection(ISelection selection) {
+ }
+ }
+
+ class VpeSelection implements ITextSelection{
+ String text=""; //$NON-NLS-1$
+ int offset, length;
+
+ public VpeSelection(int position){
+ offset = position;
+ length = 0;
+ }
+
+ public VpeSelection(int offset, int length){
+ this.offset = offset;
+ this.length = length;
+ if (length > 0) {
+ try{
+ text = sourceEditor.getTextViewer().getDocument().get(offset, length);
+ }catch(Exception ex){
+ VpePlugin.reportProblem(ex);
+ }
+ }
+ }
+
+ public VpeSelection(IndexedRegion region){
+ offset = region.getStartOffset();
+ length = region.getEndOffset() - offset;
+ try{
+ text = sourceEditor.getTextViewer().getDocument().get(offset, length);
+ }catch(Exception ex){
+ VpePlugin.reportProblem(ex);
+ }
+ }
+
+ public int getEndLine() {
+ return 0;
+ }
+ public int getLength() {
+ return length;
+ }
+ public int getOffset() {
+ return offset;
+ }
+ public int getStartLine() {
+ return 0;
+ }
+ public String getText() {
+ return text;
+ }
+ public boolean isEmpty() {
+ return false;
+ }
+}
+
+ class VpeAction extends Action{
+ public Node actionNode;
+ public VpeAction(String name, Node node){
+ super(name);
+ this.actionNode = node;
+ }
+ }
+
+ class VpeTextOperationAction extends Action{
+ private String id;
+ private IndexedRegion region;
+ public VpeTextOperationAction(String name, String id, IndexedRegion region){
+ super(name);
+ this.id = id;
+ this.region = region;
+ }
+ public void run(){
+ sourceEditor.getSelectionProvider().setSelection(new VpeSelection(region));
+ sourceEditor.getAction(id).run();
+ }
+ }
+
+ public void refreshExternalLinks() {
+ pageContext.getVisualBuilder().refreshExternalLinks();
+ }
+
+ public IPath getPath() {
+ if (editPart != null) {
+ IEditorInput input = editPart.getEditorInput();
+ if (input != null && input instanceof IFileEditorInput) {
+ return ((IFileEditorInput)input).getFile().getFullPath();
+ }
+ }
+ return null;
+ }
+
+ public void changed(Object source) {
+ if(cssReferenceListListener == source) {
+ pageContext.getVisualBuilder().refreshExternalLinks();
+ } else if (absoluteFolderReferenceListListener == source ||
+ relativeFolderReferenceListListener == source ||
+ taglibReferenceListListener == source) {
+ visualRefresh();
+ }
+ }
+
+ public void dragEnter(nsIDOMEvent event) {
+ if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
+ System.out.println("<<<<<<<<<<<<<<<<<<<< DragEnter"); //$NON-NLS-1$
+ }
+ }
+
+ public void dragExit(nsIDOMEvent event) {
+ if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
+ System.out.println("<<<<<<<<<<<<<<<<<<<< dragExit"); //$NON-NLS-1$
+ }
+ // TODO Sergey Vasilyev figure out with drag caret
+// xulRunnerEditor.hideDragCaret();
+ }
+
+ public void dragOver(nsIDOMEvent event) {
+
+ visualBuilder.getDnd().dragOver(event, this);
+
+ }
+
+ public void _dragOver(nsIDOMEvent event) {
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_VISUAL)) {
+ return;
+ }
+ if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
+ System.out.println("<<<<<<<<<<<<<<<<<<<< dragOver"); //$NON-NLS-1$
+ }
+
+// browser.computeDropPosition(event);
+
+ boolean canDrop = !xulRunnerEditor.isMozillaDragFlavor();
+ if (canDrop) {
+ Clipboard clipboard = new Clipboard(Display.getCurrent());
+ canDrop = clipboard.getContents(ModelTransfer.getInstance()) != null;
+ }
+ if (canDrop) {
+ canDrop = VpeDndUtil.isDropEnabled((IModelObjectEditorInput)sourceEditor.getEditorInput());
+ }
+ if (canDrop) {
+ VpeVisualCaretInfo caretInfo = selectionBuilder.getVisualCaretInfo(event);
+ canDrop = caretInfo.exist();
+ if (canDrop) {
+ caretInfo.showCaret();
+ } else {
+ caretInfo.hideCaret();
+ }
+ }
+ if (!canDrop) {
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ switcher.stopActiveEditor();
+ }
+
+ public void drop(nsIDOMEvent event) {
+ if (VpeDebug.PRINT_VISUAL_DRAGDROP_EVENT) {
+ System.out.println("<<< outerDrop"); //$NON-NLS-1$
+ }
+ event.preventDefault();
+ }
+
+ public boolean canInnerDrag(nsIDOMMouseEvent event) {
+ onHideTooltip();
+
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print("<<<<<< canInnerDrag"); //$NON-NLS-1$
+ }
+ if (innerDragInfo != null) {
+ innerDragInfo.Release();
+ innerDragInfo = null;
+ }
+ boolean canDrag = false;
+ VpeVisualInnerDragInfo dragInfo = selectionBuilder.getInnerDragInfo(event);
+ if (dragInfo != null) {
+ nsIDOMNode dragNode = dragInfo.getNode();
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print(" dragNode: " + dragNode.getNodeName() + "(" + dragNode + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ switch (dragNode.getNodeType()) {
+ case nsIDOMNode.ELEMENT_NODE:
+ canDrag = visualBuilder.canInnerDrag((nsIDOMElement)dragNode);
+ case nsIDOMNode.TEXT_NODE:
+ canDrag = visualBuilder.isTextEditable(dragNode);
+ }
+ if (canDrag) {
+ VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(dragInfo);
+ if (sourceInnerDragInfo.getNode() != null) {
+ innerDragInfo = dragInfo;
+ InnerDragBuffer.object = sourceInnerDragInfo.getNode();
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ InnerDragBuffer.object = null;
+ }
+ });
+ } else {
+ canDrag = false;
+ }
+ }
+ if (!canDrag) {
+ dragInfo.Release();
+ }
+ }
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println(" canDrag: " + canDrag); //$NON-NLS-1$
+ }
+ return canDrag;
+ }
+
+ VpeDropWindow dropWindow = null;
+
+ public MozillaDropInfo canInnerDrop(nsIDOMMouseEvent event) {
+ onHideTooltip();
+
+ if(dropWindow.active) {
+ if(!event.getAltKey()) {
+ dropWindow.close();
+ } else {
+ return null;
+ }
+ }
+ if(event.getAltKey()) {
+ nsIDOMNode visualNode = VisualDomUtil.getTargetNode(event);
+ Node sourceNode = domMapping.getNearSourceNode(visualNode);
+ if(sourceNode != null) {
+ dropWindow.active = true;
+ dropWindow.setEventPosition(event.getScreenX(), event.getScreenY());
+ dropWindow.setInitialTargetNode(sourceNode);
+ dropWindow.open();
+ event.stopPropagation();
+ event.preventDefault();
+ return null;
+ }
+ }
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print("<<<<<< canInnerDrop"); //$NON-NLS-1$
+ }
+ boolean canDrop = false;;
+ nsIDOMNode caretParent = null;
+ long caretOffset = 0;
+ if (innerDragInfo != null) {
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(event);
+ if (visualDropInfo.getDropContainer() != null) {
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print(" x: " + visualDropInfo.getMouseX() + " y: " + visualDropInfo.getMouseY() + //$NON-NLS-1$ //$NON-NLS-2$
+ " container: " + visualDropInfo.getDropContainer().getNodeName() + //$NON-NLS-1$
+ "(" + visualDropInfo.getDropContainer() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
+ " parent: " + visualDropInfo.getDropContainer().getParentNode().getNodeName() + //$NON-NLS-1$
+ "(" + visualDropInfo.getDropContainer().getParentNode() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
+ " offset: " + visualDropInfo.getDropOffset()); //$NON-NLS-1$
+ }
+ VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(innerDragInfo);
+ VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceInnerDragInfo.getNode(), visualDropInfo, true);
+ canDrop = sourceDropInfo.canDrop();
+ if (canDrop) {
+ VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
+ if (newVisualDropInfo != null) {
+ visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
+ caretParent = newVisualDropInfo.getDropContainer();
+ caretOffset = newVisualDropInfo.getDropOffset();
+ }
+ }
+ }
+ visualDropInfo.Release();
+ }
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println(" canDrop: " + canDrop); //$NON-NLS-1$
+ }
+ return new MozillaDropInfo(canDrop, caretParent, caretOffset);
+ }
+
+ public void innerDrop(nsIDOMMouseEvent event) {
+ onHideTooltip();
+
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print("<<<<<< innerDrop"); //$NON-NLS-1$
+ }
+ if (innerDragInfo != null) {
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(event);
+ if (visualDropInfo.getDropContainer() != null) {
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.print(" container: " + visualDropInfo.getDropContainer().getNodeName() + //$NON-NLS-1$
+ "(" + visualDropInfo.getDropContainer() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
+ " offset: " + visualDropInfo.getDropOffset()); //$NON-NLS-1$
+ }
+
+ VpeSourceInnerDragInfo sourceInnerDragInfo = visualBuilder.getSourceInnerDragInfo(innerDragInfo);
+ VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceInnerDragInfo.getNode(), visualDropInfo, true);
+ if(sourceDropInfo.canDrop()){
+ VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
+ if (newVisualDropInfo != null) {
+ visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
+ sourceDropInfo.setTop(visualDropInfo.getMouseY());
+ sourceDropInfo.setLeft(visualDropInfo.getMouseX());
+ visualBuilder.innerDrop(sourceInnerDragInfo, sourceDropInfo);
+ if (innerDragInfo != null) {
+ innerDragInfo.Release();
+ innerDragInfo = null;
+ }
+ }
+ }
+ }
+ }
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println();
+ }
+ }
+
+ public MozillaDropInfo canExternalDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
+ InnerDragBuffer.object = null;
+ onHideTooltip();
+
+ if(dropWindow.active) {
+ if(!mouseEvent.getAltKey()) {
+ dropWindow.close();
+ } else {
+ return new MozillaDropInfo(false, null, 0);
+ }
+ }
+ if(mouseEvent.getAltKey()) {
+ nsIDOMEvent event = (nsIDOMEvent) mouseEvent.queryInterface(nsIDOMEvent.NS_IDOMEVENT_IID);
+ nsIDOMNode visualNode = (nsIDOMNode) event.getTarget().queryInterface(nsIDOMNode.NS_IDOMNODE_IID);
+ Node sourceNode = domMapping.getNearSourceNode(visualNode);
+ if(sourceNode != null) {
+ if(ModelTransfer.MODEL.equals(flavor)){ //$NON-NLS-1$
+// XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
+// InnerDragBuffer.object = object;
+ } else {
+ dropWindow.flavor = flavor;
+ }
+ dropWindow.active = true;
+ dropWindow.setEventPosition(mouseEvent.getScreenX(), mouseEvent.getScreenY());
+ dropWindow.setInitialTargetNode(sourceNode);
+ dropWindow.open();
+ mouseEvent.stopPropagation();
+ mouseEvent.preventDefault();
+ return new MozillaDropInfo(false, null, 0);
+ }
+ }
+ boolean canDrop = false;
+ nsIDOMNode caretParent = null;
+ long caretOffset = 0;
+
+ if(MODEL_FLAVOR.equals(flavor)){
+ XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
+ if(object.getFileType() == XModelObject.FILE && !TLDUtil.isTaglib(object)) {
+ IFile f = (IFile)EclipseResourceUtil.getResource(object);
+ canDrop = f != null;
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
+ caretParent = visualDropInfo.getDropContainer();
+ caretOffset = visualDropInfo.getDropOffset();
+ } else {
+ String tagname = getTagName(object);
+ if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
+ Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
+ if (visualDropInfo.getDropContainer() != null) {
+ VpeSourceInnerDropInfo sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
+ canDrop = sourceDropInfo.canDrop();
+ if (canDrop) {
+ VpeVisualInnerDropInfo newVisualDropInfo = visualBuilder.getInnerDropInfo(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
+ if (newVisualDropInfo != null) {
+ visualBuilder.correctVisualDropPosition(newVisualDropInfo, visualDropInfo);
+ caretParent = newVisualDropInfo.getDropContainer();
+ caretOffset = newVisualDropInfo.getDropOffset();
+ }
+ }
+ }
+ visualDropInfo.Release();
+ }
+ }else if(XulRunnerEditor.TRANS_FLAVOR_kFileMime.equals(flavor) ||
+ XulRunnerEditor.TRANS_FLAVOR_kURLMime.equals(flavor)) {
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
+ caretParent = visualDropInfo.getDropContainer();
+ caretOffset = visualDropInfo.getDropOffset();
+ try {
+ canDrop = true;
+ } catch (Exception ex) {
+ VpePlugin.reportProblem(ex);
+ }
+ }
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println(" canDrop: " + canDrop + (canDrop ? " container: " + caretParent.getNodeName() + " offset: " + caretOffset : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+ return new MozillaDropInfo(canDrop, caretParent, caretOffset);
+
+ }
+
+ public VpeSourceInnerDropInfo canExternalDropMacro(XModelObject object, Node parentNode, int offset) {
+ String tagname = getTagName(object);
+ Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
+ return visualBuilder.getSourceInnerDropInfo(sourceDragNode, parentNode, offset, false);
+ }
+
+ public void externalDropAny(final String flavor, final String data, final Point range, Node container) {
+ if(flavor == null || flavor.length() == 0) return;
+ IDropCommand dropCommand = DropCommandFactory.getInstance().getDropCommand(flavor, JSPTagProposalFactory.getInstance());
+
+ boolean promptAttributes = "yes".equals(VpePreference.ALWAYS_REQUEST_FOR_ATTRIBUTE.getValue());
+ dropCommand.getDefaultModel().setPromptForTagAttributesRequired(promptAttributes);
+
+ dropCommand.execute(
+ new DropData(
+ flavor,
+ data,
+ getPageContext(),
+ sourceEditor.getEditorInput(),
+ (ISourceViewer)sourceEditor.getAdapter(ISourceViewer.class),
+ new VpeSelectionProvider(range.x,range.y),
+ container
+ )
+ );
+ }
+
+ private String getTagName(XModelObject object) {
+ String tagname = object.getAttributeValue("name"); //$NON-NLS-1$
+
+ XModelObject parent = object.getParent();
+ String uri = (parent == null) ? "" : parent.getAttributeValue(URIConstants.LIBRARY_URI); //$NON-NLS-1$
+ String defaultPrefix = (parent == null) ? "" : parent.getAttributeValue(URIConstants.DEFAULT_PREFIX); //$NON-NLS-1$
+
+ String[] texts = new String[]{"<"+tagname+">"}; //$NON-NLS-1$ //$NON-NLS-2$
+ PaletteInsertHelper.applyPrefix(texts, sourceEditor, tagname, uri, defaultPrefix);
+ tagname = texts[0].substring(1,texts[0].length()-1);
+
+ return tagname;
+ }
+
+ public void externalDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
+ onHideTooltip();
+
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
+ Point range = selectionBuilder.getSourceSelectionRangeAtVisualNode(visualDropInfo.getDropContainer(), (int)visualDropInfo.getDropOffset());
+ VpeSourceInnerDropInfo sourceDropInfo = null;
+
+ if(MODEL_FLAVOR.equals(flavor)){
+ XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
+ if(object.getFileType() == XModelObject.FILE && !TLDUtil.isTaglib(object)) {
+ flavor = "application/x-moz-file"; //$NON-NLS-1$
+ IFile f = (IFile)EclipseResourceUtil.getResource(object);
+ try {
+ data = f.getLocation().toFile().toURL().toString();
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+ } else {
+ String tagname = getTagName(object);
+ if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
+ Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
+ if (visualDropInfo.getDropContainer() != null) {
+ sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
+ range = selectionBuilder.getSourceSelectionRange(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
+ }
+ }
+ }
+
+ if (visualDropInfo.getDropContainer() != null) {
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println(" drop! container: " + visualDropInfo.getDropContainer().getNodeName()); //$NON-NLS-1$
+ }
+ externalDropAny(flavor, data, range, sourceDropInfo == null?null:sourceDropInfo.getContainer());
+ }
+ }
+
+ public void onShowTooltip(int x, int y, final String text) {
+
+ if (tip != null && !tip.isDisposed()) tip.dispose();
+
+ Display display = visualEditor.getControl().getDisplay();
+ Shell parent = visualEditor.getControl().getShell();
+
+ tip = new Shell(parent, SWT.NO_FOCUS| SWT.ON_TOP);
+ Color bckgColor = new Color(tip.getDisplay(), 255, 250, 236);
+ tip.setBackground(bckgColor);
+
+ Composite composite = tip;
+ GridLayout layout= new GridLayout();
+ layout.numColumns = 2;
+ layout.marginHeight= 0;
+ layout.marginWidth= 0;
+ layout.verticalSpacing= 0;
+ layout.horizontalSpacing= 0;
+ composite.setLayout(layout);
+ GridData gd= new GridData(GridData.FILL_BOTH);
+ composite.setLayoutData(gd);
+
+
+ final StyledText tipControlHeaderText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY);
+
+ tipControlHeaderText.setForeground(bckgColor);
+ tipControlHeaderText.setBackground(bckgColor);
+
+ String formatText = text.trim();
+
+ /** attributeString string containing the pairs attribute and it's value as one string*/
+ String[] attributeString = formatText.split("\n"); //$NON-NLS-1$
+ /** buffer string containing the attribute and the value in the different succeding string*/
+ String[] buffer = attributeString[0].split(" "); //$NON-NLS-1$
+
+ tipControlHeaderText.setText(buffer[0].toString());
+
+ tipControlHeaderText.addLineStyleListener(
+ new LineStyleListener() {
+ public void lineGetStyle(LineStyleEvent event){
+ Color color = new Color(tipControlHeaderText.getDisplay(), 201, 51, 40);
+ if (event.lineOffset == 0) {
+ StyleRange st = new StyleRange();
+ st.fontStyle = SWT.BOLD;
+ st.foreground = color;
+ event.styles = new StyleRange[]{st};
+ st.start = event.lineOffset;
+ st.length = event.lineText.length();
+ }
+ }
+ }
+ );
+
+ GridData gridData = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.horizontalSpan = 2;
+ tipControlHeaderText.setLayoutData(gridData);
+
+ StringBuffer tempAttr = new StringBuffer();
+ StringBuffer tempValue = new StringBuffer();
+
+ if (attributeString.length >= 2) {
+ for (int i = 1; i < attributeString.length; i++) {
+ buffer = attributeString[i].split(" ", 2); //$NON-NLS-1$
+ if (i == 1) {
+ tempAttr.append(buffer[0] + " "); //$NON-NLS-1$
+ tempValue.append((buffer.length>=2?buffer[1]:"") + " "); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ tempAttr.append("\n" + buffer[0] + " "); //$NON-NLS-1$ //$NON-NLS-2$
+ tempValue.append(" \n" + (buffer.length>=2?buffer[1]:"") + " "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+
+ final StyledText tipControlAttributeText = new StyledText(composite,
+ SWT.MULTI | SWT.READ_ONLY);
+
+ tipControlAttributeText.setForeground(bckgColor);
+ tipControlAttributeText.setBackground(bckgColor);
+
+ tipControlAttributeText.setText(tempAttr.toString());
+ tipControlAttributeText
+ .addLineStyleListener(new LineStyleListener() {
+ public void lineGetStyle(LineStyleEvent event) {
+ Color color = new Color(tipControlHeaderText
+ .getDisplay(), 42, 148, 0);
+ StyleRange st = new StyleRange();
+ st.start = event.lineOffset;
+ st.length = event.lineText.length();
+ st.foreground = color;
+ st.fontStyle = SWT.NORMAL;
+ event.styles = new StyleRange[] { st };
+ }
+ });
+ GridData gridData1 = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
+ gridData1.horizontalAlignment = GridData.FILL;
+ tipControlAttributeText.setLayoutData(gridData1);
+
+ final StyledText tipControlValueText = new StyledText(composite,
+ SWT.MULTI | SWT.READ_ONLY);
+
+ tipControlValueText.setBackground(bckgColor);
+
+ tipControlValueText.setText(tempValue.toString());
+
+
+
+ GridData gridData2 = new GridData(GridData.BEGINNING | GridData.FILL_BOTH);
+ gridData2.horizontalAlignment = GridData.FILL;
+ tipControlValueText.setLayoutData(gridData2);
+ }
+ /*
+ * Bug in Mozilla embedded API. Tooltip coordinates are wrong for
+ * elements inside an inline frame (IFrame tag). The workaround is
+ * to position the tooltip based on the mouse cursor location.
+ */
+ Point point = display.getCursorLocation();
+ /* Assuming cursor is 21x21 because this is the size of
+ * the arrow cursor on Windows
+ */
+ point.y += 21;
+ tip.setLocation(point);
+ tip.pack();
+ tip.setVisible(true);
+ }
+
+ public void onHideTooltip() {
+ if (tip != null && !tip.isDisposed()) tip.dispose();
+ tip = null;
+ }
+
+ public VpePageContext getPageContext() {
+ return pageContext;
+ }
+
+ public StructuredTextEditor getSourceEditor() {
+ return sourceEditor;
+ }
+
+ public FormatControllerManager getToolbarFormatControllerManager() {
+ return toolbarFormatControllerManager;
+ }
+
+ public void setToolbarFormatControllerManager(FormatControllerManager formatControllerManager) {
+ toolbarFormatControllerManager = formatControllerManager;
+ }
+ public void setSelectionBarController(SelectionBar selectionBar) {
+ this.selectionBar = selectionBar;
+ }
+
+ public IStructuredModel getModel() {
+ return sourceEditor.getModel();
+ }
+
+ public VpeDomMapping getDomMapping() {
+ return domMapping;
+ }
+
+ public VpeIncludeList getIncludeList(){
+ try {
+ if(includeList == null)
+ throw new Exception("includeList - NULL!!!"); //$NON-NLS-1$
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+ return includeList;
+ }
+
+ public void selectionChanged(SelectionChangedEvent event) {
+ if (editPart.getVisualMode() != VpeEditorPart.SOURCE_MODE) {
+ if(toolbarFormatControllerManager != null) toolbarFormatControllerManager.selectionChanged();
+ }
+
+ if(selectionBar != null) selectionBar.selectionChanged();
+
+ if (!switcher.startActiveEditor(ActiveEditorSwitcher.ACTIVE_EDITOR_SOURCE)) {
+ return;
+ }
+ if (VpeDebug.PRINT_SOURCE_SELECTION_EVENT) {
+ System.out.println(">>>>>>>>>>>>>> selectionChanged " + event.getSource()); //$NON-NLS-1$
+ }
+ sourceSelectionChanged();
+ switcher.stopActiveEditor();
+ }
+
+ // nsIClipboardDragDropHooks implementation
+ public void onPasteOrDrop(nsIDOMMouseEvent mouseEvent, String flavor, String data) {
+ onHideTooltip();
+
+ VpeVisualInnerDropInfo visualDropInfo = selectionBuilder.getInnerDropInfo(mouseEvent);
+ Point range = selectionBuilder.getSourceSelectionRangeAtVisualNode(visualDropInfo.getDropContainer(), (int)visualDropInfo.getDropOffset());
+ VpeSourceInnerDropInfo sourceDropInfo = null;
+
+ XModelObject object = PreferenceModelUtilities.getPreferenceModel().getModelBuffer().source();
+
+ String tagname = getTagName(object);
+ if(tagname.indexOf("taglib") >= 0) tagname= "taglib"; //$NON-NLS-1$ //$NON-NLS-2$
+ Node sourceDragNode = ((Document)getModel().getAdapter(Document.class)).createElement(tagname);
+ if (visualDropInfo.getDropContainer() != null) {
+ sourceDropInfo = visualBuilder.getSourceInnerDropInfo(sourceDragNode, visualDropInfo, true);
+ range = selectionBuilder.getSourceSelectionRange(sourceDropInfo.getContainer(), sourceDropInfo.getOffset());
+ }
+
+ if (visualDropInfo.getDropContainer() != null) {
+ if (VpeDebug.PRINT_VISUAL_INNER_DRAGDROP_EVENT) {
+ System.out.println(" drop! container: " + visualDropInfo.getDropContainer().getNodeName()); //$NON-NLS-1$
+ }
+ final String finalFlavor = flavor;
+ final String finalData = data;
+ final Point finalRange = range;
+ final Node finalDropContainer = sourceDropInfo == null ? null : sourceDropInfo.getContainer();
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ externalDropAny(finalFlavor, finalData, finalRange, finalDropContainer);
+ }
+ });
+ }
+ }
+
+ public void drop(Node node, Node parentNode, int offset) {
+ visualBuilder.innerDrop(node, parentNode, offset);
+ }
+
+ /* (non-Javadoc)
+ * @see org.mozilla.interfaces.nsISupports#queryInterface(java.lang.String)
+ */
+ public nsISupports queryInterface(String arg0) {
+ return Mozilla.getInstance().queryInterface(this, arg0);
+ }
+ /**
+ * Calls when editor content should be refreshed
+ */
+ public void onRefresh() {
+ //when we using separate thread to display selection rectangle
+ //it's working better than without
+ /*
+ * HACK
+ * We need wait some time while standart event will be handled
+ * and in process event handles some components are repainted(like buttons)
+ * and flasher are not repainted, so we should paint flasher
+ */
+
+
+ Display.getDefault().asyncExec(new Thread(){
+ public void run(){
+
+ getXulRunnerEditor().showSelectionRectangle();
+ }
+ });
+
+ }
+
+ /**
+ * @return the xulRunnerEditor
+ */
+ public XulRunnerEditor getXulRunnerEditor() {
+ return xulRunnerEditor;
+ }
+
+ /**
+ * @param xulRunnerEditor the xulRunnerEditor to set
+ */
+ public void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
+ this.xulRunnerEditor = xulRunnerEditor;
+ }
+
+ /**
+ * Start drag session
+ */
+ public void startDragSession(nsIDOMEvent domEvent) {
+
+ visualBuilder.getDnd().startDragSession(domEvent);
+ }
+
+ public void dragDrop(nsIDOMEvent domEvent) {
+
+ visualBuilder.getDnd().dragDrop(domEvent,this);
+ }
+
+ /**
+ * @return the selectionBuilder
+ */
+ public VpeSelectionBuilder getSelectionBuilder() {
+ return selectionBuilder;
+ }
+
+ /**
+ * @param selectionBuilder the selectionBuilder to set
+ */
+ public void setSelectionBuilder(VpeSelectionBuilder selectionBuilder) {
+ this.selectionBuilder = selectionBuilder;
+ }
+
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeDomBuilder.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeDomBuilder.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeDomBuilder.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,52 +1,74 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor;
-
-import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
-import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
-import org.w3c.dom.Node;
-
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-
-public class VpeDomBuilder {
- protected VpeDomMapping domMapping;
-
- protected VpeTemplateManager templateManager;
- private INodeAdapter sorceAdapter;
-
- public VpeDomBuilder(VpeDomMapping domMapping, INodeAdapter sorceAdapter, VpeTemplateManager templateManager) {
- this.domMapping = domMapping;
- this.sorceAdapter = sorceAdapter;
- this.templateManager = templateManager;
- }
-
- public VpeDomMapping getDomMapping () {
- return domMapping;
- }
-
- public VpeTemplateManager getTemplateManager () {
- return templateManager;
- }
-
- public void registerNodes(VpeNodeMapping nodeMapping) {
- if (sorceAdapter == null) {
- return;
- }
-
- domMapping.mapNodes(nodeMapping);
- Node sourceNode = nodeMapping.getSourceNode();
- if (((INodeNotifier) sourceNode).getExistingAdapter(sorceAdapter) == null) {
- ((INodeNotifier) sourceNode).addAdapter(sorceAdapter);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
+import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.w3c.dom.Node;
+
+public class VpeDomBuilder {
+ protected VpeDomMapping domMapping;
+
+ protected VpeTemplateManager templateManager;
+ private INodeAdapter sorceAdapter;
+ private List sourceNodes = new ArrayList();
+
+ public VpeDomBuilder(VpeDomMapping domMapping, INodeAdapter sorceAdapter, VpeTemplateManager templateManager) {
+ this.domMapping = domMapping;
+ this.sorceAdapter = sorceAdapter;
+ this.templateManager = templateManager;
+ }
+
+ public VpeDomMapping getDomMapping () {
+ return domMapping;
+ }
+
+ public VpeTemplateManager getTemplateManager () {
+ return templateManager;
+ }
+
+ public void registerNodes(VpeNodeMapping nodeMapping) {
+ if (sorceAdapter == null) {
+ return;
+ }
+
+ domMapping.mapNodes(nodeMapping);
+ Node sourceNode = nodeMapping.getSourceNode();
+ if (((INodeNotifier) sourceNode).getExistingAdapter(sorceAdapter) == null) {
+ ((INodeNotifier) sourceNode).addAdapter(sorceAdapter);
+ sourceNodes.add(sourceNode);
+ }
+ }
+ public void dispose() {
+ for (Iterator iterator = sourceNodes.iterator(); iterator.hasNext();) {
+ INodeNotifier sourceNode = (INodeNotifier) iterator.next();
+ if (sourceNode != null) {
+ sourceNode.removeAdapter(sorceAdapter);
+ }
+ }
+ sourceNodes.clear();
+ }
+
+ public INodeAdapter getSorceAdapter() {
+ return sorceAdapter;
+ }
+
+ public List getSourceNodes() {
+ return sourceNodes;
+ }
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeEditorPart.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeEditorPart.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeEditorPart.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,703 +1,754 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor;
-
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.ShellAdapter;
-import org.eclipse.swt.events.ShellEvent;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IPropertyListener;
-import org.eclipse.ui.IReusableEditor;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartConstants;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.IStatusField;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.event.XModelTreeEvent;
-import org.jboss.tools.common.model.event.XModelTreeListener;
-import org.jboss.tools.common.model.ui.util.ModelUtilities;
-import org.jboss.tools.jst.jsp.editor.IVisualEditor;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.mozilla.EditorLoadWindowListener;
-import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
-import org.jboss.tools.vpe.editor.mozilla.MozillaPreview;
-import org.jboss.tools.vpe.editor.xpl.SashForm;
-import org.jboss.tools.vpe.selbar.SelectionBar;
-
-public class VpeEditorPart extends EditorPart implements ITextEditor,
- ITextEditorExtension, IReusableEditor, IVisualEditor {
- private SashForm container;
- private StructuredTextEditor sourceEditor = null;
- private MozillaEditor visualEditor;
- private IEditorPart activeEditor;
- private XModelTreeListener listener;
- XModelObject optionsObject;
- private SelectionBar selectionBar = new SelectionBar();
- private ActivationListener activationListener = new ActivationListener();
- private int visualMode = 0;
- private EditorPart multiPageEditor;
- private static final QualifiedName SPLITTER_POSITION_KEY1 = new QualifiedName(
- "", "splitter_position1");
- private static final QualifiedName SPLITTER_POSITION_KEY2 = new QualifiedName(
- "", "splitter_position2");
- private static final QualifiedName SPLITTER_POSITION_KEY3 = new QualifiedName(
- "", "splitter_position3");
-
- private int controlCount = 0;
-
- /** default web-browser */
- private MozillaPreview previewWebBrowser = null;
-
- /** preview content */
- private Composite previewContent = null;
-
- public StructuredTextEditor getSourceEditor() {
- return sourceEditor;
- }
-
- // returns JSPMultipageEditor for closing by ctrl+F4 and ctrl+shift+F4 keys
- public EditorPart getParentEditor() {
- return multiPageEditor;
- }
-
- public void close(boolean save) {
- if (sourceEditor != null)
- sourceEditor.close(save);
- }
-
- public void doRevertToSaved() {
- if (sourceEditor != null)
- sourceEditor.doRevertToSaved();
- }
-
- public IDocumentProvider getDocumentProvider() {
- if (sourceEditor != null)
- return sourceEditor.getDocumentProvider();
- else {
- return null;
- }
- }
-
- public IRegion getHighlightRange() {
- if (sourceEditor != null)
- return sourceEditor.getHighlightRange();
- else {
- return null;
- }
- }
-
- public ISelectionProvider getSelectionProvider() {
- if (sourceEditor != null)
- return sourceEditor.getSelectionProvider();
- else {
- return null;
- }
- }
-
- public boolean isEditable() {
- if (sourceEditor != null)
- return sourceEditor.isEditable();
- else {
- return false;
- }
- }
-
- public void removeActionActivationCode(String actionId) {
- if (sourceEditor != null)
- sourceEditor.removeActionActivationCode(actionId);
- }
-
- public void resetHighlightRange() {
- if (sourceEditor != null)
- sourceEditor.resetHighlightRange();
- }
-
- public void selectAndReveal(int offset, int length) {
- if (sourceEditor != null)
- sourceEditor.selectAndReveal(offset, length);
- }
-
- public void setAction(String actionID, IAction action) {
- if (sourceEditor != null)
- sourceEditor.setAction(actionID, action);
- }
-
- public void setActionActivationCode(String actionId,
- char activationCharacter, int activationKeyCode,
- int activationStateMask) {
- if (sourceEditor != null)
- sourceEditor.setActionActivationCode(actionId, activationCharacter,
- activationKeyCode, activationStateMask);
- }
-
- public void setHighlightRange(int offset, int length, boolean moveCursor) {
- if (sourceEditor != null)
- sourceEditor.setHighlightRange(offset, length, moveCursor);
- }
-
- public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
- if (sourceEditor != null)
- sourceEditor.showHighlightRangeOnly(showHighlightRangeOnly);
- }
-
- public boolean showsHighlightRangeOnly() {
- if (sourceEditor != null)
- return sourceEditor.showsHighlightRangeOnly();
- else {
- return false;
- }
- }
-
- public void addRulerContextMenuListener(IMenuListener listener) {
- if (sourceEditor != null)
- sourceEditor.addRulerContextMenuListener(listener);
- }
-
- public boolean isEditorInputReadOnly() {
- if (sourceEditor != null)
- return sourceEditor.isEditorInputReadOnly();
- else {
- return false;
- }
- }
-
- public void removeRulerContextMenuListener(IMenuListener listener) {
- if (sourceEditor != null)
- sourceEditor.removeRulerContextMenuListener(listener);
- }
-
- public void setStatusField(IStatusField field, String category) {
- if (visualMode == VISUAL_MODE) {
- if (field != null) {
- field.setImage(null);
- field.setText(null);
- }
- } else if (sourceEditor != null)
- sourceEditor.setStatusField(field, category);
- }
-
- public VpeEditorPart(EditorPart multiPageEditor,
- StructuredTextEditor textEditor, boolean visualMode) {
- sourceEditor = textEditor;
- // this.visualMode = visualMode;
- this.multiPageEditor = multiPageEditor;
- }
-
- public IAction getAction(String actionID) {
- return sourceEditor.getAction(actionID);
- }
-
- public VpeEditorPart() {
- }
-
- public void doSave(IProgressMonitor monitor) {
- if (sourceEditor != null) {
- sourceEditor.doSave(monitor);
- }
- }
-
- public void doSaveAs() {
- if (sourceEditor != null) {
- sourceEditor.doSaveAs();
- setInput(sourceEditor.getEditorInput());
- }
- }
-
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- setSite(site);
- setInput(input);
- }
-
- public void setInput(IEditorInput input) {
- super.setInput(input);
- if (visualEditor != null && visualEditor.getEditorInput() != null
- && visualEditor.getEditorInput() != getEditorInput()) {
- visualEditor.setInput(input);
- }
- }
-
- public boolean isDirty() {
- if (sourceEditor != null) {
- return sourceEditor.isDirty();
- } else {
- return false;
- }
- }
-
- public boolean isSaveAsAllowed() {
- if (sourceEditor != null) {
- return sourceEditor.isSaveAsAllowed();
- } else {
- return false;
- }
- }
-
- protected int[] loadSplitterPosition() {
- int[] sizes = new int[3];
- try {
- IEditorInput input = getEditorInput();
- if (!(input instanceof IFileEditorInput))
- return null;
-
- IFile file = ((IFileEditorInput) input).getFile();
- String s = file.getPersistentProperty(SPLITTER_POSITION_KEY1);
- if (s != null) {
- sizes[0] = Integer.parseInt(s);
- } else
- return null;
-
- s = file.getPersistentProperty(SPLITTER_POSITION_KEY2);
- if (s != null) {
- sizes[1] = Integer.parseInt(s);
- } else
- return null;
-
- s = file.getPersistentProperty(SPLITTER_POSITION_KEY3);
- if (s != null) {
- sizes[2] = Integer.parseInt(s);
- } else
- return null;
-
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- return null;
- }
- return sizes;
- }
-
- protected void saveSplitterPosition(int[] weights) {
- IEditorInput input = getEditorInput();
- if (!(input instanceof IFileEditorInput))
- return;
- IFile file = ((IFileEditorInput) input).getFile();
- try {
- String s = String.valueOf(weights[0]);
- file.setPersistentProperty(SPLITTER_POSITION_KEY1, s);
- s = String.valueOf(weights[1]);
- file.setPersistentProperty(SPLITTER_POSITION_KEY2, s);
- s = String.valueOf(weights[2]);
- file.setPersistentProperty(SPLITTER_POSITION_KEY3, s);
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- }
- }
-
- Composite sourceContent = null;
- Composite visualContent = null;
-
- public void setVisualMode(int type) {
- String showSelectionBar = VpePreference.SHOW_SELECTION_TAG_BAR
- .getValue();
- switch (type) {
- case VISUALSOURCE_MODE:
- selectionBar.showBar(showSelectionBar);
- if (sourceContent != null)
- sourceContent.setVisible(true);
- if (visualContent != null)
- visualContent.setVisible(true);
- if (previewContent != null) {
- previewContent.setVisible(false);
- }
- break;
-
- case VISUAL_MODE:
- selectionBar.showBar(showSelectionBar);
- if (sourceContent != null)
- sourceContent.setVisible(false);
- if (visualContent != null)
- visualContent.setVisible(true);
- if (previewContent != null) {
- previewContent.setVisible(false);
- }
- break;
-
- case SOURCE_MODE:
- selectionBar.showBar(showSelectionBar);
- if (sourceContent != null) {
- sourceContent.setVisible(true);
-
- //Added by Max Areshkau
- //was fixed bug(border which drawed by iflasher doesn't hide on MACOS when we swith
- // to souce view)
-// if(Platform.getOS().equals(Platform.OS_MACOSX)&&controller!=null) {
-//
-// visualEditor.getController().visualRefresh();
-// }
- }
- if (visualContent != null)
- visualContent.setVisible(false);
- if (previewContent != null) {
- previewContent.setVisible(false);
- }
- break;
-
- case PREVIEW_MODE:
- if (selectionBar != null) {
- selectionBar.showBar("no");
- }
- if (sourceContent != null) {
- sourceContent.setVisible(false);
- }
-
- if (visualContent != null) {
- visualContent.setVisible(false);
- }
-
- if (previewContent != null) {
- previewWebBrowser.rebuildDom();
- previewContent.setVisible(true);
- }
- break;
- }
- container.layout();
- if (visualMode == SOURCE_MODE && type != SOURCE_MODE) {
- visualMode = type;
- if (visualEditor.getController() != null) {
- visualEditor.getController().visualRefresh();
- if(type!=PREVIEW_MODE) {
- visualEditor.getController().sourceSelectionChanged();
- }
- }
- }
- visualMode = type;
- }
-
- public int getVisualMode() {
- return visualMode;
- }
-
- public void createPartControl(Composite parent) {
- controlCount++;
- if (controlCount > 1)
- return;
- // //////////////////////////////////////////////////////////////
-
- Composite cmpEdTl = new Composite(parent, SWT.NONE);
- GridLayout layoutEdTl = new GridLayout(1, false);
- layoutEdTl.verticalSpacing = 0;
- layoutEdTl.marginHeight = 0;
- layoutEdTl.marginBottom = 3;
- layoutEdTl.marginWidth = 0;
- cmpEdTl.setLayout(layoutEdTl);
- cmpEdTl.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Composite cmpEd = new Composite(cmpEdTl, SWT.NATIVE);
- GridLayout layoutEd = new GridLayout(1, false);
- layoutEd.marginBottom = 0;
- layoutEd.marginHeight = 1;
- layoutEd.marginWidth = 0;
- layoutEd.marginRight = 0;
- layoutEd.marginLeft = 1;
- layoutEd.verticalSpacing = 0;
- layoutEd.horizontalSpacing = 0;
- cmpEd.setLayout(layoutEd);
- cmpEd.setLayoutData(new GridData(GridData.FILL_BOTH));
- // /////////////////////////////////////////////////////////////////
- container = new SashForm(cmpEd, SWT.VERTICAL);
- container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- sourceContent = new Composite(container, SWT.NONE);
- sourceContent.setLayout(new FillLayout());
- visualContent = new Composite(container, SWT.NONE);
- visualContent.setLayout(new FillLayout());
-
- // Create a preview content
- previewContent = new Composite(container, SWT.NONE);
- previewContent.setLayout(new FillLayout());
-
- // ////////////////////////////////////////////////////
-
- selectionBar.createToolBarComposite(cmpEdTl, true);
- // ///////////////////////////////////////////////////
- if (sourceEditor == null)
- sourceEditor = new StructuredTextEditor() {
- public void safelySanityCheckState(IEditorInput input) {
- super.safelySanityCheckState(input);
- }
- };
- int[] weights = loadSplitterPosition();
- if (weights != null)
- container.setWeights(weights);
- container.addWeightsChangeListener(new PropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- saveSplitterPosition(container.getWeights());
- }
- });
- parent.addControlListener(new ControlListener() {
- public void controlMoved(ControlEvent event) {
-
- }
-
- public void controlResized(ControlEvent event) {
- container.layout();
- }
- });
- visualEditor = new MozillaEditor();
- try {
- visualEditor.init(getEditorSite(), getEditorInput());
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- }
-
- previewWebBrowser = new MozillaPreview(this, sourceEditor);
- try {
- previewWebBrowser.init(getEditorSite(), getEditorInput());
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- }
-
- try {
- sourceEditor.addPropertyListener(new IPropertyListener() {
- public void propertyChanged(Object source, int propId) {
- if (propId == IWorkbenchPartConstants.PROP_TITLE) {
- VpeEditorPart.this.setPartName(sourceEditor.getTitle());
- }
- VpeEditorPart.this.firePropertyChange(propId);
- }
- });
- sourceEditor.init(getEditorSite(), getEditorInput());
-
- if (sourceContent != null) {
- sourceEditor.createPartControl(sourceContent);
- }
- if (visualEditor != null) {
- visualEditor
- .setEditorLoadWindowListener(new EditorLoadWindowListener() {
- public void load() {
- visualEditor.setEditorLoadWindowListener(null);
- visualEditor.setController(new VpeController(
- VpeEditorPart.this));
- selectionBar.setVpeController(visualEditor.getController());
- visualEditor.getController().setSelectionBarController(selectionBar);
- try {
- visualEditor.getController().init(sourceEditor, visualEditor);
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- }
- }
- });
- visualEditor.createPartControl(visualContent);
- }
-
- if (previewWebBrowser != null) {
- previewWebBrowser
- .setEditorLoadWindowListener(new EditorLoadWindowListener() {
- public void load() {
- previewWebBrowser
- .setEditorLoadWindowListener(null);
- previewWebBrowser.buildDom();
- }
- });
- previewWebBrowser.createPartControl(previewContent);
- }
-
- activeEditor = sourceEditor;
-
- sourceContent.addListener(SWT.Activate, new Listener() {
- public void handleEvent(Event event) {
- if (event.type == SWT.Activate) {
- if (activeEditor != sourceEditor) {
- activeEditor = sourceEditor;
- setFocus();
- }
- }
- }
- });
-
- visualContent.addListener(SWT.Activate, new Listener() {
- public void handleEvent(Event event) {
- if (event.type == SWT.Activate) {
- if (visualEditor != null
- && activeEditor != visualEditor) {
- activeEditor = visualEditor;
- setFocus();
- }
- }
- }
- });
-
- previewContent.addListener(SWT.Activate, new Listener() {
- public void handleEvent(Event event) {
- if (event.type == SWT.Activate) {
- if (previewWebBrowser != null
- && activeEditor != previewWebBrowser) {
- activeEditor = previewWebBrowser;
- setFocus();
- }
- }
- }
- });
-
- IWorkbenchWindow window = getSite().getWorkbenchWindow();
- window.getPartService().addPartListener(activationListener);
- window.getShell().addShellListener(activationListener);
-
- } catch (Exception e) {
- VpePlugin.reportProblem(e);
- }
- // setVisualMode(visualMode);
- // ///////////////////////////////////////
- // ///// Add preference listener
- optionsObject = ModelUtilities.getPreferenceModel().getByPath(
- VpePreference.EDITOR_PATH);
- listener = new XModelTreeListener() {
-
- public void nodeChanged(XModelTreeEvent event) {
- String showSelectionBar = VpePreference.SHOW_SELECTION_TAG_BAR
- .getValue();
- selectionBar.showBar(showSelectionBar);
- }
-
- public void structureChanged(XModelTreeEvent event) {
- }
-
- };
- optionsObject.getModel().addModelTreeListener(listener);
- // ///////////////////////////////////////
- cmpEd.layout();
- }
-
- public void setFocus() {
- if (activeEditor != null) {
- activeEditor.setFocus();
- }
- }
-
- public void dispose() {
- super.dispose();
- if (optionsObject != null) {
- optionsObject.getModel().removeModelTreeListener(listener);
- }
- if (activationListener != null) {
- IWorkbenchWindow window = getSite().getWorkbenchWindow();
- window.getPartService().removePartListener(activationListener);
- Shell shell = window.getShell();
- if (shell != null && !shell.isDisposed())
- shell.removeShellListener(activationListener);
- activationListener = null;
- }
- // editor will disposed as part of multipart editor
- if (sourceEditor != null) {
- sourceEditor.dispose();
- sourceEditor = null;
- }
-
- if (visualEditor != null) {
- visualEditor.dispose();
- visualEditor = null;
- }
-
- if (previewContent != null) {
- previewContent.dispose();
- previewContent = null;
- }
-
- if (selectionBar != null) {
- selectionBar.dispose();
- selectionBar = null;
- }
- }
-
- public Object getAdapter(Class adapter) {
- if (sourceEditor != null) {
- return sourceEditor.getAdapter(adapter);
- } else {
- return null;
- }
- }
-
- private class ActivationListener extends ShellAdapter implements
- IPartListener {
- private IWorkbenchPart fActivePart;
- private boolean fIsHandlingActivation = false;
-
- public void partActivated(IWorkbenchPart part) {
- fActivePart = part;
- handleActivation();
- }
-
- public void partBroughtToTop(IWorkbenchPart part) {
- }
-
- public void partClosed(IWorkbenchPart part) {
- }
-
- public void partDeactivated(IWorkbenchPart part) {
- fActivePart = null;
- }
-
- public void partOpened(IWorkbenchPart part) {
- }
-
- public void shellActivated(ShellEvent e) {
- e.widget.getDisplay().asyncExec(new Runnable() {
- public void run() {
- handleActivation();
- }
- });
- }
-
- private void handleActivation() {
- if (fIsHandlingActivation)
- return;
-
- if (fActivePart == multiPageEditor) {
- fIsHandlingActivation = true;
- try {
- if (sourceEditor != null) {
- if (visualEditor.getController() != null) {
- visualEditor.getController().refreshTemplates();
- }
- sourceEditor.safelySanityCheckState(getEditorInput());
- }
- } finally {
- fIsHandlingActivation = false;
- }
- }
- }
- }
-
- public VpeController getController() {
- return visualEditor.getController();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.QualifiedName;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ControlEvent;
+import org.eclipse.swt.events.ControlListener;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.ShellAdapter;
+import org.eclipse.swt.events.ShellEvent;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IPartListener;
+import org.eclipse.ui.IPropertyListener;
+import org.eclipse.ui.IReusableEditor;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.IWorkbenchPartConstants;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.EditorPart;
+import org.eclipse.ui.texteditor.IDocumentProvider;
+import org.eclipse.ui.texteditor.IStatusField;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorExtension;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.event.XModelTreeEvent;
+import org.jboss.tools.common.model.event.XModelTreeListener;
+import org.jboss.tools.common.model.ui.util.ModelUtilities;
+import org.jboss.tools.jst.jsp.editor.IVisualEditor;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.mozilla.EditorLoadWindowListener;
+import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
+import org.jboss.tools.vpe.editor.mozilla.MozillaPreview;
+import org.jboss.tools.vpe.editor.xpl.SashForm;
+import org.jboss.tools.vpe.selbar.SelectionBar;
+
+public class VpeEditorPart extends EditorPart implements ITextEditor,
+ ITextEditorExtension, IReusableEditor, IVisualEditor {
+ private SashForm container;
+ private StructuredTextEditor sourceEditor = null;
+ private MozillaEditor visualEditor;
+ private IEditorPart activeEditor;
+ private XModelTreeListener listener;
+ XModelObject optionsObject;
+ private SelectionBar selectionBar = new SelectionBar();
+ private ActivationListener activationListener = new ActivationListener();
+ private int visualMode = 0;
+ private EditorPart multiPageEditor;
+ private static final QualifiedName SPLITTER_POSITION_KEY1 = new QualifiedName(
+ "", "splitter_position1");
+ private static final QualifiedName SPLITTER_POSITION_KEY2 = new QualifiedName(
+ "", "splitter_position2");
+ private static final QualifiedName SPLITTER_POSITION_KEY3 = new QualifiedName(
+ "", "splitter_position3");
+
+ private int controlCount = 0;
+
+ /** default web-browser */
+ private MozillaPreview previewWebBrowser = null;
+
+ /** preview content */
+ private Composite previewContent = null;
+
+ public StructuredTextEditor getSourceEditor() {
+ return sourceEditor;
+ }
+
+ // returns JSPMultipageEditor for closing by ctrl+F4 and ctrl+shift+F4 keys
+ public EditorPart getParentEditor() {
+ return multiPageEditor;
+ }
+
+ public void close(boolean save) {
+ if (sourceEditor != null)
+ sourceEditor.close(save);
+ }
+
+ public void doRevertToSaved() {
+ if (sourceEditor != null)
+ sourceEditor.doRevertToSaved();
+ }
+
+ public IDocumentProvider getDocumentProvider() {
+ if (sourceEditor != null)
+ return sourceEditor.getDocumentProvider();
+ else {
+ return null;
+ }
+ }
+
+ public IRegion getHighlightRange() {
+ if (sourceEditor != null)
+ return sourceEditor.getHighlightRange();
+ else {
+ return null;
+ }
+ }
+
+ public ISelectionProvider getSelectionProvider() {
+ if (sourceEditor != null)
+ return sourceEditor.getSelectionProvider();
+ else {
+ return null;
+ }
+ }
+
+ public boolean isEditable() {
+ if (sourceEditor != null)
+ return sourceEditor.isEditable();
+ else {
+ return false;
+ }
+ }
+
+ public void removeActionActivationCode(String actionId) {
+ if (sourceEditor != null)
+ sourceEditor.removeActionActivationCode(actionId);
+ }
+
+ public void resetHighlightRange() {
+ if (sourceEditor != null)
+ sourceEditor.resetHighlightRange();
+ }
+
+ public void selectAndReveal(int offset, int length) {
+ if (sourceEditor != null)
+ sourceEditor.selectAndReveal(offset, length);
+ }
+
+ public void setAction(String actionID, IAction action) {
+ if (sourceEditor != null)
+ sourceEditor.setAction(actionID, action);
+ }
+
+ public void setActionActivationCode(String actionId,
+ char activationCharacter, int activationKeyCode,
+ int activationStateMask) {
+ if (sourceEditor != null)
+ sourceEditor.setActionActivationCode(actionId, activationCharacter,
+ activationKeyCode, activationStateMask);
+ }
+
+ public void setHighlightRange(int offset, int length, boolean moveCursor) {
+ if (sourceEditor != null)
+ sourceEditor.setHighlightRange(offset, length, moveCursor);
+ }
+
+ public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
+ if (sourceEditor != null)
+ sourceEditor.showHighlightRangeOnly(showHighlightRangeOnly);
+ }
+
+ public boolean showsHighlightRangeOnly() {
+ if (sourceEditor != null)
+ return sourceEditor.showsHighlightRangeOnly();
+ else {
+ return false;
+ }
+ }
+
+ public void addRulerContextMenuListener(IMenuListener listener) {
+ if (sourceEditor != null)
+ sourceEditor.addRulerContextMenuListener(listener);
+ }
+
+ public boolean isEditorInputReadOnly() {
+ if (sourceEditor != null)
+ return sourceEditor.isEditorInputReadOnly();
+ else {
+ return false;
+ }
+ }
+
+ public void removeRulerContextMenuListener(IMenuListener listener) {
+ if (sourceEditor != null)
+ sourceEditor.removeRulerContextMenuListener(listener);
+ }
+
+ public void setStatusField(IStatusField field, String category) {
+ if (visualMode == VISUAL_MODE) {
+ if (field != null) {
+ field.setImage(null);
+ field.setText(null);
+ }
+ } else if (sourceEditor != null)
+ sourceEditor.setStatusField(field, category);
+ }
+
+ public VpeEditorPart(EditorPart multiPageEditor,
+ StructuredTextEditor textEditor, boolean visualMode) {
+ sourceEditor = textEditor;
+ // this.visualMode = visualMode;
+ this.multiPageEditor = multiPageEditor;
+ }
+
+ public IAction getAction(String actionID) {
+ return sourceEditor.getAction(actionID);
+ }
+
+ public VpeEditorPart() {
+ }
+
+ public void doSave(IProgressMonitor monitor) {
+ if (sourceEditor != null) {
+ sourceEditor.doSave(monitor);
+ }
+ }
+
+ public void doSaveAs() {
+ if (sourceEditor != null) {
+ sourceEditor.doSaveAs();
+ setInput(sourceEditor.getEditorInput());
+ }
+ }
+
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ setSite(site);
+ setInput(input);
+ }
+
+ public void setInput(IEditorInput input) {
+ super.setInput(input);
+ if (visualEditor != null && visualEditor.getEditorInput() != null
+ && visualEditor.getEditorInput() != getEditorInput()) {
+ visualEditor.setInput(input);
+ }
+ }
+
+ public boolean isDirty() {
+ if (sourceEditor != null) {
+ return sourceEditor.isDirty();
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isSaveAsAllowed() {
+ if (sourceEditor != null) {
+ return sourceEditor.isSaveAsAllowed();
+ } else {
+ return false;
+ }
+ }
+
+ protected int[] loadSplitterPosition() {
+ int[] sizes = new int[3];
+ try {
+ IEditorInput input = getEditorInput();
+ if (!(input instanceof IFileEditorInput))
+ return null;
+
+ IFile file = ((IFileEditorInput) input).getFile();
+ String s = file.getPersistentProperty(SPLITTER_POSITION_KEY1);
+ if (s != null) {
+ sizes[0] = Integer.parseInt(s);
+ } else
+ return null;
+
+ s = file.getPersistentProperty(SPLITTER_POSITION_KEY2);
+ if (s != null) {
+ sizes[1] = Integer.parseInt(s);
+ } else
+ return null;
+
+ s = file.getPersistentProperty(SPLITTER_POSITION_KEY3);
+ if (s != null) {
+ sizes[2] = Integer.parseInt(s);
+ } else
+ return null;
+
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ return null;
+ }
+ return sizes;
+ }
+
+ protected void saveSplitterPosition(int[] weights) {
+ IEditorInput input = getEditorInput();
+ if (!(input instanceof IFileEditorInput))
+ return;
+ IFile file = ((IFileEditorInput) input).getFile();
+ try {
+ String s = String.valueOf(weights[0]);
+ file.setPersistentProperty(SPLITTER_POSITION_KEY1, s);
+ s = String.valueOf(weights[1]);
+ file.setPersistentProperty(SPLITTER_POSITION_KEY2, s);
+ s = String.valueOf(weights[2]);
+ file.setPersistentProperty(SPLITTER_POSITION_KEY3, s);
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+ }
+
+ Composite sourceContent = null;
+ Composite visualContent = null;
+
+ public void setVisualMode(int type) {
+ String showSelectionBar = VpePreference.SHOW_SELECTION_TAG_BAR
+ .getValue();
+ switch (type) {
+ case VISUALSOURCE_MODE:
+ selectionBar.showBar(showSelectionBar);
+ if (sourceContent != null)
+ sourceContent.setVisible(true);
+ if (visualContent != null)
+ visualContent.setVisible(true);
+ if (previewContent != null) {
+ previewContent.setVisible(false);
+ }
+ break;
+
+ case VISUAL_MODE:
+ selectionBar.showBar(showSelectionBar);
+ if (sourceContent != null)
+ sourceContent.setVisible(false);
+ if (visualContent != null)
+ visualContent.setVisible(true);
+ if (previewContent != null) {
+ previewContent.setVisible(false);
+ }
+ break;
+
+ case SOURCE_MODE:
+ selectionBar.showBar(showSelectionBar);
+ if (sourceContent != null) {
+ sourceContent.setVisible(true);
+
+ //Added by Max Areshkau
+ //was fixed bug(border which drawed by iflasher doesn't hide on MACOS when we swith
+ // to souce view)
+// if(Platform.getOS().equals(Platform.OS_MACOSX)&&controller!=null) {
+//
+// visualEditor.getController().visualRefresh();
+// }
+ }
+ if (visualContent != null)
+ visualContent.setVisible(false);
+ if (previewContent != null) {
+ previewContent.setVisible(false);
+ }
+ break;
+
+ case PREVIEW_MODE:
+ if (selectionBar != null) {
+ selectionBar.showBar("no");
+ }
+ if (sourceContent != null) {
+ sourceContent.setVisible(false);
+ }
+
+ if (visualContent != null) {
+ visualContent.setVisible(false);
+ }
+
+ if (previewContent != null) {
+ previewWebBrowser.rebuildDom();
+ previewContent.setVisible(true);
+ }
+ break;
+ }
+ container.layout();
+ if (visualMode == SOURCE_MODE && type != SOURCE_MODE) {
+ visualMode = type;
+ if (visualEditor != null && visualEditor.getController() != null) {
+ visualEditor.getController().visualRefresh();
+ if(type!=PREVIEW_MODE) {
+ visualEditor.getController().sourceSelectionChanged();
+ }
+ }
+ }
+ visualMode = type;
+ }
+
+ public int getVisualMode() {
+ return visualMode;
+ }
+
+ public void createPartControl(final Composite parent) {
+ controlCount++;
+ if (controlCount > 1)
+ return;
+ // //////////////////////////////////////////////////////////////
+
+ Composite cmpEdTl = new Composite(parent, SWT.NONE);
+ GridLayout layoutEdTl = new GridLayout(1, false);
+ layoutEdTl.verticalSpacing = 0;
+ layoutEdTl.marginHeight = 0;
+ layoutEdTl.marginBottom = 3;
+ layoutEdTl.marginWidth = 0;
+ cmpEdTl.setLayout(layoutEdTl);
+ cmpEdTl.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Composite cmpEd = new Composite(cmpEdTl, SWT.NATIVE);
+ GridLayout layoutEd = new GridLayout(1, false);
+ layoutEd.marginBottom = 0;
+ layoutEd.marginHeight = 1;
+ layoutEd.marginWidth = 0;
+ layoutEd.marginRight = 0;
+ layoutEd.marginLeft = 1;
+ layoutEd.verticalSpacing = 0;
+ layoutEd.horizontalSpacing = 0;
+ cmpEd.setLayout(layoutEd);
+ cmpEd.setLayoutData(new GridData(GridData.FILL_BOTH));
+ // /////////////////////////////////////////////////////////////////
+ container = new SashForm(cmpEd, SWT.VERTICAL);
+ container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ sourceContent = new Composite(container, SWT.NONE);
+ sourceContent.setLayout(new FillLayout());
+ visualContent = new Composite(container, SWT.NONE);
+ visualContent.setLayout(new FillLayout());
+
+ // Create a preview content
+ previewContent = new Composite(container, SWT.NONE);
+ previewContent.setLayout(new FillLayout());
+
+ // ////////////////////////////////////////////////////
+
+ selectionBar.createToolBarComposite(cmpEdTl, true);
+ // ///////////////////////////////////////////////////
+ if (sourceEditor == null)
+ sourceEditor = new StructuredTextEditor() {
+ public void safelySanityCheckState(IEditorInput input) {
+ super.safelySanityCheckState(input);
+ }
+ };
+ int[] weights = loadSplitterPosition();
+ if (weights != null)
+ container.setWeights(weights);
+ final PropertyChangeListener weightsChangeListener = new PropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ saveSplitterPosition(container.getWeights());
+ }
+ };
+ container.addWeightsChangeListener(weightsChangeListener);
+ container.addDisposeListener(new DisposeListener() {
+
+ public void widgetDisposed(DisposeEvent e) {
+ container.removeWeightsChangeListener(weightsChangeListener);
+ }
+
+ });
+ final ControlListener controlListener = new ControlListener() {
+ public void controlMoved(ControlEvent event) {
+
+ }
+
+ public void controlResized(ControlEvent event) {
+ container.layout();
+ }
+ };
+ parent.addControlListener(controlListener);
+ parent.addDisposeListener(new DisposeListener() {
+
+ public void widgetDisposed(DisposeEvent e) {
+ parent.removeControlListener(controlListener);
+ }
+
+ });
+ //createVisualEditor();
+
+ //createPreviewBrowser();
+
+ try {
+ sourceEditor.addPropertyListener(new IPropertyListener() {
+ public void propertyChanged(Object source, int propId) {
+ if (propId == IWorkbenchPartConstants.PROP_TITLE) {
+ VpeEditorPart.this.setPartName(sourceEditor.getTitle());
+ }
+ VpeEditorPart.this.firePropertyChange(propId);
+ }
+ });
+ sourceEditor.init(getEditorSite(), getEditorInput());
+
+ if (sourceContent != null) {
+ sourceEditor.createPartControl(sourceContent);
+ }
+
+
+ /*if (previewWebBrowser != null) {
+ previewWebBrowser
+ .setEditorLoadWindowListener(new EditorLoadWindowListener() {
+ public void load() {
+ previewWebBrowser
+ .setEditorLoadWindowListener(null);
+ previewWebBrowser.buildDom();
+ }
+ });
+ previewWebBrowser.createPartControl(previewContent);
+ }
+*/
+ activeEditor = sourceEditor;
+
+ sourceContent.addListener(SWT.Activate, new Listener() {
+ public void handleEvent(Event event) {
+ if (event.type == SWT.Activate) {
+ if (activeEditor != sourceEditor) {
+ activeEditor = sourceEditor;
+ setFocus();
+ }
+ }
+ }
+ });
+
+ visualContent.addListener(SWT.Activate, new Listener() {
+ public void handleEvent(Event event) {
+ if (event.type == SWT.Activate) {
+ if (visualEditor != null
+ && activeEditor != visualEditor) {
+ activeEditor = visualEditor;
+ setFocus();
+ }
+ }
+ }
+ });
+
+ previewContent.addListener(SWT.Activate, new Listener() {
+ public void handleEvent(Event event) {
+ if (event.type == SWT.Activate) {
+ if (previewWebBrowser != null
+ && activeEditor != previewWebBrowser) {
+ activeEditor = previewWebBrowser;
+ setFocus();
+ }
+ }
+ }
+ });
+
+ IWorkbenchWindow window = getSite().getWorkbenchWindow();
+ window.getPartService().addPartListener(activationListener);
+ window.getShell().addShellListener(activationListener);
+
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ }
+ // setVisualMode(visualMode);
+ // ///////////////////////////////////////
+ // ///// Add preference listener
+ optionsObject = ModelUtilities.getPreferenceModel().getByPath(
+ VpePreference.EDITOR_PATH);
+ listener = new XModelTreeListener() {
+
+ public void nodeChanged(XModelTreeEvent event) {
+ String showSelectionBar = VpePreference.SHOW_SELECTION_TAG_BAR
+ .getValue();
+ selectionBar.showBar(showSelectionBar);
+ }
+
+ public void structureChanged(XModelTreeEvent event) {
+ }
+
+ };
+ optionsObject.getModel().addModelTreeListener(listener);
+ // ///////////////////////////////////////
+ cmpEd.layout();
+ }
+
+ public void createVisualEditor() {
+ visualEditor = new MozillaEditor();
+ try {
+ visualEditor.init(getEditorSite(), getEditorInput());
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ }
+ if (visualEditor != null) {
+ visualEditor
+ .setEditorLoadWindowListener(new EditorLoadWindowListener() {
+ public void load() {
+ visualEditor.setEditorLoadWindowListener(null);
+ visualEditor.setController(new VpeController(
+ VpeEditorPart.this));
+ selectionBar.setVpeController(visualEditor.getController());
+ visualEditor.getController().setSelectionBarController(selectionBar);
+ try {
+ visualEditor.getController().init(sourceEditor, visualEditor);
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ }
+ }
+ });
+ visualEditor.createPartControl(visualContent);
+ }
+ }
+
+ public void createPreviewBrowser() {
+ previewWebBrowser = new MozillaPreview(this, sourceEditor);
+ try {
+ previewWebBrowser.init(getEditorSite(), getEditorInput());
+ previewWebBrowser
+ .setEditorLoadWindowListener(new EditorLoadWindowListener() {
+ public void load() {
+ previewWebBrowser.setEditorLoadWindowListener(null);
+ previewWebBrowser.buildDom();
+ }
+ });
+ previewWebBrowser.createPartControl(previewContent);
+ } catch (Exception e) {
+ VpePlugin.reportProblem(e);
+ }
+ }
+
+ public void setFocus() {
+ if (activeEditor != null) {
+ activeEditor.setFocus();
+ }
+ }
+
+ public void dispose() {
+ if (optionsObject != null) {
+ optionsObject.getModel().removeModelTreeListener(listener);
+ listener=null;
+ }
+ if (activationListener != null) {
+ IWorkbenchWindow window = getSite().getWorkbenchWindow();
+ window.getPartService().removePartListener(activationListener);
+ Shell shell = window.getShell();
+ if (shell != null && !shell.isDisposed())
+ shell.removeShellListener(activationListener);
+ activationListener = null;
+ }
+ // editor will disposed as part of multipart editor
+ if (sourceEditor != null) {
+ sourceEditor.dispose();
+ sourceEditor = null;
+ }
+
+ if (visualEditor != null) {
+ visualEditor.dispose();
+ visualEditor = null;
+ }
+
+ if (previewWebBrowser != null) {
+ previewWebBrowser.dispose();
+ previewWebBrowser=null;
+ }
+ if (previewContent != null) {
+ previewContent.dispose();
+ previewContent = null;
+ }
+
+ if (selectionBar != null) {
+ selectionBar.dispose();
+ selectionBar = null;
+ }
+ activeEditor = null;
+ super.dispose();
+ }
+
+ public Object getAdapter(Class adapter) {
+ if (sourceEditor != null) {
+ return sourceEditor.getAdapter(adapter);
+ } else {
+ return null;
+ }
+ }
+
+ private class ActivationListener extends ShellAdapter implements
+ IPartListener {
+ private IWorkbenchPart fActivePart;
+ private boolean fIsHandlingActivation = false;
+
+ public void partActivated(IWorkbenchPart part) {
+ fActivePart = part;
+ handleActivation();
+ }
+
+ public void partBroughtToTop(IWorkbenchPart part) {
+ }
+
+ public void partClosed(IWorkbenchPart part) {
+ }
+
+ public void partDeactivated(IWorkbenchPart part) {
+ fActivePart = null;
+ }
+
+ public void partOpened(IWorkbenchPart part) {
+ }
+
+ public void shellActivated(ShellEvent e) {
+ e.widget.getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ handleActivation();
+ }
+ });
+ }
+
+ private void handleActivation() {
+ if (fIsHandlingActivation)
+ return;
+
+ if (fActivePart == multiPageEditor) {
+ fIsHandlingActivation = true;
+ try {
+ if (sourceEditor != null) {
+ if (visualEditor != null)
+ if (visualEditor.getController() != null) {
+ visualEditor.getController().refreshTemplates();
+ }
+ sourceEditor.safelySanityCheckState(getEditorInput());
+ }
+ } finally {
+ fIsHandlingActivation = false;
+ }
+ }
+ }
+ }
+
+ public VpeController getController() {
+ if (visualEditor == null)
+ return null;
+ return visualEditor.getController();
+ }
+
+ public MozillaPreview getPreviewWebBrowser() {
+ return previewWebBrowser;
+ }
+
+ public MozillaEditor getVisualEditor() {
+ return visualEditor;
+ }
+
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeSourceDomBuilder.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeSourceDomBuilder.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeSourceDomBuilder.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,396 +1,402 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jst.jsp.core.internal.domdocument.TextImplForJSP;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.context.VpePageContext;
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
-import org.jboss.tools.vpe.editor.selection.VpeSelectionHelper;
-import org.jboss.tools.vpe.editor.template.VpeTemplate;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-import org.jboss.tools.vpe.editor.util.TextUtil;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.mozilla.interfaces.nsIDOMNodeList;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class VpeSourceDomBuilder extends VpeDomBuilder {
- private StructuredTextViewer structuredTextViewer;
- private IContentOutlinePage outline;
- private ISelectionProvider selectionManager;
- IDOMModel model;
- private Document sourceDocument;
- private VpePageContext pageContext;
- private StructuredTextEditor sourceEditor;
-
- public VpeSourceDomBuilder(VpeDomMapping domMapping, INodeAdapter sorceAdapter, VpeTemplateManager templateManager, StructuredTextEditor sourceEditor, VpePageContext pageContext) {
- super(domMapping, sorceAdapter, templateManager);
- this.sourceEditor = sourceEditor;
- structuredTextViewer = sourceEditor.getTextViewer();
- outline = (IContentOutlinePage)sourceEditor.getAdapter(IContentOutlinePage.class);
-// selectionManager = sourceEditor.getViewerSelectionManager();
- selectionManager = sourceEditor.getSelectionProvider();
- model = (IDOMModel)sourceEditor.getModel();
- if (model != null) {
- sourceDocument = model.getDocument();
- }
- this.pageContext = pageContext;
- }
-
- public void addNode(nsIDOMNode visualNode) {
- nsIDOMNode visualContainer = visualNode.getParentNode();
- Node sourceContainer = domMapping.getSourceNode(visualContainer);
-
- if (sourceContainer != null && (sourceContainer.getNodeType() == Node.ELEMENT_NODE || sourceContainer.getNodeType() == Node.DOCUMENT_NODE)) {
- nsIDOMNode visualNextNode = visualNode.getNextSibling();
- Node sourceNextNode = domMapping.getSourceNode(visualNextNode);
- addNode(visualNode, sourceNextNode, sourceContainer);
- }
- }
-
- public void removeNode(nsIDOMNode visualNode) {
- Node sourceNode = domMapping.getSourceNode(visualNode);
- if (sourceNode != null) {
- Node sourceContainer = sourceNode.getParentNode();
- if (sourceContainer != null) {
- sourceContainer.removeChild(sourceNode);
- }
- } else {
- sourceNode = domMapping.getNearSourceNode(visualNode);
- if (sourceNode != null) {
- if (sourceNode.getNodeType() == Node.COMMENT_NODE) {
- sourceNode.setNodeValue("");
- }
- }
- }
- }
-
- public void setText(nsIDOMNode visualText) {
- Node sourceText = domMapping.getSourceNode(visualText);
- if (sourceText != null) {
- sourceText.setNodeValue(TextUtil.sourceText(visualText.getNodeValue()));
- } else {
- nsIDOMNode visualParent = visualText.getParentNode();
- if (visualParent != null) {
- Node sourceParent = domMapping.getNearSourceNode(visualText);
- if (sourceParent != null) {
- if (sourceParent.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- template.setSourceAttributeValue(pageContext, (Element)sourceParent, elementMapping.getData());
- }
- } else if (sourceParent.getNodeType() == Node.COMMENT_NODE) {
- setComment(sourceParent, visualParent);
-// VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
-// if (elementMapping != null) {
-// VpeTemplate template = elementMapping.getTemplate();
-// template.setSourceCommentValue(pageContext, (Comment)sourceParent, elementMapping.getData());
-// }
- }
- }
- }
- }
- }
-
- public void setSelectedRange(Node sourceNode, int start, int length) {
-//glory
- structuredTextViewer.setSelectedRange(start, length);
- structuredTextViewer.revealRange(start, length);
-// ISelection selection = new StructuredSelection(sourceNode);
-// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
-// selectionManager.selectionChanged(event);
-// selectionManager.setSelection(new TextSelection(start, length));
- }
-
- public void setSelectChanged(Node sourceNode) {
-// structuredTextViewer.setSelectedRange(start, length);
-// structuredTextViewer.revealRange(start, length);
-
-//glory
-// ISelection selection = new StructuredSelection(sourceNode);
-// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
-// selectionManager.selectionChanged(event);
- if(sourceNode instanceof IDOMNode) {
- IDOMNode n = (IDOMNode)sourceNode;
- int start = n.getStartOffset();
- int length = n.getLength();
- selectionManager.setSelection(new TextSelection(start, length));
- }
- }
-
- void setSelectionAtDocumentEnd() {
- if (sourceDocument == null) return;
- int offset = ((IndexedRegion)sourceDocument).getEndOffset();
- structuredTextViewer.setSelectedRange(offset, 0);
- structuredTextViewer.revealRange(offset, 0);
- }
-
- public void setSelection(Node sourceNode, int offset, int length) {
- setSelection(sourceNode, offset, length, false);
- }
-
- void setSelection(Node sourceNode, int offset, int length, boolean innerFlag) {
- if (sourceNode != null) {
- int start = ((IndexedRegion)sourceNode).getStartOffset() + offset;
- if (innerFlag && offset == 0 && sourceNode instanceof ElementImpl) {
- ElementImpl element = (ElementImpl)sourceNode;
- if (element.isContainer()) {
- start = element.getStartEndOffset();
- length = 0;
- }
- } else if (sourceNode.getNodeType() == Node.COMMENT_NODE) {
- start += 4;
- }
-//glory
-// ISelection selection = new StructuredSelection(sourceNode);
-// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
-// selectionManager.selectionChanged(event);
- structuredTextViewer.setSelectedRange(start, length);
- structuredTextViewer.revealRange(start, length);
-// selectionManager.setSelection(new TextSelection(start, length));
- }
- }
-
- Node getSelectedNode() {
- List nodes = VpeSelectionHelper.getTextWidgetSelectedNodes(model, selectionManager);
- //selectionManager.getSelectedNodes();
- if (nodes != null && nodes.size() > 0) {
- return (Node)nodes.get(0);
- } else {
- return null;
- }
- }
-
- int getCaretPosition() {
-// return selectionManager.getCaretPosition();
- ITextViewer v = (sourceEditor == null) ? null : sourceEditor.getTextViewer();
- StyledText t = (v == null) ? null : v.getTextWidget();
- return (t == null) ? 0 : t.getCaretOffset();
- }
-
- private void addNode(nsIDOMNode visualNewNode, Node sourceNextNode, Node sourceContainer) {
- Node sourceNewNode = createNode(visualNewNode);
- if (sourceNewNode != null) {
- if (sourceNextNode == null) {
- sourceContainer.appendChild(sourceNewNode);
- } else {
- sourceContainer.insertBefore(sourceNewNode, sourceNextNode);
- }
- }
- }
-
- private Node createNode(nsIDOMNode visualNewNode) {
- if (sourceDocument != null) {
- switch (visualNewNode.getNodeType()) {
- case Node.ELEMENT_NODE:
- Element sourceNewElement = sourceDocument.createElement(visualNewNode.getNodeName());
- Set ifDependencySet = new HashSet();
- //VpeVisualDomBuilder visualBuildet =
- pageContext.getVisualBuilder();
- VpeTemplate template = templateManager.getTemplate(pageContext, sourceNewElement, ifDependencySet);
- registerNodes(new VpeElementMapping(sourceNewElement, (nsIDOMElement)visualNewNode, null, template, ifDependencySet, null));
- addChildren(visualNewNode, sourceNewElement);
- return sourceNewElement;
- case Node.TEXT_NODE:
- Node sourceTextNode = sourceDocument.createTextNode(visualNewNode.getNodeValue());
- registerNodes(new VpeNodeMapping(sourceTextNode, visualNewNode));
- return sourceTextNode;
- }
- }
- return null;
- }
-
- private void addChildren(nsIDOMNode visualContainer, Element sourceContainer) {
- nsIDOMNodeList visualNodes = visualContainer.getChildNodes();
- long len = visualNodes.getLength();
-
- for (long i = 0; i < len; i++) {
- nsIDOMNode visualNode = visualNodes.item(i);
- addNode(visualNode, null, sourceContainer);
- }
- }
-
- boolean openBundleEditors(nsIDOMNode visualNode) {
- Node sourceNode = domMapping.getNearSourceNode(visualNode);
- if (sourceNode != null && sourceNode.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceNode);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- template.openBundleEditors(pageContext, (Element)sourceNode, elementMapping.getData());
- }
- }
- return false;
- }
-
- boolean openIncludeEditor(nsIDOMNode visualNode) {
- Node sourceNode = domMapping.getNearSourceNode(visualNode);
- if (sourceNode != null && sourceNode.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceNode);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- template.openIncludeEditor(pageContext, (Element)sourceNode, elementMapping.getData());
- }
- }
- return false;
- }
-
- boolean isEmptyDocument() {
- if (sourceDocument == null) return true;
- boolean empty = false;
- NodeList sourceNodes = sourceDocument.getChildNodes();
- int len = sourceNodes.getLength();
- if (len == 0) {
- empty = true;
- } else if (len == 1) {
- Node sourceNode = sourceNodes.item(0);
- if (sourceNode.getNodeType() == Node.TEXT_NODE && sourceNode.getNodeValue().trim().length() == 0) {
- empty = true;
- }
- }
- return empty;
- }
-
- int getPosition(Node sourceNode, int offset, boolean innerFlag) {
- int start = 0;
- if (sourceNode != null) {
- start = ((IndexedRegion)sourceNode).getStartOffset() + offset;
- if (innerFlag && offset == 0 && sourceNode instanceof ElementImpl) {
- ElementImpl element = (ElementImpl)sourceNode;
- if (element.isContainer()) {
- start = element.getStartEndOffset();
- }
- }
- }
- return start;
- }
-
- void setAttributeSelection(nsIDOMNode visualText, int offset, int length) {
- nsIDOMNode visualParent = visualText.getParentNode();
- if (visualParent != null) {
- Node sourceParent = domMapping.getNearSourceNode(visualText);
- if (sourceParent != null) {
- if (sourceParent.getNodeType() == Node.ELEMENT_NODE) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- template.setSourceAttributeSelection(pageContext, (Element)sourceParent, offset, length, elementMapping.getData());
- }
- } else if (sourceParent.getNodeType() == Node.COMMENT_NODE) {
-// VpeVisualElementInfo info = domMapping.getVisualElementInfo(sourceParent);
-// if (info != null) {
-// info.setSourceCommentValue(pageContext, (Comment)sourceParent);
-// }
- //Added by Max Areshkau in scope of bug JBIDE-1209
- } else {
- try{
- IndexedRegion region = (IndexedRegion)sourceParent;
- String text = sourceParent.getNodeValue();
- int start= TextUtil.sourcePosition(text, visualText.getNodeValue(), offset);
- int end =TextUtil.sourcePosition(text, visualText.getNodeValue(), offset+length);
- offset=start;
- length=end-start;
- }catch(Exception ex){
- VpePlugin.reportProblem(ex);
- }
- setSelection(sourceParent, offset, length);
- }
- }
- }
- }
-
-// boolean
-
- public void setAttributeSelection(Attr sourceAttr, int offset, int length) {
- IDOMAttr xmlAttr = (IDOMAttr)sourceAttr;
- int start = xmlAttr.getValueRegionStartOffset() + offset;
- String value = xmlAttr.getValueRegionText();
- if (value.startsWith("\"") || value.startsWith("\'")) {
- start++;
- }
- int end = xmlAttr.getEndOffset();
- if (start > end) {
- start = end;
- }
- if (start + length > end) {
- length = end - start;
- }
-
-//glory
-// ISelection selection = new StructuredSelection(sourceAttr);
-// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
-// selectionManager.selectionChanged(event);
- structuredTextViewer.setSelectedRange(start, length);
- structuredTextViewer.revealRange(start, length);
-
-// selectionManager.setSelection(new TextSelection(start, length));
- }
-
- Point getOutputAttributesPositions(Element sourceElement) {
- VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceElement);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- if (template.isOutputAttributes()) {
- int start = ((IndexedRegion)sourceElement).getStartOffset();
- int end = ((IndexedRegion)sourceElement).getEndOffset();
- return new Point(start, end);
- }
- }
- return null;
- }
-
- Point getSelectionRange() {
- return sourceEditor.getTextViewer().getSelectedRange();
- }
-
- public void setComment(Node sourceComment, nsIDOMNode visualElement) {
- nsIDOMNodeList visualNodes = visualElement.getChildNodes();
- long len = visualNodes.getLength();
-
- if (len > 0) {
- nsIDOMNode visualText = visualNodes.item(0);
- sourceComment.setNodeValue(visualText.getNodeValue());
- }
- }
-
- public StructuredTextViewer getStructuredTextViewer() {
- return structuredTextViewer;
- }
-
- Document getSourceDocument() {
- return sourceDocument;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.TextSelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jst.jsp.core.internal.domdocument.TextImplForJSP;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
+import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
+import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.context.VpePageContext;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
+import org.jboss.tools.vpe.editor.selection.VpeSelectionHelper;
+import org.jboss.tools.vpe.editor.template.VpeTemplate;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.jboss.tools.vpe.editor.util.TextUtil;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.mozilla.interfaces.nsIDOMNodeList;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class VpeSourceDomBuilder extends VpeDomBuilder {
+ private StructuredTextViewer structuredTextViewer;
+ private IContentOutlinePage outline;
+ private ISelectionProvider selectionManager;
+ IDOMModel model;
+ private Document sourceDocument;
+ private VpePageContext pageContext;
+ private StructuredTextEditor sourceEditor;
+
+ public VpeSourceDomBuilder(VpeDomMapping domMapping, INodeAdapter sorceAdapter, VpeTemplateManager templateManager, StructuredTextEditor sourceEditor, VpePageContext pageContext) {
+ super(domMapping, sorceAdapter, templateManager);
+ this.sourceEditor = sourceEditor;
+ structuredTextViewer = sourceEditor.getTextViewer();
+ outline = (IContentOutlinePage)sourceEditor.getAdapter(IContentOutlinePage.class);
+// selectionManager = sourceEditor.getViewerSelectionManager();
+ selectionManager = sourceEditor.getSelectionProvider();
+ model = (IDOMModel)sourceEditor.getModel();
+ if (model != null) {
+ sourceDocument = model.getDocument();
+ }
+ this.pageContext = pageContext;
+ }
+
+ public void addNode(nsIDOMNode visualNode) {
+ nsIDOMNode visualContainer = visualNode.getParentNode();
+ Node sourceContainer = domMapping.getSourceNode(visualContainer);
+
+ if (sourceContainer != null && (sourceContainer.getNodeType() == Node.ELEMENT_NODE || sourceContainer.getNodeType() == Node.DOCUMENT_NODE)) {
+ nsIDOMNode visualNextNode = visualNode.getNextSibling();
+ Node sourceNextNode = domMapping.getSourceNode(visualNextNode);
+ addNode(visualNode, sourceNextNode, sourceContainer);
+ }
+ }
+
+ public void removeNode(nsIDOMNode visualNode) {
+ Node sourceNode = domMapping.getSourceNode(visualNode);
+ if (sourceNode != null) {
+ Node sourceContainer = sourceNode.getParentNode();
+ if (sourceContainer != null) {
+ sourceContainer.removeChild(sourceNode);
+ getSourceNodes().remove(sourceNode);
+ if (sourceNode instanceof INodeNotifier) {
+ ((INodeNotifier) sourceNode).removeAdapter(getSorceAdapter());
+ }
+ domMapping.remove(sourceNode);
+ }
+ } else {
+ sourceNode = domMapping.getNearSourceNode(visualNode);
+ if (sourceNode != null) {
+ if (sourceNode.getNodeType() == Node.COMMENT_NODE) {
+ sourceNode.setNodeValue("");
+ }
+ }
+ }
+ }
+
+ public void setText(nsIDOMNode visualText) {
+ Node sourceText = domMapping.getSourceNode(visualText);
+ if (sourceText != null) {
+ sourceText.setNodeValue(TextUtil.sourceText(visualText.getNodeValue()));
+ } else {
+ nsIDOMNode visualParent = visualText.getParentNode();
+ if (visualParent != null) {
+ Node sourceParent = domMapping.getNearSourceNode(visualText);
+ if (sourceParent != null) {
+ if (sourceParent.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ template.setSourceAttributeValue(pageContext, (Element)sourceParent, elementMapping.getData());
+ }
+ } else if (sourceParent.getNodeType() == Node.COMMENT_NODE) {
+ setComment(sourceParent, visualParent);
+// VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
+// if (elementMapping != null) {
+// VpeTemplate template = elementMapping.getTemplate();
+// template.setSourceCommentValue(pageContext, (Comment)sourceParent, elementMapping.getData());
+// }
+ }
+ }
+ }
+ }
+ }
+
+ public void setSelectedRange(Node sourceNode, int start, int length) {
+//glory
+ structuredTextViewer.setSelectedRange(start, length);
+ structuredTextViewer.revealRange(start, length);
+// ISelection selection = new StructuredSelection(sourceNode);
+// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
+// selectionManager.selectionChanged(event);
+// selectionManager.setSelection(new TextSelection(start, length));
+ }
+
+ public void setSelectChanged(Node sourceNode) {
+// structuredTextViewer.setSelectedRange(start, length);
+// structuredTextViewer.revealRange(start, length);
+
+//glory
+// ISelection selection = new StructuredSelection(sourceNode);
+// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
+// selectionManager.selectionChanged(event);
+ if(sourceNode instanceof IDOMNode) {
+ IDOMNode n = (IDOMNode)sourceNode;
+ int start = n.getStartOffset();
+ int length = n.getLength();
+ selectionManager.setSelection(new TextSelection(start, length));
+ }
+ }
+
+ void setSelectionAtDocumentEnd() {
+ if (sourceDocument == null) return;
+ int offset = ((IndexedRegion)sourceDocument).getEndOffset();
+ structuredTextViewer.setSelectedRange(offset, 0);
+ structuredTextViewer.revealRange(offset, 0);
+ }
+
+ public void setSelection(Node sourceNode, int offset, int length) {
+ setSelection(sourceNode, offset, length, false);
+ }
+
+ void setSelection(Node sourceNode, int offset, int length, boolean innerFlag) {
+ if (sourceNode != null) {
+ int start = ((IndexedRegion)sourceNode).getStartOffset() + offset;
+ if (innerFlag && offset == 0 && sourceNode instanceof ElementImpl) {
+ ElementImpl element = (ElementImpl)sourceNode;
+ if (element.isContainer()) {
+ start = element.getStartEndOffset();
+ length = 0;
+ }
+ } else if (sourceNode.getNodeType() == Node.COMMENT_NODE) {
+ start += 4;
+ }
+//glory
+// ISelection selection = new StructuredSelection(sourceNode);
+// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
+// selectionManager.selectionChanged(event);
+ structuredTextViewer.setSelectedRange(start, length);
+ structuredTextViewer.revealRange(start, length);
+// selectionManager.setSelection(new TextSelection(start, length));
+ }
+ }
+
+ Node getSelectedNode() {
+ List nodes = VpeSelectionHelper.getTextWidgetSelectedNodes(model, selectionManager);
+ //selectionManager.getSelectedNodes();
+ if (nodes != null && nodes.size() > 0) {
+ return (Node)nodes.get(0);
+ } else {
+ return null;
+ }
+ }
+
+ int getCaretPosition() {
+// return selectionManager.getCaretPosition();
+ ITextViewer v = (sourceEditor == null) ? null : sourceEditor.getTextViewer();
+ StyledText t = (v == null) ? null : v.getTextWidget();
+ return (t == null) ? 0 : t.getCaretOffset();
+ }
+
+ private void addNode(nsIDOMNode visualNewNode, Node sourceNextNode, Node sourceContainer) {
+ Node sourceNewNode = createNode(visualNewNode);
+ if (sourceNewNode != null) {
+ if (sourceNextNode == null) {
+ sourceContainer.appendChild(sourceNewNode);
+ } else {
+ sourceContainer.insertBefore(sourceNewNode, sourceNextNode);
+ }
+ }
+ }
+
+ private Node createNode(nsIDOMNode visualNewNode) {
+ if (sourceDocument != null) {
+ switch (visualNewNode.getNodeType()) {
+ case Node.ELEMENT_NODE:
+ Element sourceNewElement = sourceDocument.createElement(visualNewNode.getNodeName());
+ Set ifDependencySet = new HashSet();
+ //VpeVisualDomBuilder visualBuildet =
+ pageContext.getVisualBuilder();
+ VpeTemplate template = templateManager.getTemplate(pageContext, sourceNewElement, ifDependencySet);
+ registerNodes(new VpeElementMapping(sourceNewElement, (nsIDOMElement)visualNewNode, null, template, ifDependencySet, null));
+ addChildren(visualNewNode, sourceNewElement);
+ return sourceNewElement;
+ case Node.TEXT_NODE:
+ Node sourceTextNode = sourceDocument.createTextNode(visualNewNode.getNodeValue());
+ registerNodes(new VpeNodeMapping(sourceTextNode, visualNewNode));
+ return sourceTextNode;
+ }
+ }
+ return null;
+ }
+
+ private void addChildren(nsIDOMNode visualContainer, Element sourceContainer) {
+ nsIDOMNodeList visualNodes = visualContainer.getChildNodes();
+ long len = visualNodes.getLength();
+
+ for (long i = 0; i < len; i++) {
+ nsIDOMNode visualNode = visualNodes.item(i);
+ addNode(visualNode, null, sourceContainer);
+ }
+ }
+
+ boolean openBundleEditors(nsIDOMNode visualNode) {
+ Node sourceNode = domMapping.getNearSourceNode(visualNode);
+ if (sourceNode != null && sourceNode.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceNode);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ template.openBundleEditors(pageContext, (Element)sourceNode, elementMapping.getData());
+ }
+ }
+ return false;
+ }
+
+ boolean openIncludeEditor(nsIDOMNode visualNode) {
+ Node sourceNode = domMapping.getNearSourceNode(visualNode);
+ if (sourceNode != null && sourceNode.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceNode);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ template.openIncludeEditor(pageContext, (Element)sourceNode, elementMapping.getData());
+ }
+ }
+ return false;
+ }
+
+ boolean isEmptyDocument() {
+ if (sourceDocument == null) return true;
+ boolean empty = false;
+ NodeList sourceNodes = sourceDocument.getChildNodes();
+ int len = sourceNodes.getLength();
+ if (len == 0) {
+ empty = true;
+ } else if (len == 1) {
+ Node sourceNode = sourceNodes.item(0);
+ if (sourceNode.getNodeType() == Node.TEXT_NODE && sourceNode.getNodeValue().trim().length() == 0) {
+ empty = true;
+ }
+ }
+ return empty;
+ }
+
+ int getPosition(Node sourceNode, int offset, boolean innerFlag) {
+ int start = 0;
+ if (sourceNode != null) {
+ start = ((IndexedRegion)sourceNode).getStartOffset() + offset;
+ if (innerFlag && offset == 0 && sourceNode instanceof ElementImpl) {
+ ElementImpl element = (ElementImpl)sourceNode;
+ if (element.isContainer()) {
+ start = element.getStartEndOffset();
+ }
+ }
+ }
+ return start;
+ }
+
+ void setAttributeSelection(nsIDOMNode visualText, int offset, int length) {
+ nsIDOMNode visualParent = visualText.getParentNode();
+ if (visualParent != null) {
+ Node sourceParent = domMapping.getNearSourceNode(visualText);
+ if (sourceParent != null) {
+ if (sourceParent.getNodeType() == Node.ELEMENT_NODE) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceParent);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ template.setSourceAttributeSelection(pageContext, (Element)sourceParent, offset, length, elementMapping.getData());
+ }
+ } else if (sourceParent.getNodeType() == Node.COMMENT_NODE) {
+// VpeVisualElementInfo info = domMapping.getVisualElementInfo(sourceParent);
+// if (info != null) {
+// info.setSourceCommentValue(pageContext, (Comment)sourceParent);
+// }
+ //Added by Max Areshkau in scope of bug JBIDE-1209
+ } else {
+ try{
+ IndexedRegion region = (IndexedRegion)sourceParent;
+ String text = sourceParent.getNodeValue();
+ int start= TextUtil.sourcePosition(text, visualText.getNodeValue(), offset);
+ int end =TextUtil.sourcePosition(text, visualText.getNodeValue(), offset+length);
+ offset=start;
+ length=end-start;
+ }catch(Exception ex){
+ VpePlugin.reportProblem(ex);
+ }
+ setSelection(sourceParent, offset, length);
+ }
+ }
+ }
+ }
+
+// boolean
+
+ public void setAttributeSelection(Attr sourceAttr, int offset, int length) {
+ IDOMAttr xmlAttr = (IDOMAttr)sourceAttr;
+ int start = xmlAttr.getValueRegionStartOffset() + offset;
+ String value = xmlAttr.getValueRegionText();
+ if (value.startsWith("\"") || value.startsWith("\'")) {
+ start++;
+ }
+ int end = xmlAttr.getEndOffset();
+ if (start > end) {
+ start = end;
+ }
+ if (start + length > end) {
+ length = end - start;
+ }
+
+//glory
+// ISelection selection = new StructuredSelection(sourceAttr);
+// SelectionChangedEvent event = new SelectionChangedEvent(outline, selection);
+// selectionManager.selectionChanged(event);
+ structuredTextViewer.setSelectedRange(start, length);
+ structuredTextViewer.revealRange(start, length);
+
+// selectionManager.setSelection(new TextSelection(start, length));
+ }
+
+ Point getOutputAttributesPositions(Element sourceElement) {
+ VpeElementMapping elementMapping = (VpeElementMapping)domMapping.getNodeMapping(sourceElement);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ if (template.isOutputAttributes()) {
+ int start = ((IndexedRegion)sourceElement).getStartOffset();
+ int end = ((IndexedRegion)sourceElement).getEndOffset();
+ return new Point(start, end);
+ }
+ }
+ return null;
+ }
+
+ Point getSelectionRange() {
+ return sourceEditor.getTextViewer().getSelectedRange();
+ }
+
+ public void setComment(Node sourceComment, nsIDOMNode visualElement) {
+ nsIDOMNodeList visualNodes = visualElement.getChildNodes();
+ long len = visualNodes.getLength();
+
+ if (len > 0) {
+ nsIDOMNode visualText = visualNodes.item(0);
+ sourceComment.setNodeValue(visualText.getNodeValue());
+ }
+ }
+
+ public StructuredTextViewer getStructuredTextViewer() {
+ return structuredTextViewer;
+ }
+
+ Document getSourceDocument() {
+ return sourceDocument;
+ }
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeVisualDomBuilder.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeVisualDomBuilder.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/VpeVisualDomBuilder.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,2070 +1,2143 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.eclipse.wst.xml.core.internal.document.NodeImpl;
-import org.jboss.tools.common.model.XModel;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.project.IModelNature;
-import org.jboss.tools.common.model.util.EclipseResourceUtil;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.jst.web.model.helpers.WebAppHelper;
-import org.jboss.tools.vpe.VpeDebug;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.dnd.VpeDnD;
-import org.jboss.tools.vpe.editor.bundle.BundleMap;
-import org.jboss.tools.vpe.editor.context.VpePageContext;
-import org.jboss.tools.vpe.editor.css.CSSReferenceList;
-import org.jboss.tools.vpe.editor.css.ResourceReference;
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
-import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
-import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
-import org.jboss.tools.vpe.editor.template.VpeChildrenInfo;
-import org.jboss.tools.vpe.editor.template.VpeCreationData;
-import org.jboss.tools.vpe.editor.template.VpeDefaultPseudoContentCreator;
-import org.jboss.tools.vpe.editor.template.VpeTagDescription;
-import org.jboss.tools.vpe.editor.template.VpeTemplate;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-import org.jboss.tools.vpe.editor.template.VpeToggableTemplate;
-import org.jboss.tools.vpe.editor.template.dnd.VpeDnd;
-import org.jboss.tools.vpe.editor.util.HTML;
-import org.jboss.tools.vpe.editor.util.TextUtil;
-import org.jboss.tools.vpe.editor.util.VisualDomUtil;
-import org.jboss.tools.vpe.editor.util.VpeStyleUtil;
-import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
-import org.jboss.tools.vpe.xulrunner.editor.XulRunnerVpeUtils;
-import org.mozilla.interfaces.nsIDOMAttr;
-import org.mozilla.interfaces.nsIDOMDocument;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMHTMLInputElement;
-import org.mozilla.interfaces.nsIDOMMouseEvent;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.mozilla.interfaces.nsIDOMNodeList;
-import org.mozilla.interfaces.nsIDOMRange;
-import org.mozilla.interfaces.nsIDOMText;
-import org.mozilla.xpcom.XPCOMException;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class VpeVisualDomBuilder extends VpeDomBuilder {
- /** REGEX_EL */
- private static final Pattern REGEX_EL = Pattern.compile(
- "[\\$|\\#]\\{.*\\}", Pattern.MULTILINE + Pattern.DOTALL);
-
- private static final String PSEUDO_ELEMENT = "br";
- private static final String PSEUDO_ELEMENT_ATTR = "vpe:pseudo-element";
- private static final String INIT_ELEMENT_ATTR = "vpe:init-element";
- private static final String MOZ_ANONCLASS_ATTR = "_MOZ_ANONCLASS";
- private static final String COMMENT_STYLE = "font-style:italic; color:green";
- private static final String COMMENT_PREFIX = "";
- private static final String COMMENT_SUFFIX = "";
- private static final String INCLUDE_ELEMENT_ATTR = "vpe:include-element";
- private static final int DRAG_AREA_WIDTH = 10;
- private static final int DRAG_AREA_HEIGHT = 10;
- private static final String ATTR_XMLNS = "xmlns";
- private static final String ATTR_DRAG_AVAILABLE_CLASS = "__drag__available_style";
-
- private MozillaEditor visualEditor;
- private XulRunnerEditor xulRunnerEditor;
- private nsIDOMDocument visualDocument;
- private nsIDOMElement visualContentArea;
- private VpePageContext pageContext;
- private VpeDnD dnd;
- private nsIDOMNode headNode;
- private List includeStack;
- boolean rebuildFlag = false;
-
- /** faceletFile */
- private boolean faceletFile = false;
-
- private static final String ATTR_VPE = "vpe";
- private static final String ATTR_VPE_INLINE_LINK_VALUE = "inlinelink";
-
- private static final String ATTR_REL_STYLESHEET_VALUE = "stylesheet";
-
- private static final String YES_STRING = "yes";
- private static final String NO_STRING = "no";
- private static final String ZERO_STRING = "0";
- private static final String EMPTY_STRING = "";
-
- private static final String ATRIBUTE_BORDER = "border";
- private static final String ATRIBUTE_CELLSPACING = "cellspacing";
- private static final String ATRIBUTE_CELLPADDING = "cellpadding";
-
- private static final String DOTTED_BORDER_STYLE = "border : 1px dotted #808080";
- private static final String DOTTED_BORDER_STYLE_FOR_IMG = "1px dotted #808080";
- private static final String DOTTED_BORDER_STYLE_FOR_TD = "border-left : 1px dotted #808080; border-right : 1px dotted #808080; border-top : 1px dotted #808080; border-bottom : 0px; color:#0051DD; background-color:#ECF3FF; padding-left: 3px; padding-right: 3px; line-height : 10px; font-family : arial; font-size : 10px; text-align:top; margin : 1px; -moz-user-modify : read-only";
- private static final String DOTTED_BORDER_STYLE_FOR_SPAN = "border : 1px solid #0051DD; color:#0051DD; background-color:#ECF3FF; padding-left: 3px; padding-right: 3px; line-height : 10px; font-family : arial; font-size : 10px; text-align:top; margin : 1px; -moz-user-modify : read-only";
-
- static private HashSet<String> unborderedSourceNodes = new HashSet<String>();
- static {
- unborderedSourceNodes.add(HTML.TAG_HTML);
- unborderedSourceNodes.add(HTML.TAG_HEAD);
- unborderedSourceNodes.add(HTML.TAG_BODY);
- }
-
- static private HashSet<String> unborderedVisualNodes = new HashSet<String>();
- static {
- unborderedVisualNodes.add(HTML.TAG_TBODY);
- unborderedVisualNodes.add(HTML.TAG_THEAD);
- unborderedVisualNodes.add(HTML.TAG_TR);
- unborderedVisualNodes.add(HTML.TAG_TD);
- unborderedVisualNodes.add(HTML.TAG_COL);
- unborderedVisualNodes.add(HTML.TAG_COLS);
- unborderedVisualNodes.add(HTML.TAG_COLGROUP);
- unborderedVisualNodes.add(HTML.TAG_LI);
- unborderedVisualNodes.add(HTML.TAG_BR);
- }
- private VpeDnd dropper;
-
- public VpeVisualDomBuilder(VpeDomMapping domMapping,
- INodeAdapter sorceAdapter, VpeTemplateManager templateManager,
- MozillaEditor visualEditor, VpePageContext pageContext) {
- super(domMapping, sorceAdapter, templateManager);
- this.visualEditor = visualEditor;
- xulRunnerEditor = visualEditor.getXulRunnerEditor();
- this.visualDocument = visualEditor.getDomDocument();
- this.visualContentArea = visualEditor.getContentArea();
- this.dnd = new VpeDnD();
- this.pageContext = pageContext;
- this.headNode = visualEditor.getHeadNode();
- dropper = new VpeDnd();
- dropper.setDndData(false, true);
-
- if (isFacelet()) {
- faceletFile = true;
- } else {
- faceletFile = false;
- }
-
- }
-
- public void buildDom(Document sourceDocument) {
- includeStack = new ArrayList();
- IEditorInput input = pageContext.getEditPart().getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) input).getFile();
- if (file != null) {
- includeStack.add(new VpeIncludeInfo(null, file, pageContext
- .getSourceBuilder().getSourceDocument()));
- }
- }
- pageContext.refreshConnector();
- pageContext.installIncludeElements();
- addChildren(null, sourceDocument, visualContentArea);
- registerNodes(new VpeNodeMapping(sourceDocument, visualContentArea));
- }
-
- public void rebuildDom(Document sourceDocument) {
- cleanHead();
- domMapping.clear(visualContentArea);
- pageContext.clearAll();
- refreshExternalLinks();
- pageContext.getBundle().refreshRegisteredBundles();
-
- nsIDOMNodeList children = visualContentArea.getChildNodes();
- long len = children.getLength();
- for (long i = len - 1; i >= 0; i--) {
- visualContentArea.removeChild(children.item(i));
- }
-
- if (sourceDocument != null) {
- buildDom(sourceDocument);
- }
-
- rebuildFlag = true;
- }
-
- // temporary, will be change to prefference's variable
- // private boolean borderVisible = true;
-
- private boolean addNode(Node sourceNode, nsIDOMNode visualNextNode,
- nsIDOMNode visualContainer) {
- nsIDOMNode visualNewNode = createNode(sourceNode, visualContainer);
- // Fix for JBIDE-1097
- try {
- if (visualNewNode != null) {
- nsIDOMHTMLInputElement iDOMInputElement = (nsIDOMHTMLInputElement) visualNewNode
- .queryInterface(nsIDOMHTMLInputElement.NS_IDOMHTMLINPUTELEMENT_IID);
- iDOMInputElement.setReadOnly(true);
- }
- } catch (XPCOMException ex) {
- // just ignore this exception
- }
- if (visualNewNode != null) {
- if (visualNextNode == null) {
- visualContainer.appendChild(visualNewNode);
- } else {
- visualContainer.insertBefore(visualNewNode, visualNextNode);
- }
- return true;
- }
-
- return false;
- }
-
- private nsIDOMElement createBorder(Node sourceNode,
- nsIDOMElement visualNode, boolean block) {
- nsIDOMElement border = null;
- if (visualNode == null)
- return null;
- if (unborderedSourceNodes.contains(sourceNode.getNodeName()
- .toLowerCase()))
- return null;
- if (unborderedVisualNodes.contains(visualNode.getNodeName()
- .toLowerCase()))
- return null;
- if (HTML.TAG_IMG.equalsIgnoreCase(visualNode.getNodeName())) {
- String width = visualNode.getAttribute(ATRIBUTE_BORDER);
- if (width == null || ZERO_STRING.equalsIgnoreCase(width)
- || EMPTY_STRING.equalsIgnoreCase(width)) {
- String style = visualNode
- .getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
- style = VpeStyleUtil.setParameterInStyle(style,
- ATRIBUTE_BORDER, DOTTED_BORDER_STYLE_FOR_IMG);
- visualNode.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
- }
- return null;
- }
- if (block) {
- if (YES_STRING.equals(VpePreference.USE_DETAIL_BORDER.getValue())) {
- border = visualDocument.createElement(HTML.TAG_TABLE);
- border.setAttribute(ATRIBUTE_CELLSPACING, ZERO_STRING);
- border.setAttribute(ATRIBUTE_CELLPADDING, ZERO_STRING);
-
- nsIDOMElement tr1 = visualDocument.createElement(HTML.TAG_TR);
- border.appendChild(tr1);
- nsIDOMElement td1 = visualDocument.createElement(HTML.TAG_TD);
- td1.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
- DOTTED_BORDER_STYLE_FOR_TD);
- nsIDOMText text = visualDocument.createTextNode(sourceNode
- .getNodeName());
- td1.appendChild(text);
- tr1.appendChild(td1);
- nsIDOMElement tr2 = visualDocument.createElement(HTML.TAG_TR);
- border.appendChild(tr2);
- nsIDOMElement td2 = visualDocument.createElement(HTML.TAG_TD);
- tr2.appendChild(td2);
- nsIDOMElement p = visualDocument.createElement(HTML.TAG_P);
- p.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
- DOTTED_BORDER_STYLE);
- td2.appendChild(p);
-
- p.appendChild(visualNode);
-
- } else {
- border = visualDocument.createElement(HTML.TAG_TABLE);
- border.setAttribute(ATRIBUTE_CELLSPACING, ZERO_STRING);
- border.setAttribute(ATRIBUTE_CELLPADDING, ZERO_STRING);
-
- nsIDOMElement tr2 = visualDocument.createElement(HTML.TAG_TR);
- border.appendChild(tr2);
- nsIDOMElement td2 = visualDocument.createElement(HTML.TAG_TD);
- tr2.appendChild(td2);
- nsIDOMElement p = visualDocument.createElement(HTML.TAG_P);
- p.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
- DOTTED_BORDER_STYLE);
- td2.appendChild(p);
-
- p.appendChild(visualNode);
- }
- } else {
- border = visualDocument.createElement(HTML.TAG_SPAN);
- border.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
- DOTTED_BORDER_STYLE);
- if (YES_STRING.equals(VpePreference.USE_DETAIL_BORDER.getValue())) {
- nsIDOMElement name = visualDocument
- .createElement(HTML.TAG_SPAN);
- name.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
- DOTTED_BORDER_STYLE_FOR_SPAN);
- nsIDOMText text = visualDocument.createTextNode(sourceNode
- .getNodeName());
- name.appendChild(text);
- border.appendChild(name);
- }
- border.appendChild(visualNode);
- }
- if (VpeStyleUtil.getAbsolute((Element) sourceNode) && border != null) {
- int top = VpeStyleUtil.getSizeFromStyle((Element) sourceNode,
- VpeStyleUtil.ATTRIBUTE_STYLE + VpeStyleUtil.DOT_STRING
- + VpeStyleUtil.PARAMETER_TOP);
- int left = VpeStyleUtil.getSizeFromStyle((Element) sourceNode,
- VpeStyleUtil.ATTRIBUTE_STYLE + VpeStyleUtil.DOT_STRING
- + VpeStyleUtil.PARAMETER_LEFT);
-
- String style = visualNode
- .getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
- style = VpeStyleUtil.deleteFromString(style,
- VpeStyleUtil.PARAMETER_POSITION,
- VpeStyleUtil.SEMICOLON_STRING);
- style = VpeStyleUtil.deleteFromString(style,
- VpeStyleUtil.PARAMETER_TOP, VpeStyleUtil.SEMICOLON_STRING);
- style = VpeStyleUtil.deleteFromString(style,
- VpeStyleUtil.PARAMETER_LEFT, VpeStyleUtil.SEMICOLON_STRING);
- visualNode.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
-
- style = border.getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
- style = VpeStyleUtil.setAbsolute(style);
- if (top != -1)
- style = VpeStyleUtil.setSizeInStyle(style,
- VpeStyleUtil.PARAMETER_TOP, top);
- if (left != -1)
- style = VpeStyleUtil.setSizeInStyle(style,
- VpeStyleUtil.PARAMETER_LEFT, left);
- border.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
- }
- return border;
- }
-
- protected nsIDOMNode createNode(Node sourceNode,
- nsIDOMNode visualOldContainer) {
- boolean registerFlag = isCurrentMainDocument();
- switch (sourceNode.getNodeType()) {
- case Node.ELEMENT_NODE:
- Map<?, ?> xmlnsMap = createXmlns((Element) sourceNode);
- Set<Node> ifDependencySet = new HashSet<Node>();
- pageContext.setCurrentVisualNode(visualOldContainer);
- VpeTemplate template = templateManager.getTemplate(pageContext,
- (Element) sourceNode, ifDependencySet);
-
- VpeCreationData creationData = null;
- //FIX FOR JBIDE-1568, added by Max Areshkau
- try {
- creationData = template.create(getPageContext(), sourceNode, getVisualDocument());
- }catch (XPCOMException ex) {
- VpePlugin.getPluginLog().logError(ex);
- VpeTemplate defTemplate = templateManager.getDefTemplate();
- creationData = defTemplate.create(getPageContext(), sourceNode, getVisualDocument());
- }
- pageContext.setCurrentVisualNode(null);
- nsIDOMElement visualNewElement = (nsIDOMElement) creationData
- .getNode();
-
- if (visualNewElement != null)
- correctVisualAttribute(visualNewElement);
-
- nsIDOMElement border = null;
- setTooltip((Element) sourceNode, visualNewElement);
- if (YES_STRING.equals(VpePreference.SHOW_BORDER_FOR_ALL_TAGS
- .getValue())
- && visualNewElement != null) {
- boolean block = true;
- if (template.getTagDescription(null, null, null,
- visualNewElement, null).getDisplayType() == VpeTagDescription.DISPLAY_TYPE_INLINE) {
- block = false;
- }
- border = createBorder(sourceNode, visualNewElement, block);
- }
- if (!isCurrentMainDocument() && visualNewElement != null) {
- setReadOnlyElement(visualNewElement);
- }
- if (registerFlag) {
- VpeElementMapping elementMapping = new VpeElementMapping(
- (Element) sourceNode, visualNewElement, border,
- template, ifDependencySet, creationData.getData());
- elementMapping.setXmlnsMap(xmlnsMap);
- registerNodes(elementMapping);
- }
- if (template.isChildren()) {
- List<?> childrenInfoList = creationData.getChildrenInfoList();
- if (childrenInfoList == null) {
- addChildren(template, sourceNode,
- visualNewElement != null ? visualNewElement
- : visualOldContainer);
- } else {
- addChildren(template, sourceNode, visualOldContainer,
- childrenInfoList);
- }
- }
- pageContext.setCurrentVisualNode(visualOldContainer);
- template.validate(pageContext, (Element) sourceNode,
- visualDocument, creationData);
- pageContext.setCurrentVisualNode(null);
- if (border != null)
- return border;
- else
- return visualNewElement;
- case Node.TEXT_NODE:
- return createTextNode(sourceNode, registerFlag);
- case Node.COMMENT_NODE:
- if (!YES_STRING.equals(VpePreference.SHOW_COMMENTS.getValue())) {
- return null;
- }
- nsIDOMElement visualNewComment = createComment(sourceNode);
- if (registerFlag) {
- registerNodes(new VpeNodeMapping(sourceNode, visualNewComment));
- }
- return visualNewComment;
- }
- return null;
- }
-
- private void correctVisualAttribute(nsIDOMElement element) {
-
- String styleValue = element.getAttribute(HTML.TAG_STYLE);
- String backgroundValue = element
- .getAttribute(VpeStyleUtil.PARAMETR_BACKGROND);
-
- if (styleValue != null) {
- styleValue = VpeStyleUtil.addFullPathIntoURLValue(styleValue,
- pageContext.getEditPart().getEditorInput());
- element.setAttribute(HTML.TAG_STYLE, styleValue);
- }
- if (backgroundValue != null) {
- backgroundValue = VpeStyleUtil
- .addFullPathIntoBackgroundValue(backgroundValue,
- pageContext.getEditPart().getEditorInput());
- element.setAttribute(VpeStyleUtil.PARAMETR_BACKGROND,
- backgroundValue);
- }
- }
-
- protected nsIDOMElement createComment(Node sourceNode) {
- nsIDOMElement div = visualDocument.createElement(HTML.TAG_DIV);
- div.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, COMMENT_STYLE);
- String value = COMMENT_PREFIX + sourceNode.getNodeValue()
- + COMMENT_SUFFIX;
- nsIDOMText text = visualDocument.createTextNode(value);
- div.appendChild(text);
- return div;
- }
-
- protected void addChildren(VpeTemplate containerTemplate,
- Node sourceContainer, nsIDOMNode visualContainer) {
- NodeList sourceNodes = sourceContainer.getChildNodes();
- int len = sourceNodes.getLength();
- int childrenCount = 0;
- for (int i = 0; i < len; i++) {
- Node sourceNode = sourceNodes.item(i);
- if (addNode(sourceNode, null, visualContainer)) {
- childrenCount++;
- }
- }
- if (childrenCount == 0) {
- setPseudoContent(containerTemplate, sourceContainer,
- visualContainer);
- }
- }
-
- protected void addChildren(VpeTemplate containerTemplate,
- Node sourceContainer, nsIDOMNode visualOldContainer,
- List<?> childrenInfoList) {
- for (int i = 0; i < childrenInfoList.size(); i++) {
- VpeChildrenInfo info = (VpeChildrenInfo) childrenInfoList.get(i);
- nsIDOMNode visualParent = info.getVisualParent();
- if (visualParent == null)
- visualParent = visualOldContainer;
- List<?> sourceChildren = info.getSourceChildren();
- int childrenCount = 0;
- if (sourceChildren != null) {
- for (int j = 0; j < sourceChildren.size(); j++) {
- if (addNode((Node) sourceChildren.get(j), null,
- visualParent)) {
- childrenCount++;
- }
- }
- }
- if (childrenCount == 0 && childrenInfoList.size() == 0) {
- setPseudoContent(containerTemplate, sourceContainer,
- visualParent);
- }
- }
- }
-
- // /////////////////////////////////////////////////////////////////////////
- public nsIDOMNode addStyleNodeToHead(String styleText) {
- nsIDOMNode newStyle = visualDocument
- .createElement(VpeStyleUtil.ATTRIBUTE_STYLE);
-
- if (styleText != null) {
- nsIDOMText newText = visualDocument.createTextNode(styleText);
- newStyle.appendChild(newText);
- }
- headNode.appendChild(newStyle);
- return newStyle;
- }
-
- public nsIDOMNode replaceStyleNodeToHead(nsIDOMNode oldStyleNode,
- String styleText) {
- nsIDOMElement newStyle = visualDocument
- .createElement(VpeStyleUtil.ATTRIBUTE_STYLE);
-
- if (styleText != null) {
- nsIDOMNode newText = visualDocument.createTextNode(styleText);
- newStyle.appendChild(newText);
- }
-
- headNode.replaceChild(newStyle, oldStyleNode);
- return newStyle;
- }
-
- public void removeStyleNodeFromHead(nsIDOMNode oldStyleNode) {
- headNode.removeChild(oldStyleNode);
- }
-
- void addExternalLinks() {
- IEditorInput input = pageContext.getEditPart().getEditorInput();
- IFile file = null;
- if (input instanceof IFileEditorInput) {
- file = ((IFileEditorInput) input).getFile();
- }
- ResourceReference[] l = null;
- if (file != null) {
- l = CSSReferenceList.getInstance().getAllResources(file);
- }
- if (l != null) {
- for (int i = 0; i < l.length; i++) {
- ResourceReference item = l[i];
- addLinkNodeToHead("file:///" + item.getLocation(), YES_STRING);
- }
- }
- }
-
- void removeExternalLinks() {
- nsIDOMNodeList childs = headNode.getChildNodes();
- long length = childs.getLength();
- for (long i = length - 1; i >= 0; i--) {
- nsIDOMNode node = childs.item(i);
- if (node.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- boolean isLink = false;
- boolean isStyle = false;
- if ((isLink = HTML.TAG_LINK
- .equalsIgnoreCase(node.getNodeName()))
- || (isStyle = HTML.TAG_STYLE.equalsIgnoreCase(node
- .getNodeName()))) {
- nsIDOMElement element = (nsIDOMElement) node
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- if ((isLink || (isStyle && ATTR_VPE_INLINE_LINK_VALUE
- .equalsIgnoreCase(element.getAttribute(ATTR_VPE))))
- && YES_STRING.equalsIgnoreCase(element
- .getAttribute("ext"))) {
- headNode.removeChild(node);
- }
- }
- }
- }
- }
-
- void refreshExternalLinks() {
- removeExternalLinks();
- addExternalLinks();
- }
-
- // ==========================================================
- void resetPseudoElement(nsIDOMNode visualNode) {
- if (visualNode != null) {
- nsIDOMNode visualParent = visualNode.getParentNode();
- if (visualParent != null) {
- PseudoInfo info = getPseudoInfo(visualParent);
- if (info.pseudoNode == null && !info.isElements) {
- addPseudoElementImpl(visualParent);
- } else if (info.pseudoNode != null && info.isElements) {
- visualParent.removeChild(info.pseudoNode);
- }
- }
- }
- }
-
- private PseudoInfo getPseudoInfo(nsIDOMNode visualParent) {
- nsIDOMNode pseudoNode = null;
- boolean isElements = false;
-
- if (visualParent == null)
- return new PseudoInfo();
- nsIDOMNodeList visualNodes = visualParent.getChildNodes();
- if (visualNodes == null)
- return new PseudoInfo();
-
- long length = visualNodes.getLength();
- for (long i = 0; i < length; i++) {
- nsIDOMNode visualNode = visualNodes.item(i);
- if (pseudoNode == null && isPseudoElement(visualNode)) {
- pseudoNode = visualNode;
- } else if (!isEmptyText(visualNode)) {
- isElements = true;
- }
- if (pseudoNode != null && isElements) {
- break;
- }
- }
- return new PseudoInfo(pseudoNode, isElements);
- }
-
- static boolean isInitElement(nsIDOMNode visualNode) {
- if (visualNode == null) {
- return false;
- }
-
- if (visualNode.getNodeType() != Node.ELEMENT_NODE) {
- return false;
- }
-
- if (YES_STRING.equalsIgnoreCase(((nsIDOMElement) visualNode)
- .getAttribute(INIT_ELEMENT_ATTR))) {
- return true;
- }
-
- return false;
- }
-
- static boolean isPseudoElement(nsIDOMNode visualNode) {
- if (visualNode == null) {
- return false;
- }
-
- if (visualNode.getNodeType() != Node.ELEMENT_NODE) {
- return false;
- }
-
- if (YES_STRING.equalsIgnoreCase(((nsIDOMElement) visualNode
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
- .getAttribute(PSEUDO_ELEMENT_ATTR))) {
- return true;
- }
-
- return false;
- }
-
- private void setPseudoContent(VpeTemplate containerTemplate,
- Node sourceContainer, nsIDOMNode visualContainer) {
- if (containerTemplate != null) {
- containerTemplate.setPseudoContent(pageContext, sourceContainer,
- visualContainer, visualDocument);
- } else {
- VpeDefaultPseudoContentCreator.getInstance().setPseudoContent(
- pageContext, sourceContainer, visualContainer,
- visualDocument);
- }
-
- // if (isEmptyElement(visualContainer)) {
- // addPseudoElementImpl(visualContainer);
- // }
- }
-
- private void addPseudoElementImpl(nsIDOMNode visualParent) {
- if (!templateManager.isWithoutPseudoElementContainer(visualParent
- .getNodeName())) {
- if (VpeDebug.VISUAL_ADD_PSEUDO_ELEMENT) {
- System.out.println("-------------------- addPseudoElement: "
- + visualParent.getNodeName());
- }
- nsIDOMElement visualPseudoElement = visualDocument
- .createElement(PSEUDO_ELEMENT);
- visualPseudoElement.setAttribute(PSEUDO_ELEMENT_ATTR, "yes");
- visualParent.appendChild(visualPseudoElement);
- }
- }
-
- public boolean isEmptyElement(nsIDOMNode visualParent) {
- nsIDOMNodeList visualNodes = visualParent.getChildNodes();
- long len = visualNodes.getLength();
-
- if ((len == 0) || (len == 1 && isEmptyText(visualNodes.item(0)))) {
- return true;
- }
-
- return false;
- }
-
- public boolean isEmptyDocument() {
- nsIDOMNodeList visualNodes = visualContentArea.getChildNodes();
- long len = visualNodes.getLength();
- if ((len == 0)
- || (len == 1 && (isEmptyText(visualNodes.item(0)) || isPseudoElement(visualNodes
- .item(0))))) {
- return true;
- }
-
- return false;
- }
-
- private boolean isEmptyText(nsIDOMNode visualNode) {
- if (visualNode == null
- || (visualNode.getNodeType() != nsIDOMNode.TEXT_NODE)) {
- return false;
- }
-
- if (visualNode.getNodeValue().trim().length() == 0) {
- return true;
- }
-
- return false;
- }
-
- // ==========================================================
-
- public void updateNode(Node sourceNode) {
- if (sourceNode == null)
- return;
-
- switch (sourceNode.getNodeType()) {
- case Node.DOCUMENT_NODE:
- rebuildDom((Document) sourceNode);
- break;
- case Node.COMMENT_NODE:
- updateComment(sourceNode);
- break;
- default:
- updateElement(getNodeForUpdate(sourceNode));
- }
- }
-
- // TODO Ssergey Vasilyev make a common code for figuring out
- // if it is need to update parent node or not
- private Node getNodeForUpdate(Node sourceNode) {
- /* Changing of <tr> or <td> tags can affect whole the table */
- Node sourceTable = getParentTable(sourceNode, 2);
- if (sourceTable != null) {
- return sourceTable;
- }
-
- /* Changing of an <option> tag can affect the parent select */
- Node sourceSelect = getParentSelect(sourceNode);
- if (sourceSelect != null) {
- return sourceSelect;
- }
-
- return sourceNode;
- }
-
- private void updateComment(Node sourceNode) {
- VpeNodeMapping mapping = domMapping.getNodeMapping(sourceNode);
- if (mapping != null
- && mapping.getType() == VpeNodeMapping.COMMENT_MAPPING) {
- nsIDOMNodeList visualNodes = mapping.getVisualNode()
- .getChildNodes();
-
- if (visualNodes.getLength() > 0) {
- visualNodes.item(0).setNodeValue(sourceNode.getNodeValue());
- }
- }
- }
-
- private void updateElement(Node sourceNode) {
- VpeElementMapping elementMapping = null;
- VpeNodeMapping nodeMapping = domMapping.getNodeMapping(sourceNode);
- if (nodeMapping instanceof VpeElementMapping) {
- elementMapping = (VpeElementMapping) nodeMapping;
- if (elementMapping != null && elementMapping.getTemplate() != null) {
- Node updateNode = elementMapping.getTemplate()
- .getNodeForUptate(pageContext,
- elementMapping.getSourceNode(),
- elementMapping.getVisualNode(),
- elementMapping.getData());
- if (updateNode != null && updateNode != sourceNode) {
- updateNode(updateNode);
- return;
- }
- }
- }
- nsIDOMNode visualOldNode = domMapping.remove(sourceNode);
- if (visualOldNode != null) {
- if (elementMapping != null) {
- nsIDOMElement border = elementMapping.getBorder();
- if (border != null) {
- visualOldNode = border;
- }
- }
- nsIDOMNode visualContainer = visualOldNode.getParentNode();
- nsIDOMNode visualNextNode = visualOldNode.getNextSibling();
- if (visualContainer != null) {
- visualContainer.removeChild(visualOldNode);
- addNode(sourceNode, visualNextNode, visualContainer);
- }
- } else {
- if (sourceNode.getNodeType() == Node.TEXT_NODE) {
- updateNode(sourceNode.getParentNode());
- }
- }
- }
-
- public void removeNode(Node sourceNode) {
- domMapping.remove(sourceNode);
- }
-
- private Node getParentTable(Node sourceNode, int depth) {
- Node parentNode = sourceNode.getParentNode();
- for (int i = 0; parentNode != null && i < depth; parentNode = parentNode
- .getParentNode(), i++) {
- if (HTML.TAG_TABLE.equalsIgnoreCase(parentNode.getNodeName())) {
- return parentNode;
- }
- }
- return null;
- }
-
- private Node getParentSelect(Node sourceNode) {
- if (HTML.TAG_OPTION.equalsIgnoreCase(sourceNode.getNodeName())) {
- Node parentNode = sourceNode.getParentNode();
- if (HTML.TAG_SELECT.equalsIgnoreCase(parentNode.getNodeName())) {
- return parentNode;
- }
- }
- return null;
- }
-
- public void setText(Node sourceText) {
- Node sourceParent = sourceText.getParentNode();
- if (sourceParent != null && sourceParent.getLocalName() != null) {
- String sourceParentName = sourceParent.getLocalName();
- if (HTML.TAG_TEXTAREA.equalsIgnoreCase(sourceParentName)
- || HTML.TAG_OPTION.equalsIgnoreCase(sourceParentName)) {
- updateNode(sourceText.getParentNode());
- return;
- }
- }
- nsIDOMNode visualText = domMapping.getVisualNode(sourceText);
- if (visualText != null) {
- String visualValue = TextUtil.visualText(sourceText.getNodeValue());
- visualText.setNodeValue(visualValue);
- }else {
- VpeNodeMapping nodeMapping = domMapping
- .getNodeMapping(sourceParent);
- if (nodeMapping != null
- && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
- VpeTemplate template = ((VpeElementMapping) nodeMapping)
- .getTemplate();
- if (template != null) {
- if (!template.containsText()) {
- return;
- }
- }
- }
- updateNode(sourceText);
- }
- }
-
- public void setAttribute(Element sourceElement, String name, String value) {
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(sourceElement);
- if (elementMapping != null) {
- if (elementMapping.isIfDependencyFromAttribute(name)) {
- updateElement(sourceElement);
- } else {
- VpeTemplate template = elementMapping.getTemplate();
- if (elementMapping.getBorder() != null) {
- updateElement(sourceElement);
- } else if (template.isRecreateAtAttrChange(pageContext,
- sourceElement, visualDocument,
- (nsIDOMElement) elementMapping.getVisualNode(),
- elementMapping.getData(), name, value)) {
- updateElement(sourceElement);
- } else {
- nsIDOMElement visualElement = (nsIDOMElement) elementMapping
- .getVisualNode();
- if (visualElement != null) {
- String visualElementName = visualElement.getNodeName();
- if (HTML.TAG_SELECT.equalsIgnoreCase(visualElementName)) {
- updateElement(sourceElement);
- return;
- } else if (HTML.TAG_OPTION
- .equalsIgnoreCase(visualElementName)) {
- updateElement(sourceElement.getParentNode());
- return;
- } else if (HTML.TAG_INPUT
- .equalsIgnoreCase(visualElementName)) {
- updateElement(sourceElement);
- }
- }
- setXmlnsAttribute(elementMapping, name, value);
- template.setAttribute(pageContext, sourceElement,
- visualDocument, visualElement, elementMapping
- .getData(), name, value);
- resetTooltip(sourceElement, visualElement);
- }
- }
- }
- }
-
- public void stopToggle(Node sourceNode) {
- if (!(sourceNode instanceof Element))
- return;
-
- Element sourceElement = (Element) sourceNode;
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(sourceElement);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
-
- if (template instanceof VpeToggableTemplate) {
- ((VpeToggableTemplate) template).stopToggling(sourceElement);
- }
- }
- }
-
- public boolean doToggle(nsIDOMNode visualNode) {
- if (visualNode == null)
- return false;
- nsIDOMElement visualElement = null;
- try {
-
- visualElement = (nsIDOMElement) visualNode
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- } catch (XPCOMException exception) {
- visualElement = (nsIDOMElement) visualNode.getParentNode()
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- }
- if (visualElement == null)
- return false;
-
- nsIDOMAttr toggleIdAttr = visualElement
- .getAttributeNode("vpe-user-toggle-id");
- if (toggleIdAttr == null)
- return false;
- String toggleId = toggleIdAttr.getNodeValue();
-
- if (toggleId == null)
- return false;
-
- boolean toggleLookup = false;
- nsIDOMAttr toggleLookupAttr = visualElement
- .getAttributeNode("vpe-user-toggle-lookup-parent");
- if (toggleLookupAttr != null) {
- toggleLookup = "true".equals(toggleLookupAttr.getNodeValue());
- }
-
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(getLastSelectedElement());
- Node sourceNode = (Node) domMapping
- .getSourceNode(getLastSelectedElement());
- if (sourceNode == null)
- return false;
-
- Element sourceElement = (Element) (sourceNode instanceof Element ? sourceNode
- : sourceNode.getParentNode());
-
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
-
- while (toggleLookup && sourceElement != null
- && !(template instanceof VpeToggableTemplate)) {
- sourceElement = (Element) sourceElement.getParentNode();
- if (sourceElement == null)
- break;
- elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(sourceElement);
- if (elementMapping == null)
- continue;
- template = elementMapping.getTemplate();
- }
-
- if (template instanceof VpeToggableTemplate) {
- ((VpeToggableTemplate) template).toggle(this, sourceElement,
- toggleId);
- updateElement(sourceElement);
- return true;
- }
- }
- return false;
- }
-
- public void removeAttribute(Element sourceElement, String name) {
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(sourceElement);
- if (elementMapping != null) {
- if (elementMapping.isIfDependencyFromAttribute(name)) {
- updateElement(sourceElement);
- } else {
- VpeTemplate template = elementMapping.getTemplate();
- if (template.isRecreateAtAttrChange(pageContext, sourceElement,
- visualDocument, (nsIDOMElement) elementMapping
- .getVisualNode(), elementMapping.getData(),
- name, null)) {
- updateElement(sourceElement);
- } else {
- removeXmlnsAttribute(elementMapping, name);
- template.removeAttribute(pageContext, sourceElement,
- visualDocument, (nsIDOMElement) elementMapping
- .getVisualNode(), elementMapping.getData(),
- name);
- resetTooltip(sourceElement, (nsIDOMElement) elementMapping
- .getVisualNode());
- }
- }
- }
- }
-
- public void refreshBundleValues(Element sourceElement) {
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(sourceElement);
- if (elementMapping != null) {
- VpeTemplate template = elementMapping.getTemplate();
- template.refreshBundleValues(pageContext, sourceElement,
- elementMapping.getData());
- }
- }
-
- boolean isContentArea(nsIDOMNode visualNode) {
- return visualContentArea.equals(visualNode);
- }
-
- nsIDOMElement getContentArea() {
- return visualContentArea;
- }
-
- void setSelectionRectangle(nsIDOMElement visualElement) {
- setSelectionRectangle(visualElement, true);
- }
-
- void setSelectionRectangle(nsIDOMElement visualElement, boolean scroll) {
- int resizerConstrains = getResizerConstrains(visualElement);
- visualEditor.setSelectionRectangle(visualElement, resizerConstrains,
- scroll);
- }
-
- public nsIDOMNode addLinkNodeToHead(String href_val, String ext_val) {
- nsIDOMElement newNode = createLinkNode(href_val,
- ATTR_REL_STYLESHEET_VALUE, ext_val);
- headNode.appendChild(newNode);
- return newNode;
- }
-
- public nsIDOMNode replaceLinkNodeToHead(nsIDOMNode oldNode,
- String href_val, String ext_val) {
- nsIDOMNode newNode = createLinkNode(href_val,
- ATTR_REL_STYLESHEET_VALUE, ext_val);
- headNode.replaceChild(newNode, oldNode);
- return newNode;
- }
-
- public nsIDOMNode replaceLinkNodeToHead(String href_val, String ext_val) {
- nsIDOMNode newNode = null;
- nsIDOMNode oldNode = getLinkNode(href_val, ext_val);
- if (oldNode == null) {
- newNode = addLinkNodeToHead(href_val, ext_val);
- }
- return newNode;
- }
-
- public void removeLinkNodeFromHead(nsIDOMNode node) {
- headNode.removeChild(node);
- }
-
- private nsIDOMElement createLinkNode(String href_val, String rel_val,
- String ext_val) {
- nsIDOMElement linkNode = null;
- if ((ATTR_REL_STYLESHEET_VALUE.equalsIgnoreCase(rel_val))
- && href_val.startsWith("file:")) {
- /*
- * Because of the Mozilla caches the linked css files we replace tag
- * <link rel="styleseet" href="file://..."> with tag <style
- * vpe="ATTR_VPE_INLINE_LINK_VALUE">file content</style> It is
- * LinkReplacer
- */
- linkNode = visualDocument.createElement(HTML.TAG_STYLE);
- linkNode.setAttribute(ATTR_VPE, ATTR_VPE_INLINE_LINK_VALUE);
-
- /* Copy links attributes into our <style> */
- linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_HREF, href_val);
- linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_EXT, ext_val);
- try {
- StringBuffer styleText = new StringBuffer(EMPTY_STRING);
- URL url = new URL((new Path(href_val)).toOSString());
- String fileName = url.getFile();
- BufferedReader in = new BufferedReader(new FileReader(
- (fileName)));
- String str = EMPTY_STRING;
- while ((str = in.readLine()) != null) {
- styleText.append(str);
- }
-
- String styleForParse = styleText.toString();
- styleForParse = VpeStyleUtil.addFullPathIntoURLValue(
- styleForParse, href_val);
-
- in.close();
- nsIDOMText textNode = visualDocument
- .createTextNode(styleForParse);
- linkNode.appendChild(textNode);
- return linkNode;
- } catch (FileNotFoundException fnfe) {
- /* File which was pointed by user is not exists. Do nothing. */
- } catch (IOException ioe) {
- VpePlugin.getPluginLog().logError(ioe.getMessage(), ioe);
- }
- }
-
- linkNode = visualDocument.createElement(HTML.TAG_LINK);
- linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_REL, rel_val);
- linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_HREF, href_val);
- linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_EXT, ext_val);
-
- return linkNode;
- }
-
- private boolean isLinkReplacer(nsIDOMNode node) {
- return HTML.TAG_STYLE.equalsIgnoreCase(node.getNodeName())
- && ATTR_VPE_INLINE_LINK_VALUE
- .equalsIgnoreCase(((nsIDOMElement) node
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
- .getAttribute(ATTR_VPE));
- }
-
- private nsIDOMNode getLinkNode(String href_val, String ext_val) {
- nsIDOMNodeList children = headNode.getChildNodes();
- long len = children.getLength();
- for (long i = len - 1; i >= 0; i--) {
- nsIDOMNode node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- if (HTML.TAG_LINK.equalsIgnoreCase(node.getNodeName())
- || isLinkReplacer(node)) {
- nsIDOMElement element = (nsIDOMElement) node
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- if (ext_val.equalsIgnoreCase(element
- .getAttribute(VpeTemplateManager.ATTR_LINK_EXT))
- && href_val
- .equalsIgnoreCase(element
- .getAttribute(VpeTemplateManager.ATTR_LINK_HREF))) {
- return node;
- }
- }
- }
- }
- return null;
- }
-
- private void cleanHead() {
- nsIDOMNodeList children = headNode.getChildNodes();
- long len = children.getLength();
- for (long i = len - 1; i >= 0; i--) {
- nsIDOMNode node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- String name = node.getNodeName();
- if (HTML.TAG_LINK.equalsIgnoreCase(name)
- || isLinkReplacer(node)) {
- if (NO_STRING.equalsIgnoreCase(((nsIDOMElement) node
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
- .getAttribute("ext"))) {
- // int linkAddress =
- // MozillaSupports.queryInterface(node,
- // nsIStyleSheetLinkingElement.NS_ISTYLESHEETLINKINGELEMENT_IID);
- // nsIStyleSheetLinkingElement linkingElement = new
- // nsIStyleSheetLinkingElement(linkAddress);
- // linkingElement.removeStyleSheet();
- node = headNode.removeChild(node);
- }
- } else if (HTML.TAG_STYLE.equalsIgnoreCase(node.getNodeName())
- && (!YES_STRING
- .equalsIgnoreCase(((nsIDOMElement) node
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
- .getAttribute(ATTR_VPE)))) {
- node = headNode.removeChild(node);
- }
- }
- }
- }
-
- private class PseudoInfo {
- private nsIDOMNode pseudoNode;
- private boolean isElements;
-
- private PseudoInfo() {
- this(null, false);
- }
-
- private PseudoInfo(nsIDOMNode pseudoNode, boolean isElements) {
- this.pseudoNode = pseudoNode;
- this.isElements = isElements;
- }
- }
-
- void showDragCaret(nsIDOMNode node, int offset) {
- xulRunnerEditor.showDragCaret(node, offset);
- }
-
- void hideDragCaret() {
-
- xulRunnerEditor.hideDragCaret();
- }
-
- private int getResizerConstrains(nsIDOMNode visualNode) {
- VpeNodeMapping nodeMapping = domMapping.getNodeMapping(visualNode);
- if (nodeMapping != null
- && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
- return ((VpeElementMapping) nodeMapping).getTemplate()
- .getTagDescription(pageContext,
- (Element) nodeMapping.getSourceNode(),
- visualDocument,
- (nsIDOMElement) nodeMapping.getVisualNode(),
- ((VpeElementMapping) nodeMapping).getData())
- .getResizeConstrains();
- }
- return VpeTagDescription.RESIZE_CONSTRAINS_NONE;
- }
-
- public void resize(nsIDOMElement element, int resizerConstrains, int top,
- int left, int width, int height) {
- VpeElementMapping elementMapping = (VpeElementMapping) domMapping
- .getNodeMapping(element);
- if (elementMapping != null) {
- elementMapping.getTemplate().resize(pageContext,
- (Element) elementMapping.getSourceNode(), visualDocument,
- element, elementMapping.getData(), resizerConstrains, top,
- left, width, height);
- }
- }
-
- static boolean isAnonElement(nsIDOMNode visualNode) {
- if (visualNode != null
- && visualNode.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- String attrValue = ((nsIDOMElement) visualNode
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
- .getAttribute(MOZ_ANONCLASS_ATTR);
-
- return attrValue != null && attrValue.length() > 0;
- }
-
- return false;
- }
-
- boolean canInnerDrag(nsIDOMElement visualDragElement) {
- VpeNodeMapping node = domMapping.getNodeMapping(visualDragElement);
- if (node instanceof VpeElementMapping) {
- VpeElementMapping elementMapping = (VpeElementMapping) node;
- if (elementMapping != null) {
- return elementMapping.getTemplate().canInnerDrag(pageContext,
- (Element) elementMapping.getSourceNode(),
- visualDocument, visualDragElement,
- elementMapping.getData());
- }
- }
- return false;
- }
-
- VpeSourceInnerDropInfo getSourceInnerDropInfo(Node sourceDragNode,
- VpeVisualInnerDropInfo visualDropInfo, boolean checkParentTemplates) {
- nsIDOMNode visualDropContainer = visualDropInfo.getDropContainer();
- long visualDropOffset = visualDropInfo.getDropOffset();
- Node sourceDropContainer = null;
- int sourceDropOffset = 0;
-
- switch (visualDropContainer.getNodeType()) {
- case nsIDOMNode.ELEMENT_NODE:
- nsIDOMNode visualOffsetNode = null;
- boolean afterFlag = false;
- long visualChildCount = VisualDomUtil
- .getChildCount(visualDropContainer);
- if (visualDropOffset < visualChildCount) {
- visualOffsetNode = VisualDomUtil.getChildNode(
- visualDropContainer, visualDropOffset);
- if (isPseudoElement(visualOffsetNode)
- || isAnonElement(visualOffsetNode)) {
- visualOffsetNode = getLastAppreciableVisualChild(visualDropContainer);
- afterFlag = true;
- }
- } else {
- visualOffsetNode = getLastAppreciableVisualChild(visualDropContainer);
- afterFlag = visualChildCount != 0;
- }
- if (visualOffsetNode != null) {
- Node sourceOffsetNode = domMapping
- .getSourceNode(visualOffsetNode);
- if (sourceOffsetNode != null) {
- sourceDropContainer = sourceOffsetNode.getParentNode();
- sourceDropOffset = ((NodeImpl) sourceOffsetNode).getIndex();
- if (afterFlag) {
- sourceDropOffset++;
- }
- }
- }
- if (sourceDropContainer == null) {
- sourceDropContainer = domMapping
- .getNearSourceNode(visualDropContainer);
- if (sourceDropContainer != null) {
- sourceDropOffset = sourceDropContainer.getChildNodes()
- .getLength();
- }
- }
- if (sourceDropContainer == null) {
- sourceDropContainer = domMapping
- .getNearSourceNode(visualContentArea);
- sourceDropOffset = sourceDropContainer.getChildNodes()
- .getLength();
- }
- break;
- case nsIDOMNode.TEXT_NODE:
- VpeNodeMapping nodeMapping = domMapping
- .getNearNodeMapping(visualDropContainer);
- switch (nodeMapping.getType()) {
- case VpeNodeMapping.TEXT_MAPPING:
- sourceDropContainer = nodeMapping.getSourceNode();
- sourceDropOffset = TextUtil.sourceInnerPosition(
- sourceDropContainer.getNodeValue(), visualDropOffset);
- break;
- case VpeNodeMapping.ELEMENT_MAPPING:
- // it's attribute
- if (isTextEditable(visualDropContainer)) {
- String[] atributeNames = ((VpeElementMapping) nodeMapping)
- .getTemplate().getOutputAtributeNames();
- if (atributeNames != null && atributeNames.length > 0) {
- Element sourceElement = (Element) nodeMapping
- .getSourceNode();
- sourceDropContainer = sourceElement
- .getAttributeNode(atributeNames[0]);
- sourceDropOffset = TextUtil.sourceInnerPosition(
- sourceDropContainer.getNodeValue(),
- visualDropOffset);
- }
- }
- nodeMapping.getVisualNode();
- }
- break;
- }
- if (sourceDropContainer != null) {
- return getSourceInnerDropInfo(sourceDragNode, sourceDropContainer,
- sourceDropOffset, checkParentTemplates);
- } else {
- return new VpeSourceInnerDropInfo(null, 0, false);
- }
- }
-
- VpeSourceInnerDropInfo getSourceInnerDropInfo(Node dragNode,
- Node container, int offset, boolean checkParentsTemplates) {
- // Thread.dumpStack();
- boolean canDrop = false;
- switch (container.getNodeType()) {
- case Node.ELEMENT_NODE:
- VpeNodeMapping nodeMapping = domMapping.getNodeMapping(container);
- if (nodeMapping != null
- && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
- canDrop = ((VpeElementMapping) nodeMapping).getTemplate()
- .canInnerDrop(pageContext, container, dragNode);
- }
- if (!canDrop) {
- if (!checkParentsTemplates)
- return new VpeSourceInnerDropInfo(container, offset,
- canDrop);
- // offset = ((NodeImpl)container).getIndex();
- // container = container.getParentNode();
- // TODO Max Areshkau unclear logic , if we can drop on element
- // why we trying to drop
- // this on parent
- // return getSourceInnerDropInfo(dragNode, container, offset,
- // false);
- return new VpeSourceInnerDropInfo(container, offset, canDrop);
- }
- break;
- case Node.TEXT_NODE:
- case Node.DOCUMENT_NODE:
- canDrop = true;
- break;
- case Node.ATTRIBUTE_NODE:
- canDrop = true;
- break;
- }
- if (canDrop) {
- return new VpeSourceInnerDropInfo(container, offset, canDrop);
- } else {
- return new VpeSourceInnerDropInfo(null, 0, canDrop);
- }
- }
-
- public void innerDrop(Node dragNode, Node container, int offset) {
- VpeNodeMapping mapping = domMapping.getNearNodeMapping(container);
- if (mapping != null) {
- nsIDOMNode visualDropContainer = mapping.getVisualNode();
- switch (mapping.getType()) {
- case VpeNodeMapping.TEXT_MAPPING:
- break;
- case VpeNodeMapping.ELEMENT_MAPPING:
- nsIDOMNode visualParent = visualDropContainer.getParentNode();
- VpeNodeMapping oldMapping = mapping;
- mapping = domMapping.getNearNodeMapping(visualParent);
- if (mapping != null
- && mapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
- ((VpeElementMapping) mapping).getTemplate()
- .innerDrop(
- pageContext,
- new VpeSourceInnerDragInfo(dragNode, 0, 0),
- new VpeSourceInnerDropInfo(container,
- offset, true));
- } else {
- ((VpeElementMapping) oldMapping).getTemplate()
- .innerDrop(
- pageContext,
- new VpeSourceInnerDragInfo(dragNode, 0, 0),
- new VpeSourceInnerDropInfo(container,
- offset, true));
- }
- }
-
- }
- }
-
- void innerDrop(VpeSourceInnerDragInfo dragInfo,
- VpeSourceInnerDropInfo dropInfo) {
- dropper.drop(pageContext, dragInfo, dropInfo);
- }
-
- nsIDOMElement getNearDragElement(Element visualElement) {
- VpeElementMapping elementMapping = domMapping
- .getNearElementMapping(visualElement);
- while (elementMapping != null) {
- if (canInnerDrag(elementMapping.getVisualElement())) {
- return elementMapping.getVisualElement();
- }
- elementMapping = domMapping.getNearElementMapping(elementMapping
- .getVisualNode().getParentNode());
- }
- return null;
- }
-
- nsIDOMElement getDragElement(nsIDOMElement visualElement) {
- VpeElementMapping elementMapping = domMapping
- .getNearElementMapping(visualElement);
- if (elementMapping != null
- && canInnerDrag(elementMapping.getVisualElement())) {
- return elementMapping.getVisualElement();
- }
- return null;
- }
-
- public boolean isTextEditable(nsIDOMNode visualNode) {
- if (visualNode != null) {
- nsIDOMNode parent = visualNode.getParentNode();
- if (parent != null
- && parent.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- nsIDOMElement element = (nsIDOMElement) parent
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- nsIDOMAttr style = element.getAttributeNode("style");
- if (style != null) {
- String styleValue = style.getNodeValue();
- String[] items = styleValue.split(";");
- for (int i = 0; i < items.length; i++) {
- String[] item = items[i].split(":");
- if ("-moz-user-modify".equals(item[0].trim())
- && "read-only".equals(item[1].trim())) {
- return false;
- }
- }
- }
- nsIDOMAttr classAttr = element.getAttributeNode("class");
- if (classAttr != null) {
- String classValue = classAttr.getNodeValue().trim();
- if ("__any__tag__caption".equals(classValue)) {
- return false;
- }
- }
- }
- }
- return true;
- }
-
- VpeVisualInnerDropInfo getInnerDropInfo(Node sourceDropContainer,
- int sourceDropOffset) {
- nsIDOMNode visualDropContainer = null;
- long visualDropOffset = 0;
-
- switch (sourceDropContainer.getNodeType()) {
- case Node.TEXT_NODE:
- visualDropContainer = domMapping.getVisualNode(sourceDropContainer);
- visualDropOffset = TextUtil.visualInnerPosition(sourceDropContainer
- .getNodeValue(), sourceDropOffset);
- break;
- case Node.ELEMENT_NODE:
- case Node.DOCUMENT_NODE:
- NodeList sourceChildren = sourceDropContainer.getChildNodes();
- if (sourceDropOffset < sourceChildren.getLength()) {
- Node sourceChild = sourceChildren.item(sourceDropOffset);
- nsIDOMNode visualChild = domMapping.getVisualNode(sourceChild);
- if (visualChild != null) {
- visualDropContainer = visualChild.getParentNode();
-
- visualDropOffset = VisualDomUtil.getOffset(visualChild);
- }
- }
- if (visualDropContainer == null) {
- visualDropContainer = domMapping
- .getNearVisualNode(sourceDropContainer);
- nsIDOMNode visualChild = getLastAppreciableVisualChild(visualDropContainer);
- if (visualChild != null) {
- visualDropOffset = VisualDomUtil.getOffset(visualChild) + 1;
- } else {
- visualDropOffset = 0;
- }
- }
- break;
- case Node.ATTRIBUTE_NODE:
- Element sourceElement = ((Attr) sourceDropContainer)
- .getOwnerElement();
- VpeElementMapping elementMapping = domMapping
- .getNearElementMapping(sourceElement);
- nsIDOMNode textNode = elementMapping.getTemplate()
- .getOutputTextNode(pageContext, sourceElement,
- elementMapping.getData());
- if (textNode != null) {
- visualDropContainer = textNode;
- visualDropOffset = TextUtil.visualInnerPosition(
- sourceDropContainer.getNodeValue(), sourceDropOffset);
- }
- break;
- }
- if (visualDropContainer == null) {
- return null;
- }
- return new VpeVisualInnerDropInfo(visualDropContainer,
- visualDropOffset, 0, 0);
- }
-
- protected void setTooltip(Element sourceElement, nsIDOMElement visualElement) {
- if (visualElement != null && sourceElement != null
- && !((ElementImpl) sourceElement).isJSPTag()) {
- if (HTML.TAG_HTML.equalsIgnoreCase(sourceElement.getNodeName()))
- return;
- String titleValue = getTooltip(sourceElement);
-
- if (titleValue != null) {
- titleValue = titleValue.replaceAll("&", "&");
- titleValue = titleValue.replaceAll("<", "<");
- titleValue = titleValue.replaceAll(">", ">");
- }
-
- if (titleValue != null) {
- // visualElement.setAttribute("title", titleValue);
- setTooltip(visualElement, titleValue);
- }
- }
- }
-
- protected void setTooltip(nsIDOMElement visualElement, String titleValue) {
- visualElement.setAttribute("title", titleValue);
- nsIDOMNodeList children = visualElement.getChildNodes();
- long len = children.getLength();
- for (long i = 0; i < len; i++) {
- nsIDOMNode child = children.item(i);
- if (child.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- setTooltip(((nsIDOMElement) child
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID)),
- titleValue);
- }
- }
- }
-
- private void resetTooltip(Element sourceElement, nsIDOMElement visualElement) {
- if (visualElement != null && sourceElement != null
- && !((ElementImpl) sourceElement).isJSPTag()) {
- if (HTML.TAG_HTML.equalsIgnoreCase(sourceElement.getNodeName()))
- return;
- String titleValue = getTooltip(sourceElement);
-
- if (titleValue != null) {
- titleValue = titleValue.replaceAll("&", "&");
- titleValue = titleValue.replaceAll("<", "<");
- titleValue = titleValue.replaceAll(">", ">");
- }
-
- if (titleValue != null) {
- resetTooltip(visualElement, titleValue);
- }
- }
- }
-
- private void resetTooltip(nsIDOMElement visualElement, String titleValue) {
- visualElement.setAttribute("title", titleValue);
- nsIDOMNodeList children = visualElement.getChildNodes();
- long len = children.getLength();
- for (long i = 0; i < len; i++) {
- nsIDOMNode child = children.item(i);
- if (child.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- if (domMapping.getNodeMapping(child) == null) {
- resetTooltip((nsIDOMElement) child
- .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID),
- titleValue);
- }
- }
- }
- }
-
- private String getTooltip(Element sourceElement) {
- StringBuffer buffer = new StringBuffer();
- buffer.append(sourceElement.getNodeName());
- NamedNodeMap attrs = sourceElement.getAttributes();
- int len = attrs.getLength();
- for (int i = 0; i < len; i++) {
- if (i == 7) {
- return buffer.append("\n\t... ").toString();
- }
- int valueLength = attrs.item(i).getNodeValue().length();
- if (valueLength > 30) {
- StringBuffer temp = new StringBuffer();
- temp.append(attrs.item(i).getNodeValue().substring(0, 15)
- + " ... "
- + attrs.item(i).getNodeValue().substring(
- valueLength - 15, valueLength));
- buffer.append("\n" + attrs.item(i).getNodeName() + ": " + temp);
- } else
- buffer.append("\n" + attrs.item(i).getNodeName() + ": "
- + attrs.item(i).getNodeValue());
-
- }
-
- return buffer.toString();
- }
-
- Rectangle getNodeBounds(nsIDOMNode visualNode) {
-
- return XulRunnerVpeUtils.getElementBounds(visualNode);
- }
-
- static boolean canInsertAfter(int x, int y, Rectangle rect) {
- if (y > (rect.y + rect.height) || x > (rect.x + rect.width)) {
- return true;
- }
- return y >= rect.x && x > (rect.x + rect.width / 2);
- }
-
- static nsIDOMNode getLastAppreciableVisualChild(nsIDOMNode visualParent) {
- nsIDOMNode visualLastChild = null;
- nsIDOMNodeList visualChildren = visualParent.getChildNodes();
- long len = visualChildren.getLength();
- for (long i = len - 1; i >= 0; i--) {
- nsIDOMNode visualChild = visualChildren.item(i);
- if (!isPseudoElement(visualChild) && !isAnonElement(visualChild)) {
- visualLastChild = visualChild;
- break;
- }
- }
- return visualLastChild;
- }
-
- void correctVisualDropPosition(VpeVisualInnerDropInfo newVisualDropInfo,
- VpeVisualInnerDropInfo oldVisualDropInfo) {
- nsIDOMNode newVisualDropContainer = newVisualDropInfo
- .getDropContainer();
- nsIDOMNode oldVisualDropContainer = oldVisualDropInfo
- .getDropContainer();
-
- if (newVisualDropContainer.equals(oldVisualDropContainer)) {
- newVisualDropInfo.setDropOffset(oldVisualDropInfo.getDropOffset());
- return;
- }
-
- nsIDOMNode child = oldVisualDropContainer;
- while (child != null && child.getNodeType() != Node.DOCUMENT_NODE) {
- nsIDOMNode parent = child.getParentNode();
- if (newVisualDropContainer.equals(parent)) {
- long offset = VisualDomUtil.getOffset(child);
- Rectangle rect = getNodeBounds(child);
- if (canInsertAfter(oldVisualDropInfo.getMouseX(),
- oldVisualDropInfo.getMouseY(), rect)) {
- offset++;
- }
- newVisualDropInfo.setDropOffset(offset);
- }
- child = parent;
- }
- }
-
- public nsIDOMRange createDOMRange() {
- return xulRunnerEditor.createDOMRange();
- }
-
- public nsIDOMRange createDOMRange(nsIDOMNode selectedNode) {
- nsIDOMRange range = createDOMRange();
- range.selectNode(selectedNode);
- return range;
- }
-
- public static boolean isIncludeElement(nsIDOMElement visualElement) {
- return YES_STRING.equalsIgnoreCase(visualElement
- .getAttribute(INCLUDE_ELEMENT_ATTR));
- }
-
- public static void markIncludeElement(nsIDOMElement visualElement) {
- visualElement.setAttribute(INCLUDE_ELEMENT_ATTR, YES_STRING);
- }
-
- protected void setReadOnlyElement(nsIDOMElement node) {
- String style = node.getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
- style = VpeStyleUtil.setParameterInStyle(style, "-moz-user-modify",
- "read-only");
- node.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
- }
-
- void setMoveCursor(nsIDOMMouseEvent mouseEvent) {
-
- nsIDOMElement selectedElement = xulRunnerEditor
- .getLastSelectedElement();
- if (selectedElement != null && canInnerDrag(selectedElement)) {
- String styleClasses = selectedElement.getAttribute(HTML.ATTR_CLASS);
- if (inDragArea(getNodeBounds(selectedElement), VisualDomUtil
- .getMousePoint(mouseEvent))) {
- // change cursor
- if (styleClasses == null
- || !(styleClasses.contains(ATTR_DRAG_AVAILABLE_CLASS))) {
- // change cursor style to move
- styleClasses = ATTR_DRAG_AVAILABLE_CLASS + " "
- + styleClasses;
- }
- } else {
- // change cursor style to normal
- if (styleClasses != null) {
-
- styleClasses = styleClasses.replaceAll(
- ATTR_DRAG_AVAILABLE_CLASS, "");
- }
- }
- selectedElement.setAttribute(HTML.ATTR_CLASS, styleClasses);
- }
- }
-
- private boolean inDragArea(Rectangle dragArea, Point mousePoint) {
- // TODO add drag and drop support
- return dragArea.contains(mousePoint)
- && mousePoint.x < (dragArea.x + DRAG_AREA_WIDTH)
- && mousePoint.y < (dragArea.y + DRAG_AREA_HEIGHT);
- }
-
- nsIDOMElement getDragElement(nsIDOMMouseEvent mouseEvent) {
-
- nsIDOMElement selectedElement = xulRunnerEditor
- .getLastSelectedElement();
- if (selectedElement != null && canInnerDrag(selectedElement)) {
- if (inDragArea(getNodeBounds(selectedElement), VisualDomUtil
- .getMousePoint(mouseEvent))) {
- return selectedElement;
- }
- }
- return null;
- }
-
- VpeSourceInnerDragInfo getSourceInnerDragInfo(
- VpeVisualInnerDragInfo visualDragInfo) {
- nsIDOMNode visualNode = visualDragInfo.getNode();
- int offset = visualDragInfo.getOffset();
- int length = visualDragInfo.getLength();
-
- VpeNodeMapping nodeMapping = domMapping.getNearNodeMapping(visualNode);
- Node sourceNode = nodeMapping.getSourceNode();
-
- if (sourceNode != null) {
- switch (sourceNode.getNodeType()) {
- case Node.TEXT_NODE:
- int end = TextUtil.sourceInnerPosition(visualNode
- .getNodeValue(), offset + length);
- offset = TextUtil.sourceInnerPosition(
- visualNode.getNodeValue(), offset);
- length = end - offset;
- break;
- case Node.ELEMENT_NODE:
- if (visualNode.getNodeType() == Node.TEXT_NODE) {
- // it's attribute
- sourceNode = null;
- if (isTextEditable(visualNode)) {
- String[] atributeNames = ((VpeElementMapping) nodeMapping)
- .getTemplate().getOutputAtributeNames();
- if (atributeNames != null && atributeNames.length > 0) {
- Element sourceElement = (Element) nodeMapping
- .getSourceNode();
- sourceNode = sourceElement
- .getAttributeNode(atributeNames[0]);
- end = TextUtil.sourceInnerPosition(visualNode
- .getNodeValue(), offset + length);
- offset = TextUtil.sourceInnerPosition(visualNode
- .getNodeValue(), offset);
- length = end - offset;
- }
- }
- }
- break;
- }
- }
- return new VpeSourceInnerDragInfo(sourceNode, offset, length);
- }
-
- public nsIDOMText getOutputTextNode(Attr attr) {
- Element sourceElement = ((Attr) attr).getOwnerElement();
- VpeElementMapping elementMapping = domMapping
- .getNearElementMapping(sourceElement);
- if (elementMapping != null) {
- return elementMapping.getTemplate().getOutputTextNode(pageContext,
- sourceElement, elementMapping.getData());
- }
- return null;
- }
-
- nsIDOMElement getLastSelectedElement() {
-
- return xulRunnerEditor.getLastSelectedElement();
- }
-
- public void pushIncludeStack(VpeIncludeInfo includeInfo) {
- includeStack.add(includeInfo);
- }
-
- public VpeIncludeInfo popIncludeStack() {
- VpeIncludeInfo includeInfo = null;
- if (includeStack.size() > 0) {
- includeInfo = (VpeIncludeInfo) includeStack.remove(includeStack
- .size() - 1);
- }
- return includeInfo;
- }
-
- public boolean isFileInIncludeStack(IFile file) {
- if (file == null)
- return false;
- for (int i = 0; i < includeStack.size(); i++) {
- if (file.equals(((VpeIncludeInfo) includeStack.get(i)).getFile())) {
- return true;
- }
- }
- return false;
- }
-
- protected boolean isCurrentMainDocument() {
- return includeStack.size() <= 1;
- }
-
- public int getCurrentMainIncludeOffset() {
- if (includeStack.size() <= 1)
- return -1;
- VpeIncludeInfo info = (VpeIncludeInfo) includeStack.get(1);
- return ((IndexedRegion) info.getElement()).getStartOffset();
- }
-
- public VpeIncludeInfo getCurrentIncludeInfo() {
- if (includeStack.size() <= 0)
- return null;
- return (VpeIncludeInfo) includeStack.get(includeStack.size() - 1);
- }
-
- public VpeIncludeInfo getRootIncludeInfo() {
- if (includeStack.size() <= 1)
- return null;
- return (VpeIncludeInfo) includeStack.get(1);
- }
-
- void dispose() {
- cleanHead();
- domMapping.clear(visualContentArea);
- pageContext.dispose();
- }
-
- protected Map createXmlns(Element sourceNode) {
- NamedNodeMap attrs = ((Element) sourceNode).getAttributes();
- if (attrs != null) {
- Map xmlnsMap = new HashMap();
- for (int i = 0; i < attrs.getLength(); i++) {
- addTaglib(sourceNode, xmlnsMap, attrs.item(i).getNodeName(),
- true);
- }
- if (xmlnsMap.size() > 0) {
- return xmlnsMap;
- }
- }
- return null;
- }
-
- private void setXmlnsAttribute(VpeElementMapping elementMapping,
- String name, String value) {
- Element sourceElement = (Element) elementMapping.getSourceNode();
- if (sourceElement != null) {
- Map xmlnsMap = elementMapping.getXmlnsMap();
- if (xmlnsMap == null)
- xmlnsMap = new HashMap();
- addTaglib(sourceElement, xmlnsMap, name, true);
- elementMapping.setXmlnsMap(xmlnsMap.size() > 0 ? xmlnsMap : null);
- }
- }
-
- private void removeXmlnsAttribute(VpeElementMapping elementMapping,
- String name) {
- Element sourceElement = (Element) elementMapping.getSourceNode();
- if (sourceElement != null) {
- Map xmlnsMap = elementMapping.getXmlnsMap();
- if (xmlnsMap != null) {
- Object id = xmlnsMap.remove(name);
- if (id != null) {
- pageContext.setTaglib(((Integer) id).intValue(), null,
- null, true);
- elementMapping.setXmlnsMap(xmlnsMap.size() > 0 ? xmlnsMap
- : null);
- }
- }
- }
- }
-
- private void addTaglib(Element sourceElement, Map xmlnsMap,
- String attrName, boolean ns) {
- Attr attr = sourceElement.getAttributeNode(attrName);
- if (ATTR_XMLNS.equals(attr.getPrefix())) {
- xmlnsMap.put(attr.getNodeName(), Integer.valueOf(attr.hashCode()));
- pageContext.setTaglib(attr.hashCode(), attr.getNodeValue(), attr
- .getLocalName(), ns);
- }
- }
-
- /**
- * @return the dnd
- */
- public VpeDnD getDnd() {
-
- return dnd;
- }
-
- /**
- * @param dnd
- * the dnd to set
- */
- public void setDnd(VpeDnD dnd) {
-
- this.dnd = dnd;
- }
-
- /**
- * @return the pageContext
- */
- protected VpePageContext getPageContext() {
- return pageContext;
- }
-
- /**
- * @param pageContext
- * the pageContext to set
- */
- protected void setPageContext(VpePageContext pageContext) {
- this.pageContext = pageContext;
- }
-
- /**
- * @return the visualDocument
- */
- protected nsIDOMDocument getVisualDocument() {
- return visualDocument;
- }
-
- /**
- * @param visualDocument
- * the visualDocument to set
- */
- protected void setVisualDocument(nsIDOMDocument visualDocument) {
- this.visualDocument = visualDocument;
- }
-
- /**
- * Check this file is facelet
- *
- * @return this if file is facelet, otherwize false
- */
- private boolean isFacelet() {
- boolean isFacelet = false;
-
- IEditorInput iEditorInput = pageContext.getEditPart().getEditorInput();
- if (iEditorInput instanceof IFileEditorInput) {
- IFileEditorInput iFileEditorInput = (IFileEditorInput) iEditorInput;
-
- IFile iFile = iFileEditorInput.getFile();
-
- IProject project = iFile.getProject();
- IModelNature nature = EclipseResourceUtil.getModelNature(project);
- if (nature != null) {
- XModel model = nature.getModel();
- XModelObject webXML = WebAppHelper.getWebApp(model);
- XModelObject param = WebAppHelper.findWebAppContextParam(
- webXML, "javax.faces.DEFAULT_SUFFIX");
- if (param != null) {
- String value = param.getAttributeValue("param-value");
-
- if (value.length() != 0 && iFile.getName().endsWith(value)) {
- isFacelet = true;
- }
- }
- }
- }
-
- return isFacelet;
- }
-
- /**
- * Create a visual element for text node
- *
- * @param sourceNode
- * @param registerFlag
- * @return a visual element for text node
- */
-
- protected nsIDOMNode createTextNode(Node sourceNode, boolean registerFlag) {
- String sourceText = sourceNode.getNodeValue();
- if (sourceText.trim().length() <= 0) {
- registerNodes(new VpeNodeMapping(sourceNode, null));
- return null;
- }
-
- if (faceletFile) {
- Matcher matcher_EL = REGEX_EL.matcher(sourceText);
- if (matcher_EL.find()) {
- BundleMap bundle = pageContext.getBundle();
- int offset = pageContext.getVisualBuilder()
- .getCurrentMainIncludeOffset();
- if (offset == -1)
- offset = ((IndexedRegion) sourceNode).getStartOffset();
- String jsfValue = bundle.getBundleValue(sourceText, offset);
- sourceText = jsfValue;
- }
- }
- String visualText = TextUtil.visualText(sourceText);
-
- nsIDOMNode visualNewTextNode = visualDocument
- .createTextNode(visualText);
- nsIDOMElement element = visualDocument.createElement(HTML.TAG_SPAN);
- element.appendChild(visualNewTextNode);
- if (registerFlag) {
- registerNodes(new VpeNodeMapping(sourceNode, element));
- }
-
- return element;
- }
-
- /**
- * @return the xulRunnerEditor
- */
- public XulRunnerEditor getXulRunnerEditor() {
- return xulRunnerEditor;
- }
-
- /**
- * @param xulRunnerEditor
- * the xulRunnerEditor to set
- */
- public void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
- this.xulRunnerEditor = xulRunnerEditor;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+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.regex.Matcher;
+import java.util.regex.Pattern;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter;
+import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier;
+import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.eclipse.wst.xml.core.internal.document.NodeImpl;
+import org.jboss.tools.common.model.XModel;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.project.IModelNature;
+import org.jboss.tools.common.model.util.EclipseResourceUtil;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.jst.web.model.helpers.WebAppHelper;
+import org.jboss.tools.vpe.VpeDebug;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.dnd.VpeDnD;
+import org.jboss.tools.vpe.editor.bundle.BundleMap;
+import org.jboss.tools.vpe.editor.context.VpePageContext;
+import org.jboss.tools.vpe.editor.css.CSSReferenceList;
+import org.jboss.tools.vpe.editor.css.ResourceReference;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeElementMapping;
+import org.jboss.tools.vpe.editor.mapping.VpeNodeMapping;
+import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
+import org.jboss.tools.vpe.editor.template.VpeChildrenInfo;
+import org.jboss.tools.vpe.editor.template.VpeCreationData;
+import org.jboss.tools.vpe.editor.template.VpeCreatorUtil;
+import org.jboss.tools.vpe.editor.template.VpeDefaultPseudoContentCreator;
+import org.jboss.tools.vpe.editor.template.VpeTagDescription;
+import org.jboss.tools.vpe.editor.template.VpeTemplate;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.jboss.tools.vpe.editor.template.VpeToggableTemplate;
+import org.jboss.tools.vpe.editor.template.dnd.VpeDnd;
+import org.jboss.tools.vpe.editor.util.HTML;
+import org.jboss.tools.vpe.editor.util.TextUtil;
+import org.jboss.tools.vpe.editor.util.VisualDomUtil;
+import org.jboss.tools.vpe.editor.util.VpeStyleUtil;
+import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
+import org.jboss.tools.vpe.xulrunner.editor.XulRunnerVpeUtils;
+import org.mozilla.interfaces.nsIDOMAttr;
+import org.mozilla.interfaces.nsIDOMDocument;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMHTMLInputElement;
+import org.mozilla.interfaces.nsIDOMMouseEvent;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.mozilla.interfaces.nsIDOMNodeList;
+import org.mozilla.interfaces.nsIDOMRange;
+import org.mozilla.interfaces.nsIDOMText;
+import org.mozilla.xpcom.XPCOMException;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.eclipse.jface.text.IDocument;
+public class VpeVisualDomBuilder extends VpeDomBuilder {
+ /** REGEX_EL */
+ private static final Pattern REGEX_EL = Pattern.compile(
+ "[\\$|\\#]\\{.*\\}", Pattern.MULTILINE + Pattern.DOTALL);
+
+ private static final String PSEUDO_ELEMENT = "br";
+ private static final String PSEUDO_ELEMENT_ATTR = "vpe:pseudo-element";
+ private static final String INIT_ELEMENT_ATTR = "vpe:init-element";
+ private static final String MOZ_ANONCLASS_ATTR = "_MOZ_ANONCLASS";
+ private static final String COMMENT_STYLE = "font-style:italic; color:green";
+ private static final String COMMENT_PREFIX = "";
+ private static final String COMMENT_SUFFIX = "";
+ private static final String INCLUDE_ELEMENT_ATTR = "vpe:include-element";
+ private static final int DRAG_AREA_WIDTH = 10;
+ private static final int DRAG_AREA_HEIGHT = 10;
+ private static final String ATTR_XMLNS = "xmlns";
+ private static final String ATTR_DRAG_AVAILABLE_CLASS = "__drag__available_style";
+
+ private MozillaEditor visualEditor;
+ private XulRunnerEditor xulRunnerEditor;
+ private nsIDOMDocument visualDocument;
+ private nsIDOMElement visualContentArea;
+ private VpePageContext pageContext;
+ private VpeDnD dnd;
+ private nsIDOMNode headNode;
+ private List includeStack;
+ boolean rebuildFlag = false;
+
+ /** faceletFile */
+ private boolean faceletFile = false;
+
+ private static final String ATTR_VPE = "vpe";
+ private static final String ATTR_VPE_INLINE_LINK_VALUE = "inlinelink";
+
+ private static final String ATTR_REL_STYLESHEET_VALUE = "stylesheet";
+
+ private static final String YES_STRING = "yes";
+ private static final String NO_STRING = "no";
+ private static final String ZERO_STRING = "0";
+ private static final String EMPTY_STRING = "";
+
+ private static final String ATRIBUTE_BORDER = "border";
+ private static final String ATRIBUTE_CELLSPACING = "cellspacing";
+ private static final String ATRIBUTE_CELLPADDING = "cellpadding";
+
+ private static final String DOTTED_BORDER_STYLE = "border : 1px dotted #808080";
+ private static final String DOTTED_BORDER_STYLE_FOR_IMG = "1px dotted #808080";
+ private static final String DOTTED_BORDER_STYLE_FOR_TD = "border-left : 1px dotted #808080; border-right : 1px dotted #808080; border-top : 1px dotted #808080; border-bottom : 0px; color:#0051DD; background-color:#ECF3FF; padding-left: 3px; padding-right: 3px; line-height : 10px; font-family : arial; font-size : 10px; text-align:top; margin : 1px; -moz-user-modify : read-only";
+ private static final String DOTTED_BORDER_STYLE_FOR_SPAN = "border : 1px solid #0051DD; color:#0051DD; background-color:#ECF3FF; padding-left: 3px; padding-right: 3px; line-height : 10px; font-family : arial; font-size : 10px; text-align:top; margin : 1px; -moz-user-modify : read-only";
+
+ static private HashSet<String> unborderedSourceNodes = new HashSet<String>();
+ static {
+ unborderedSourceNodes.add(HTML.TAG_HTML);
+ unborderedSourceNodes.add(HTML.TAG_HEAD);
+ unborderedSourceNodes.add(HTML.TAG_BODY);
+ }
+
+ static private HashSet<String> unborderedVisualNodes = new HashSet<String>();
+ static {
+ unborderedVisualNodes.add(HTML.TAG_TBODY);
+ unborderedVisualNodes.add(HTML.TAG_THEAD);
+ unborderedVisualNodes.add(HTML.TAG_TR);
+ unborderedVisualNodes.add(HTML.TAG_TD);
+ unborderedVisualNodes.add(HTML.TAG_COL);
+ unborderedVisualNodes.add(HTML.TAG_COLS);
+ unborderedVisualNodes.add(HTML.TAG_COLGROUP);
+ unborderedVisualNodes.add(HTML.TAG_LI);
+ unborderedVisualNodes.add(HTML.TAG_BR);
+ }
+ private VpeDnd dropper;
+
+ private Map<IFile,Document> includeDocuments = new HashMap<IFile, Document>();
+
+ public VpeVisualDomBuilder(VpeDomMapping domMapping,
+ INodeAdapter sorceAdapter, VpeTemplateManager templateManager,
+ MozillaEditor visualEditor, VpePageContext pageContext) {
+ super(domMapping, sorceAdapter, templateManager);
+ this.visualEditor = visualEditor;
+ xulRunnerEditor = visualEditor.getXulRunnerEditor();
+ this.visualDocument = visualEditor.getDomDocument();
+ this.visualContentArea = visualEditor.getContentArea();
+ this.dnd = new VpeDnD();
+ this.pageContext = pageContext;
+ this.headNode = visualEditor.getHeadNode();
+ dropper = new VpeDnd();
+ dropper.setDndData(false, true);
+
+ if (isFacelet()) {
+ faceletFile = true;
+ } else {
+ faceletFile = false;
+ }
+
+ }
+
+ public void buildDom(Document sourceDocument) {
+ VpeSourceDomBuilder sourceBuilder = pageContext.getSourceBuilder();
+ IDocument document = sourceBuilder.getStructuredTextViewer()
+ .getDocument();
+ if (document == null)
+ return;
+ includeStack = new ArrayList();
+ IEditorInput input = pageContext.getEditPart().getEditorInput();
+ if (input instanceof IFileEditorInput) {
+ IFile file = ((IFileEditorInput) input).getFile();
+ if (file != null) {
+ includeStack.add(new VpeIncludeInfo(null, file, pageContext
+ .getSourceBuilder().getSourceDocument()));
+ }
+ }
+ pageContext.refreshConnector();
+ pageContext.installIncludeElements();
+ addChildren(null, sourceDocument, visualContentArea);
+ registerNodes(new VpeNodeMapping(sourceDocument, visualContentArea));
+ }
+
+ public void rebuildDom(Document sourceDocument) {
+ //clearIncludeDocuments();
+ cleanHead();
+ domMapping.clear(visualContentArea);
+ super.dispose();
+
+ pageContext.clearAll();
+ refreshExternalLinks();
+ pageContext.getBundle().refreshRegisteredBundles();
+ nsIDOMNodeList children = visualContentArea.getChildNodes();
+ long len = children.getLength();
+ for (long i = len - 1; i >= 0; i--) {
+ visualContentArea.removeChild(children.item(i));
+ }
+
+ if (sourceDocument != null) {
+ buildDom(sourceDocument);
+ }
+
+ rebuildFlag = true;
+ }
+
+ // temporary, will be change to prefference's variable
+ // private boolean borderVisible = true;
+
+ private boolean addNode(Node sourceNode, nsIDOMNode visualNextNode,
+ nsIDOMNode visualContainer) {
+ nsIDOMNode visualNewNode = createNode(sourceNode, visualContainer);
+ // Fix for JBIDE-1097
+ try {
+ if (visualNewNode != null) {
+ nsIDOMHTMLInputElement iDOMInputElement = (nsIDOMHTMLInputElement) visualNewNode
+ .queryInterface(nsIDOMHTMLInputElement.NS_IDOMHTMLINPUTELEMENT_IID);
+ iDOMInputElement.setReadOnly(true);
+ }
+ } catch (XPCOMException ex) {
+ // just ignore this exception
+ }
+ if (visualNewNode != null) {
+ if (visualNextNode == null) {
+ visualContainer.appendChild(visualNewNode);
+ } else {
+ visualContainer.insertBefore(visualNewNode, visualNextNode);
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ private nsIDOMElement createBorder(Node sourceNode,
+ nsIDOMElement visualNode, boolean block) {
+ nsIDOMElement border = null;
+ if (visualNode == null)
+ return null;
+ if (unborderedSourceNodes.contains(sourceNode.getNodeName()
+ .toLowerCase()))
+ return null;
+ if (unborderedVisualNodes.contains(visualNode.getNodeName()
+ .toLowerCase()))
+ return null;
+ if (HTML.TAG_IMG.equalsIgnoreCase(visualNode.getNodeName())) {
+ String width = visualNode.getAttribute(ATRIBUTE_BORDER);
+ if (width == null || ZERO_STRING.equalsIgnoreCase(width)
+ || EMPTY_STRING.equalsIgnoreCase(width)) {
+ String style = visualNode
+ .getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
+ style = VpeStyleUtil.setParameterInStyle(style,
+ ATRIBUTE_BORDER, DOTTED_BORDER_STYLE_FOR_IMG);
+ visualNode.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
+ }
+ return null;
+ }
+ if (block) {
+ if (YES_STRING.equals(VpePreference.USE_DETAIL_BORDER.getValue())) {
+ border = visualDocument.createElement(HTML.TAG_TABLE);
+ border.setAttribute(ATRIBUTE_CELLSPACING, ZERO_STRING);
+ border.setAttribute(ATRIBUTE_CELLPADDING, ZERO_STRING);
+
+ nsIDOMElement tr1 = visualDocument.createElement(HTML.TAG_TR);
+ border.appendChild(tr1);
+ nsIDOMElement td1 = visualDocument.createElement(HTML.TAG_TD);
+ td1.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
+ DOTTED_BORDER_STYLE_FOR_TD);
+ nsIDOMText text = visualDocument.createTextNode(sourceNode
+ .getNodeName());
+ td1.appendChild(text);
+ tr1.appendChild(td1);
+ nsIDOMElement tr2 = visualDocument.createElement(HTML.TAG_TR);
+ border.appendChild(tr2);
+ nsIDOMElement td2 = visualDocument.createElement(HTML.TAG_TD);
+ tr2.appendChild(td2);
+ nsIDOMElement p = visualDocument.createElement(HTML.TAG_P);
+ p.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
+ DOTTED_BORDER_STYLE);
+ td2.appendChild(p);
+
+ p.appendChild(visualNode);
+
+ } else {
+ border = visualDocument.createElement(HTML.TAG_TABLE);
+ border.setAttribute(ATRIBUTE_CELLSPACING, ZERO_STRING);
+ border.setAttribute(ATRIBUTE_CELLPADDING, ZERO_STRING);
+
+ nsIDOMElement tr2 = visualDocument.createElement(HTML.TAG_TR);
+ border.appendChild(tr2);
+ nsIDOMElement td2 = visualDocument.createElement(HTML.TAG_TD);
+ tr2.appendChild(td2);
+ nsIDOMElement p = visualDocument.createElement(HTML.TAG_P);
+ p.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
+ DOTTED_BORDER_STYLE);
+ td2.appendChild(p);
+
+ p.appendChild(visualNode);
+ }
+ } else {
+ border = visualDocument.createElement(HTML.TAG_SPAN);
+ border.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
+ DOTTED_BORDER_STYLE);
+ if (YES_STRING.equals(VpePreference.USE_DETAIL_BORDER.getValue())) {
+ nsIDOMElement name = visualDocument
+ .createElement(HTML.TAG_SPAN);
+ name.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE,
+ DOTTED_BORDER_STYLE_FOR_SPAN);
+ nsIDOMText text = visualDocument.createTextNode(sourceNode
+ .getNodeName());
+ name.appendChild(text);
+ border.appendChild(name);
+ }
+ border.appendChild(visualNode);
+ }
+ if (VpeStyleUtil.getAbsolute((Element) sourceNode) && border != null) {
+ int top = VpeStyleUtil.getSizeFromStyle((Element) sourceNode,
+ VpeStyleUtil.ATTRIBUTE_STYLE + VpeStyleUtil.DOT_STRING
+ + VpeStyleUtil.PARAMETER_TOP);
+ int left = VpeStyleUtil.getSizeFromStyle((Element) sourceNode,
+ VpeStyleUtil.ATTRIBUTE_STYLE + VpeStyleUtil.DOT_STRING
+ + VpeStyleUtil.PARAMETER_LEFT);
+
+ String style = visualNode
+ .getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
+ style = VpeStyleUtil.deleteFromString(style,
+ VpeStyleUtil.PARAMETER_POSITION,
+ VpeStyleUtil.SEMICOLON_STRING);
+ style = VpeStyleUtil.deleteFromString(style,
+ VpeStyleUtil.PARAMETER_TOP, VpeStyleUtil.SEMICOLON_STRING);
+ style = VpeStyleUtil.deleteFromString(style,
+ VpeStyleUtil.PARAMETER_LEFT, VpeStyleUtil.SEMICOLON_STRING);
+ visualNode.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
+
+ style = border.getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
+ style = VpeStyleUtil.setAbsolute(style);
+ if (top != -1)
+ style = VpeStyleUtil.setSizeInStyle(style,
+ VpeStyleUtil.PARAMETER_TOP, top);
+ if (left != -1)
+ style = VpeStyleUtil.setSizeInStyle(style,
+ VpeStyleUtil.PARAMETER_LEFT, left);
+ border.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
+ }
+ return border;
+ }
+
+ protected nsIDOMNode createNode(Node sourceNode,
+ nsIDOMNode visualOldContainer) {
+ boolean registerFlag = isCurrentMainDocument();
+ switch (sourceNode.getNodeType()) {
+ case Node.ELEMENT_NODE:
+ Map<?, ?> xmlnsMap = createXmlns((Element) sourceNode);
+ Set<Node> ifDependencySet = new HashSet<Node>();
+ pageContext.setCurrentVisualNode(visualOldContainer);
+ VpeTemplate template = templateManager.getTemplate(pageContext,
+ (Element) sourceNode, ifDependencySet);
+
+ VpeCreationData creationData = null;
+ //FIX FOR JBIDE-1568, added by Max Areshkau
+ try {
+ creationData = template.create(getPageContext(), sourceNode, getVisualDocument());
+ }catch (XPCOMException ex) {
+ VpePlugin.getPluginLog().logError(ex);
+ VpeTemplate defTemplate = templateManager.getDefTemplate();
+ creationData = defTemplate.create(getPageContext(), sourceNode, getVisualDocument());
+ }
+ pageContext.setCurrentVisualNode(null);
+ nsIDOMElement visualNewElement = (nsIDOMElement) creationData
+ .getNode();
+
+ if (visualNewElement != null)
+ correctVisualAttribute(visualNewElement);
+
+ nsIDOMElement border = null;
+ setTooltip((Element) sourceNode, visualNewElement);
+ if (YES_STRING.equals(VpePreference.SHOW_BORDER_FOR_ALL_TAGS
+ .getValue())
+ && visualNewElement != null) {
+ boolean block = true;
+ if (template.getTagDescription(null, null, null,
+ visualNewElement, null).getDisplayType() == VpeTagDescription.DISPLAY_TYPE_INLINE) {
+ block = false;
+ }
+ border = createBorder(sourceNode, visualNewElement, block);
+ }
+ if (!isCurrentMainDocument() && visualNewElement != null) {
+ setReadOnlyElement(visualNewElement);
+ }
+ if (registerFlag) {
+ VpeElementMapping elementMapping = new VpeElementMapping(
+ (Element) sourceNode, visualNewElement, border,
+ template, ifDependencySet, creationData.getData());
+ elementMapping.setXmlnsMap(xmlnsMap);
+ registerNodes(elementMapping);
+ }
+ if (template.isChildren()) {
+ List<?> childrenInfoList = creationData.getChildrenInfoList();
+ if (childrenInfoList == null) {
+ addChildren(template, sourceNode,
+ visualNewElement != null ? visualNewElement
+ : visualOldContainer);
+ } else {
+ addChildren(template, sourceNode, visualOldContainer,
+ childrenInfoList);
+ }
+ }
+ pageContext.setCurrentVisualNode(visualOldContainer);
+ template.validate(pageContext, (Element) sourceNode,
+ visualDocument, creationData);
+ pageContext.setCurrentVisualNode(null);
+ if (border != null)
+ return border;
+ else
+ return visualNewElement;
+ case Node.TEXT_NODE:
+ return createTextNode(sourceNode, registerFlag);
+ case Node.COMMENT_NODE:
+ if (!YES_STRING.equals(VpePreference.SHOW_COMMENTS.getValue())) {
+ return null;
+ }
+ nsIDOMElement visualNewComment = createComment(sourceNode);
+ if (registerFlag) {
+ registerNodes(new VpeNodeMapping(sourceNode, visualNewComment));
+ }
+ return visualNewComment;
+ }
+ return null;
+ }
+
+ private void correctVisualAttribute(nsIDOMElement element) {
+
+ String styleValue = element.getAttribute(HTML.TAG_STYLE);
+ String backgroundValue = element
+ .getAttribute(VpeStyleUtil.PARAMETR_BACKGROND);
+
+ if (styleValue != null) {
+ styleValue = VpeStyleUtil.addFullPathIntoURLValue(styleValue,
+ pageContext.getEditPart().getEditorInput());
+ element.setAttribute(HTML.TAG_STYLE, styleValue);
+ }
+ if (backgroundValue != null) {
+ backgroundValue = VpeStyleUtil
+ .addFullPathIntoBackgroundValue(backgroundValue,
+ pageContext.getEditPart().getEditorInput());
+ element.setAttribute(VpeStyleUtil.PARAMETR_BACKGROND,
+ backgroundValue);
+ }
+ }
+
+ protected nsIDOMElement createComment(Node sourceNode) {
+ nsIDOMElement div = visualDocument.createElement(HTML.TAG_DIV);
+ div.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, COMMENT_STYLE);
+ String value = COMMENT_PREFIX + sourceNode.getNodeValue()
+ + COMMENT_SUFFIX;
+ nsIDOMText text = visualDocument.createTextNode(value);
+ div.appendChild(text);
+ return div;
+ }
+
+ protected void addChildren(VpeTemplate containerTemplate,
+ Node sourceContainer, nsIDOMNode visualContainer) {
+ NodeList sourceNodes = sourceContainer.getChildNodes();
+ int len = sourceNodes.getLength();
+ int childrenCount = 0;
+ for (int i = 0; i < len; i++) {
+ Node sourceNode = sourceNodes.item(i);
+ if (addNode(sourceNode, null, visualContainer)) {
+ childrenCount++;
+ }
+ }
+ if (childrenCount == 0) {
+ setPseudoContent(containerTemplate, sourceContainer,
+ visualContainer);
+ }
+ }
+
+ protected void addChildren(VpeTemplate containerTemplate,
+ Node sourceContainer, nsIDOMNode visualOldContainer,
+ List<?> childrenInfoList) {
+ for (int i = 0; i < childrenInfoList.size(); i++) {
+ VpeChildrenInfo info = (VpeChildrenInfo) childrenInfoList.get(i);
+ nsIDOMNode visualParent = info.getVisualParent();
+ if (visualParent == null)
+ visualParent = visualOldContainer;
+ List<?> sourceChildren = info.getSourceChildren();
+ int childrenCount = 0;
+ if (sourceChildren != null) {
+ for (int j = 0; j < sourceChildren.size(); j++) {
+ if (addNode((Node) sourceChildren.get(j), null,
+ visualParent)) {
+ childrenCount++;
+ }
+ }
+ }
+ if (childrenCount == 0 && childrenInfoList.size() == 0) {
+ setPseudoContent(containerTemplate, sourceContainer,
+ visualParent);
+ }
+ }
+ }
+
+ // /////////////////////////////////////////////////////////////////////////
+ public nsIDOMNode addStyleNodeToHead(String styleText) {
+ nsIDOMNode newStyle = visualDocument
+ .createElement(VpeStyleUtil.ATTRIBUTE_STYLE);
+
+ if (styleText != null) {
+ nsIDOMText newText = visualDocument.createTextNode(styleText);
+ newStyle.appendChild(newText);
+ }
+ headNode.appendChild(newStyle);
+ return newStyle;
+ }
+
+ public nsIDOMNode replaceStyleNodeToHead(nsIDOMNode oldStyleNode,
+ String styleText) {
+ nsIDOMElement newStyle = visualDocument
+ .createElement(VpeStyleUtil.ATTRIBUTE_STYLE);
+
+ if (styleText != null) {
+ nsIDOMNode newText = visualDocument.createTextNode(styleText);
+ newStyle.appendChild(newText);
+ }
+
+ headNode.replaceChild(newStyle, oldStyleNode);
+ return newStyle;
+ }
+
+ public void removeStyleNodeFromHead(nsIDOMNode oldStyleNode) {
+ headNode.removeChild(oldStyleNode);
+ }
+
+ void addExternalLinks() {
+ IEditorInput input = pageContext.getEditPart().getEditorInput();
+ IFile file = null;
+ if (input instanceof IFileEditorInput) {
+ file = ((IFileEditorInput) input).getFile();
+ }
+ ResourceReference[] l = null;
+ if (file != null) {
+ l = CSSReferenceList.getInstance().getAllResources(file);
+ }
+ if (l != null) {
+ for (int i = 0; i < l.length; i++) {
+ ResourceReference item = l[i];
+ addLinkNodeToHead("file:///" + item.getLocation(), YES_STRING);
+ }
+ }
+ }
+
+ void removeExternalLinks() {
+ nsIDOMNodeList childs = headNode.getChildNodes();
+ long length = childs.getLength();
+ for (long i = length - 1; i >= 0; i--) {
+ nsIDOMNode node = childs.item(i);
+ if (node.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ boolean isLink = false;
+ boolean isStyle = false;
+ if ((isLink = HTML.TAG_LINK
+ .equalsIgnoreCase(node.getNodeName()))
+ || (isStyle = HTML.TAG_STYLE.equalsIgnoreCase(node
+ .getNodeName()))) {
+ nsIDOMElement element = (nsIDOMElement) node
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ if ((isLink || (isStyle && ATTR_VPE_INLINE_LINK_VALUE
+ .equalsIgnoreCase(element.getAttribute(ATTR_VPE))))
+ && YES_STRING.equalsIgnoreCase(element
+ .getAttribute("ext"))) {
+ headNode.removeChild(node);
+ }
+ }
+ }
+ }
+ }
+
+ void refreshExternalLinks() {
+ removeExternalLinks();
+ addExternalLinks();
+ }
+
+ // ==========================================================
+ void resetPseudoElement(nsIDOMNode visualNode) {
+ if (visualNode != null) {
+ nsIDOMNode visualParent = visualNode.getParentNode();
+ if (visualParent != null) {
+ PseudoInfo info = getPseudoInfo(visualParent);
+ if (info.pseudoNode == null && !info.isElements) {
+ addPseudoElementImpl(visualParent);
+ } else if (info.pseudoNode != null && info.isElements) {
+ visualParent.removeChild(info.pseudoNode);
+ }
+ }
+ }
+ }
+
+ private PseudoInfo getPseudoInfo(nsIDOMNode visualParent) {
+ nsIDOMNode pseudoNode = null;
+ boolean isElements = false;
+
+ if (visualParent == null)
+ return new PseudoInfo();
+ nsIDOMNodeList visualNodes = visualParent.getChildNodes();
+ if (visualNodes == null)
+ return new PseudoInfo();
+
+ long length = visualNodes.getLength();
+ for (long i = 0; i < length; i++) {
+ nsIDOMNode visualNode = visualNodes.item(i);
+ if (pseudoNode == null && isPseudoElement(visualNode)) {
+ pseudoNode = visualNode;
+ } else if (!isEmptyText(visualNode)) {
+ isElements = true;
+ }
+ if (pseudoNode != null && isElements) {
+ break;
+ }
+ }
+ return new PseudoInfo(pseudoNode, isElements);
+ }
+
+ static boolean isInitElement(nsIDOMNode visualNode) {
+ if (visualNode == null) {
+ return false;
+ }
+
+ if (visualNode.getNodeType() != Node.ELEMENT_NODE) {
+ return false;
+ }
+
+ if (YES_STRING.equalsIgnoreCase(((nsIDOMElement) visualNode)
+ .getAttribute(INIT_ELEMENT_ATTR))) {
+ return true;
+ }
+
+ return false;
+ }
+
+ static boolean isPseudoElement(nsIDOMNode visualNode) {
+ if (visualNode == null) {
+ return false;
+ }
+
+ if (visualNode.getNodeType() != Node.ELEMENT_NODE) {
+ return false;
+ }
+
+ if (YES_STRING.equalsIgnoreCase(((nsIDOMElement) visualNode
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
+ .getAttribute(PSEUDO_ELEMENT_ATTR))) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private void setPseudoContent(VpeTemplate containerTemplate,
+ Node sourceContainer, nsIDOMNode visualContainer) {
+ if (containerTemplate != null) {
+ containerTemplate.setPseudoContent(pageContext, sourceContainer,
+ visualContainer, visualDocument);
+ } else {
+ VpeDefaultPseudoContentCreator.getInstance().setPseudoContent(
+ pageContext, sourceContainer, visualContainer,
+ visualDocument);
+ }
+
+ // if (isEmptyElement(visualContainer)) {
+ // addPseudoElementImpl(visualContainer);
+ // }
+ }
+
+ private void addPseudoElementImpl(nsIDOMNode visualParent) {
+ if (!templateManager.isWithoutPseudoElementContainer(visualParent
+ .getNodeName())) {
+ if (VpeDebug.VISUAL_ADD_PSEUDO_ELEMENT) {
+ System.out.println("-------------------- addPseudoElement: "
+ + visualParent.getNodeName());
+ }
+ nsIDOMElement visualPseudoElement = visualDocument
+ .createElement(PSEUDO_ELEMENT);
+ visualPseudoElement.setAttribute(PSEUDO_ELEMENT_ATTR, "yes");
+ visualParent.appendChild(visualPseudoElement);
+ }
+ }
+
+ public boolean isEmptyElement(nsIDOMNode visualParent) {
+ nsIDOMNodeList visualNodes = visualParent.getChildNodes();
+ long len = visualNodes.getLength();
+
+ if ((len == 0) || (len == 1 && isEmptyText(visualNodes.item(0)))) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public boolean isEmptyDocument() {
+ nsIDOMNodeList visualNodes = visualContentArea.getChildNodes();
+ long len = visualNodes.getLength();
+ if ((len == 0)
+ || (len == 1 && (isEmptyText(visualNodes.item(0)) || isPseudoElement(visualNodes
+ .item(0))))) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private boolean isEmptyText(nsIDOMNode visualNode) {
+ if (visualNode == null
+ || (visualNode.getNodeType() != nsIDOMNode.TEXT_NODE)) {
+ return false;
+ }
+
+ if (visualNode.getNodeValue().trim().length() == 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ // ==========================================================
+
+ public void updateNode(Node sourceNode) {
+ if (sourceNode == null)
+ return;
+
+ switch (sourceNode.getNodeType()) {
+ case Node.DOCUMENT_NODE:
+ rebuildDom((Document) sourceNode);
+ break;
+ case Node.COMMENT_NODE:
+ updateComment(sourceNode);
+ break;
+ default:
+ updateElement(getNodeForUpdate(sourceNode));
+ }
+ }
+
+ // TODO Ssergey Vasilyev make a common code for figuring out
+ // if it is need to update parent node or not
+ private Node getNodeForUpdate(Node sourceNode) {
+ /* Changing of <tr> or <td> tags can affect whole the table */
+ Node sourceTable = getParentTable(sourceNode, 2);
+ if (sourceTable != null) {
+ return sourceTable;
+ }
+
+ /* Changing of an <option> tag can affect the parent select */
+ Node sourceSelect = getParentSelect(sourceNode);
+ if (sourceSelect != null) {
+ return sourceSelect;
+ }
+
+ return sourceNode;
+ }
+
+ private void updateComment(Node sourceNode) {
+ VpeNodeMapping mapping = domMapping.getNodeMapping(sourceNode);
+ if (mapping != null
+ && mapping.getType() == VpeNodeMapping.COMMENT_MAPPING) {
+ nsIDOMNodeList visualNodes = mapping.getVisualNode()
+ .getChildNodes();
+
+ if (visualNodes.getLength() > 0) {
+ visualNodes.item(0).setNodeValue(sourceNode.getNodeValue());
+ }
+ }
+ }
+
+ private void updateElement(Node sourceNode) {
+ VpeElementMapping elementMapping = null;
+ VpeNodeMapping nodeMapping = domMapping.getNodeMapping(sourceNode);
+ if (nodeMapping instanceof VpeElementMapping) {
+ elementMapping = (VpeElementMapping) nodeMapping;
+ if (elementMapping != null && elementMapping.getTemplate() != null) {
+ Node updateNode = elementMapping.getTemplate()
+ .getNodeForUptate(pageContext,
+ elementMapping.getSourceNode(),
+ elementMapping.getVisualNode(),
+ elementMapping.getData());
+ if (updateNode != null && updateNode != sourceNode) {
+ updateNode(updateNode);
+ return;
+ }
+ }
+ }
+ nsIDOMNode visualOldNode = domMapping.remove(sourceNode);
+ getSourceNodes().remove(sourceNode);
+ if (sourceNode instanceof INodeNotifier) {
+ ((INodeNotifier) sourceNode).removeAdapter(getSorceAdapter());
+ }
+ if (visualOldNode != null) {
+ if (elementMapping != null) {
+ nsIDOMElement border = elementMapping.getBorder();
+ if (border != null) {
+ visualOldNode = border;
+ }
+ }
+ nsIDOMNode visualContainer = visualOldNode.getParentNode();
+ nsIDOMNode visualNextNode = visualOldNode.getNextSibling();
+ if (visualContainer != null) {
+ visualContainer.removeChild(visualOldNode);
+ addNode(sourceNode, visualNextNode, visualContainer);
+ }
+ } else {
+ //Max Areshkau Why we need update parent node when we update text node?
+ //lookd like we haven't need do it.
+ if (sourceNode.getNodeType() == Node.TEXT_NODE) {
+ updateNode(sourceNode.getParentNode());
+ }
+ }
+ }
+
+ public void removeNode(Node sourceNode) {
+ domMapping.remove(sourceNode);
+ getSourceNodes().remove(sourceNode);
+ if (sourceNode instanceof INodeNotifier) {
+ ((INodeNotifier) sourceNode).removeAdapter(getSorceAdapter());
+ }
+ }
+
+ private Node getParentTable(Node sourceNode, int depth) {
+ Node parentNode = sourceNode.getParentNode();
+ for (int i = 0; parentNode != null && i < depth; parentNode = parentNode
+ .getParentNode(), i++) {
+ if (HTML.TAG_TABLE.equalsIgnoreCase(parentNode.getNodeName())) {
+ return parentNode;
+ }
+ }
+ return null;
+ }
+
+ private Node getParentSelect(Node sourceNode) {
+ if (HTML.TAG_OPTION.equalsIgnoreCase(sourceNode.getNodeName())) {
+ Node parentNode = sourceNode.getParentNode();
+ if (HTML.TAG_SELECT.equalsIgnoreCase(parentNode.getNodeName())) {
+ return parentNode;
+ }
+ }
+ return null;
+ }
+
+// public void setText(Node sourceText) {
+// Node sourceParent = sourceText.getParentNode();
+// if (sourceParent != null && sourceParent.getLocalName() != null) {
+// String sourceParentName = sourceParent.getLocalName();
+// if (HTML.TAG_TEXTAREA.equalsIgnoreCase(sourceParentName)
+// || HTML.TAG_OPTION.equalsIgnoreCase(sourceParentName)) {
+// updateNode(sourceText.getParentNode());
+// return;
+// }
+// }
+// nsIDOMNode visualText = domMapping.getVisualNode(sourceText);
+// if (visualText != null) {
+// String visualValue = TextUtil.visualText(sourceText.getNodeValue());
+// visualText.setNodeValue(visualValue);
+// }else {
+// VpeNodeMapping nodeMapping = domMapping
+// .getNodeMapping(sourceParent);
+// if (nodeMapping != null
+// && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
+// VpeTemplate template = ((VpeElementMapping) nodeMapping)
+// .getTemplate();
+// if (template != null) {
+// if (!template.containsText()) {
+// return;
+// }
+ public boolean setText(Node sourceText) {
+ Node sourceParent = sourceText.getParentNode();
+ if (sourceParent != null && sourceParent.getLocalName() != null) {
+ String sourceParentName = sourceParent.getLocalName();
+ if (HTML.TAG_TEXTAREA.equalsIgnoreCase(sourceParentName)
+ || HTML.TAG_OPTION.equalsIgnoreCase(sourceParentName)) {
+ updateNode(sourceText.getParentNode());
+ return true;
+ }
+ }
+ nsIDOMNode visualText = domMapping.getVisualNode(sourceText);
+ if (visualText != null) {
+ String visualValue = TextUtil.visualText(sourceText.getNodeValue());
+ visualText.setNodeValue(visualValue);
+ } else {
+ VpeNodeMapping nodeMapping = domMapping
+ .getNodeMapping(sourceParent);
+ if (nodeMapping != null
+ && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
+ VpeTemplate template = ((VpeElementMapping) nodeMapping)
+ .getTemplate();
+ if (template != null) {
+ if (!template.containsText()) {
+ return false;
+ }
+ }
+ }
+ updateNode(sourceText);
+ return true;
+ }
+
+ // }
+ // updateNode(sourceText);
+ return false;
+ }
+// }
+
+ public void setAttribute(Element sourceElement, String name, String value) {
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(sourceElement);
+ if (elementMapping != null) {
+ if (elementMapping.isIfDependencyFromAttribute(name)) {
+ updateElement(sourceElement);
+ } else {
+ VpeTemplate template = elementMapping.getTemplate();
+ if (elementMapping.getBorder() != null) {
+ updateElement(sourceElement);
+ } else if (template.isRecreateAtAttrChange(pageContext,
+ sourceElement, visualDocument,
+ (nsIDOMElement) elementMapping.getVisualNode(),
+ elementMapping.getData(), name, value)) {
+ updateElement(sourceElement);
+ } else {
+ nsIDOMElement visualElement = (nsIDOMElement) elementMapping
+ .getVisualNode();
+ if (visualElement != null) {
+ String visualElementName = visualElement.getNodeName();
+ if (HTML.TAG_SELECT.equalsIgnoreCase(visualElementName)) {
+ updateElement(sourceElement);
+ return;
+ } else if (HTML.TAG_OPTION
+ .equalsIgnoreCase(visualElementName)) {
+ updateElement(sourceElement.getParentNode());
+ return;
+ } else if (HTML.TAG_INPUT
+ .equalsIgnoreCase(visualElementName)) {
+ updateElement(sourceElement);
+ }
+ }
+ setXmlnsAttribute(elementMapping, name, value);
+ template.setAttribute(pageContext, sourceElement,
+ visualDocument, visualElement, elementMapping
+ .getData(), name, value);
+ resetTooltip(sourceElement, visualElement);
+ }
+ }
+ }
+ }
+
+ public void stopToggle(Node sourceNode) {
+ if (!(sourceNode instanceof Element))
+ return;
+
+ Element sourceElement = (Element) sourceNode;
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(sourceElement);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+
+ if (template instanceof VpeToggableTemplate) {
+ ((VpeToggableTemplate) template).stopToggling(sourceElement);
+ }
+ }
+ }
+
+ public boolean doToggle(nsIDOMNode visualNode) {
+ if (visualNode == null)
+ return false;
+ nsIDOMElement visualElement = null;
+ try {
+
+ visualElement = (nsIDOMElement) visualNode
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ } catch (XPCOMException exception) {
+ visualElement = (nsIDOMElement) visualNode.getParentNode()
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ }
+ if (visualElement == null)
+ return false;
+
+ nsIDOMAttr toggleIdAttr = visualElement
+ .getAttributeNode("vpe-user-toggle-id");
+ if (toggleIdAttr == null)
+ return false;
+ String toggleId = toggleIdAttr.getNodeValue();
+
+ if (toggleId == null)
+ return false;
+
+ boolean toggleLookup = false;
+ nsIDOMAttr toggleLookupAttr = visualElement
+ .getAttributeNode("vpe-user-toggle-lookup-parent");
+ if (toggleLookupAttr != null) {
+ toggleLookup = "true".equals(toggleLookupAttr.getNodeValue());
+ }
+
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(getLastSelectedElement());
+ Node sourceNode = (Node) domMapping
+ .getSourceNode(getLastSelectedElement());
+ if (sourceNode == null)
+ return false;
+
+ Element sourceElement = (Element) (sourceNode instanceof Element ? sourceNode
+ : sourceNode.getParentNode());
+
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+
+ while (toggleLookup && sourceElement != null
+ && !(template instanceof VpeToggableTemplate)) {
+ sourceElement = (Element) sourceElement.getParentNode();
+ if (sourceElement == null)
+ break;
+ elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(sourceElement);
+ if (elementMapping == null)
+ continue;
+ template = elementMapping.getTemplate();
+ }
+
+ if (template instanceof VpeToggableTemplate) {
+ ((VpeToggableTemplate) template).toggle(this, sourceElement,
+ toggleId);
+ updateElement(sourceElement);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void removeAttribute(Element sourceElement, String name) {
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(sourceElement);
+ if (elementMapping != null) {
+ if (elementMapping.isIfDependencyFromAttribute(name)) {
+ updateElement(sourceElement);
+ } else {
+ VpeTemplate template = elementMapping.getTemplate();
+ if (template.isRecreateAtAttrChange(pageContext, sourceElement,
+ visualDocument, (nsIDOMElement) elementMapping
+ .getVisualNode(), elementMapping.getData(),
+ name, null)) {
+ updateElement(sourceElement);
+ } else {
+ removeXmlnsAttribute(elementMapping, name);
+ template.removeAttribute(pageContext, sourceElement,
+ visualDocument, (nsIDOMElement) elementMapping
+ .getVisualNode(), elementMapping.getData(),
+ name);
+ resetTooltip(sourceElement, (nsIDOMElement) elementMapping
+ .getVisualNode());
+ }
+ }
+ }
+ }
+
+ public void refreshBundleValues(Element sourceElement) {
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(sourceElement);
+ if (elementMapping != null) {
+ VpeTemplate template = elementMapping.getTemplate();
+ template.refreshBundleValues(pageContext, sourceElement,
+ elementMapping.getData());
+ }
+ }
+
+ boolean isContentArea(nsIDOMNode visualNode) {
+ return visualContentArea.equals(visualNode);
+ }
+
+ nsIDOMElement getContentArea() {
+ return visualContentArea;
+ }
+
+ void setSelectionRectangle(nsIDOMElement visualElement) {
+ setSelectionRectangle(visualElement, true);
+ }
+
+ void setSelectionRectangle(nsIDOMElement visualElement, boolean scroll) {
+ int resizerConstrains = getResizerConstrains(visualElement);
+ visualEditor.setSelectionRectangle(visualElement, resizerConstrains,
+ scroll);
+ }
+
+ public nsIDOMNode addLinkNodeToHead(String href_val, String ext_val) {
+ nsIDOMElement newNode = createLinkNode(href_val,
+ ATTR_REL_STYLESHEET_VALUE, ext_val);
+ headNode.appendChild(newNode);
+ return newNode;
+ }
+
+ public nsIDOMNode replaceLinkNodeToHead(nsIDOMNode oldNode,
+ String href_val, String ext_val) {
+ nsIDOMNode newNode = createLinkNode(href_val,
+ ATTR_REL_STYLESHEET_VALUE, ext_val);
+ headNode.replaceChild(newNode, oldNode);
+ return newNode;
+ }
+
+ public nsIDOMNode replaceLinkNodeToHead(String href_val, String ext_val) {
+ nsIDOMNode newNode = null;
+ nsIDOMNode oldNode = getLinkNode(href_val, ext_val);
+ if (oldNode == null) {
+ newNode = addLinkNodeToHead(href_val, ext_val);
+ }
+ return newNode;
+ }
+
+ public void removeLinkNodeFromHead(nsIDOMNode node) {
+ headNode.removeChild(node);
+ }
+
+ private nsIDOMElement createLinkNode(String href_val, String rel_val,
+ String ext_val) {
+ nsIDOMElement linkNode = null;
+ if ((ATTR_REL_STYLESHEET_VALUE.equalsIgnoreCase(rel_val))
+ && href_val.startsWith("file:")) {
+ /*
+ * Because of the Mozilla caches the linked css files we replace tag
+ * <link rel="styleseet" href="file://..."> with tag <style
+ * vpe="ATTR_VPE_INLINE_LINK_VALUE">file content</style> It is
+ * LinkReplacer
+ */
+ linkNode = visualDocument.createElement(HTML.TAG_STYLE);
+ linkNode.setAttribute(ATTR_VPE, ATTR_VPE_INLINE_LINK_VALUE);
+
+ /* Copy links attributes into our <style> */
+ linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_HREF, href_val);
+ linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_EXT, ext_val);
+ try {
+ StringBuffer styleText = new StringBuffer(EMPTY_STRING);
+ URL url = new URL((new Path(href_val)).toOSString());
+ String fileName = url.getFile();
+ BufferedReader in = new BufferedReader(new FileReader(
+ (fileName)));
+ String str = EMPTY_STRING;
+ while ((str = in.readLine()) != null) {
+ styleText.append(str);
+ }
+
+ String styleForParse = styleText.toString();
+ styleForParse = VpeStyleUtil.addFullPathIntoURLValue(
+ styleForParse, href_val);
+
+ in.close();
+ nsIDOMText textNode = visualDocument
+ .createTextNode(styleForParse);
+ linkNode.appendChild(textNode);
+ return linkNode;
+ } catch (FileNotFoundException fnfe) {
+ /* File which was pointed by user is not exists. Do nothing. */
+ } catch (IOException ioe) {
+ VpePlugin.getPluginLog().logError(ioe.getMessage(), ioe);
+ }
+ }
+
+ linkNode = visualDocument.createElement(HTML.TAG_LINK);
+ linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_REL, rel_val);
+ linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_HREF, href_val);
+ linkNode.setAttribute(VpeTemplateManager.ATTR_LINK_EXT, ext_val);
+
+ return linkNode;
+ }
+
+ private boolean isLinkReplacer(nsIDOMNode node) {
+ return HTML.TAG_STYLE.equalsIgnoreCase(node.getNodeName())
+ && ATTR_VPE_INLINE_LINK_VALUE
+ .equalsIgnoreCase(((nsIDOMElement) node
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
+ .getAttribute(ATTR_VPE));
+ }
+
+ private nsIDOMNode getLinkNode(String href_val, String ext_val) {
+ nsIDOMNodeList children = headNode.getChildNodes();
+ long len = children.getLength();
+ for (long i = len - 1; i >= 0; i--) {
+ nsIDOMNode node = children.item(i);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ if (HTML.TAG_LINK.equalsIgnoreCase(node.getNodeName())
+ || isLinkReplacer(node)) {
+ nsIDOMElement element = (nsIDOMElement) node
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ if (ext_val.equalsIgnoreCase(element
+ .getAttribute(VpeTemplateManager.ATTR_LINK_EXT))
+ && href_val
+ .equalsIgnoreCase(element
+ .getAttribute(VpeTemplateManager.ATTR_LINK_HREF))) {
+ return node;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ private void cleanHead() {
+ nsIDOMNodeList children = headNode.getChildNodes();
+ long len = children.getLength();
+ for (long i = len - 1; i >= 0; i--) {
+ nsIDOMNode node = children.item(i);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ String name = node.getNodeName();
+ if (HTML.TAG_LINK.equalsIgnoreCase(name)
+ || isLinkReplacer(node)) {
+ if (NO_STRING.equalsIgnoreCase(((nsIDOMElement) node
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
+ .getAttribute("ext"))) {
+ // int linkAddress =
+ // MozillaSupports.queryInterface(node,
+ // nsIStyleSheetLinkingElement.NS_ISTYLESHEETLINKINGELEMENT_IID);
+ // nsIStyleSheetLinkingElement linkingElement = new
+ // nsIStyleSheetLinkingElement(linkAddress);
+ // linkingElement.removeStyleSheet();
+ node = headNode.removeChild(node);
+ }
+ } else if (HTML.TAG_STYLE.equalsIgnoreCase(node.getNodeName())
+ && (!YES_STRING
+ .equalsIgnoreCase(((nsIDOMElement) node
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
+ .getAttribute(ATTR_VPE)))) {
+ node = headNode.removeChild(node);
+ }
+ }
+ }
+ }
+
+ private class PseudoInfo {
+ private nsIDOMNode pseudoNode;
+ private boolean isElements;
+
+ private PseudoInfo() {
+ this(null, false);
+ }
+
+ private PseudoInfo(nsIDOMNode pseudoNode, boolean isElements) {
+ this.pseudoNode = pseudoNode;
+ this.isElements = isElements;
+ }
+ }
+
+ void showDragCaret(nsIDOMNode node, int offset) {
+ xulRunnerEditor.showDragCaret(node, offset);
+ }
+
+ void hideDragCaret() {
+
+ xulRunnerEditor.hideDragCaret();
+ }
+
+ private int getResizerConstrains(nsIDOMNode visualNode) {
+ VpeNodeMapping nodeMapping = domMapping.getNodeMapping(visualNode);
+ if (nodeMapping != null
+ && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
+ return ((VpeElementMapping) nodeMapping).getTemplate()
+ .getTagDescription(pageContext,
+ (Element) nodeMapping.getSourceNode(),
+ visualDocument,
+ (nsIDOMElement) nodeMapping.getVisualNode(),
+ ((VpeElementMapping) nodeMapping).getData())
+ .getResizeConstrains();
+ }
+ return VpeTagDescription.RESIZE_CONSTRAINS_NONE;
+ }
+
+ public void resize(nsIDOMElement element, int resizerConstrains, int top,
+ int left, int width, int height) {
+ VpeElementMapping elementMapping = (VpeElementMapping) domMapping
+ .getNodeMapping(element);
+ if (elementMapping != null) {
+ elementMapping.getTemplate().resize(pageContext,
+ (Element) elementMapping.getSourceNode(), visualDocument,
+ element, elementMapping.getData(), resizerConstrains, top,
+ left, width, height);
+ }
+ }
+
+ static boolean isAnonElement(nsIDOMNode visualNode) {
+ if (visualNode != null
+ && visualNode.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ String attrValue = ((nsIDOMElement) visualNode
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID))
+ .getAttribute(MOZ_ANONCLASS_ATTR);
+
+ return attrValue != null && attrValue.length() > 0;
+ }
+
+ return false;
+ }
+
+ boolean canInnerDrag(nsIDOMElement visualDragElement) {
+ VpeNodeMapping node = domMapping.getNodeMapping(visualDragElement);
+ if (node instanceof VpeElementMapping) {
+ VpeElementMapping elementMapping = (VpeElementMapping) node;
+ if (elementMapping != null) {
+ return elementMapping.getTemplate().canInnerDrag(pageContext,
+ (Element) elementMapping.getSourceNode(),
+ visualDocument, visualDragElement,
+ elementMapping.getData());
+ }
+ }
+ return false;
+ }
+
+ VpeSourceInnerDropInfo getSourceInnerDropInfo(Node sourceDragNode,
+ VpeVisualInnerDropInfo visualDropInfo, boolean checkParentTemplates) {
+ nsIDOMNode visualDropContainer = visualDropInfo.getDropContainer();
+ long visualDropOffset = visualDropInfo.getDropOffset();
+ Node sourceDropContainer = null;
+ int sourceDropOffset = 0;
+
+ switch (visualDropContainer.getNodeType()) {
+ case nsIDOMNode.ELEMENT_NODE:
+ nsIDOMNode visualOffsetNode = null;
+ boolean afterFlag = false;
+ long visualChildCount = VisualDomUtil
+ .getChildCount(visualDropContainer);
+ if (visualDropOffset < visualChildCount) {
+ visualOffsetNode = VisualDomUtil.getChildNode(
+ visualDropContainer, visualDropOffset);
+ if (isPseudoElement(visualOffsetNode)
+ || isAnonElement(visualOffsetNode)) {
+ visualOffsetNode = getLastAppreciableVisualChild(visualDropContainer);
+ afterFlag = true;
+ }
+ } else {
+ visualOffsetNode = getLastAppreciableVisualChild(visualDropContainer);
+ afterFlag = visualChildCount != 0;
+ }
+ if (visualOffsetNode != null) {
+ Node sourceOffsetNode = domMapping
+ .getSourceNode(visualOffsetNode);
+ if (sourceOffsetNode != null) {
+ sourceDropContainer = sourceOffsetNode.getParentNode();
+ sourceDropOffset = ((NodeImpl) sourceOffsetNode).getIndex();
+ if (afterFlag) {
+ sourceDropOffset++;
+ }
+ }
+ }
+ if (sourceDropContainer == null) {
+ sourceDropContainer = domMapping
+ .getNearSourceNode(visualDropContainer);
+ if (sourceDropContainer != null) {
+ sourceDropOffset = sourceDropContainer.getChildNodes()
+ .getLength();
+ }
+ }
+ if (sourceDropContainer == null) {
+ sourceDropContainer = domMapping
+ .getNearSourceNode(visualContentArea);
+ sourceDropOffset = sourceDropContainer.getChildNodes()
+ .getLength();
+ }
+ break;
+ case nsIDOMNode.TEXT_NODE:
+ VpeNodeMapping nodeMapping = domMapping
+ .getNearNodeMapping(visualDropContainer);
+ switch (nodeMapping.getType()) {
+ case VpeNodeMapping.TEXT_MAPPING:
+ sourceDropContainer = nodeMapping.getSourceNode();
+ sourceDropOffset = TextUtil.sourceInnerPosition(
+ sourceDropContainer.getNodeValue(), visualDropOffset);
+ break;
+ case VpeNodeMapping.ELEMENT_MAPPING:
+ // it's attribute
+ if (isTextEditable(visualDropContainer)) {
+ String[] atributeNames = ((VpeElementMapping) nodeMapping)
+ .getTemplate().getOutputAtributeNames();
+ if (atributeNames != null && atributeNames.length > 0) {
+ Element sourceElement = (Element) nodeMapping
+ .getSourceNode();
+ sourceDropContainer = sourceElement
+ .getAttributeNode(atributeNames[0]);
+ sourceDropOffset = TextUtil.sourceInnerPosition(
+ sourceDropContainer.getNodeValue(),
+ visualDropOffset);
+ }
+ }
+ nodeMapping.getVisualNode();
+ }
+ break;
+ }
+ if (sourceDropContainer != null) {
+ return getSourceInnerDropInfo(sourceDragNode, sourceDropContainer,
+ sourceDropOffset, checkParentTemplates);
+ } else {
+ return new VpeSourceInnerDropInfo(null, 0, false);
+ }
+ }
+
+ VpeSourceInnerDropInfo getSourceInnerDropInfo(Node dragNode,
+ Node container, int offset, boolean checkParentsTemplates) {
+ // Thread.dumpStack();
+ boolean canDrop = false;
+ switch (container.getNodeType()) {
+ case Node.ELEMENT_NODE:
+ VpeNodeMapping nodeMapping = domMapping.getNodeMapping(container);
+ if (nodeMapping != null
+ && nodeMapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
+ canDrop = ((VpeElementMapping) nodeMapping).getTemplate()
+ .canInnerDrop(pageContext, container, dragNode);
+ }
+ if (!canDrop) {
+ if (!checkParentsTemplates)
+ return new VpeSourceInnerDropInfo(container, offset,
+ canDrop);
+ // offset = ((NodeImpl)container).getIndex();
+ // container = container.getParentNode();
+ // TODO Max Areshkau unclear logic , if we can drop on element
+ // why we trying to drop
+ // this on parent
+ // return getSourceInnerDropInfo(dragNode, container, offset,
+ // false);
+ return new VpeSourceInnerDropInfo(container, offset, canDrop);
+ }
+ break;
+ case Node.TEXT_NODE:
+ case Node.DOCUMENT_NODE:
+ canDrop = true;
+ break;
+ case Node.ATTRIBUTE_NODE:
+ canDrop = true;
+ break;
+ }
+ if (canDrop) {
+ return new VpeSourceInnerDropInfo(container, offset, canDrop);
+ } else {
+ return new VpeSourceInnerDropInfo(null, 0, canDrop);
+ }
+ }
+
+ public void innerDrop(Node dragNode, Node container, int offset) {
+ VpeNodeMapping mapping = domMapping.getNearNodeMapping(container);
+ if (mapping != null) {
+ nsIDOMNode visualDropContainer = mapping.getVisualNode();
+ switch (mapping.getType()) {
+ case VpeNodeMapping.TEXT_MAPPING:
+ break;
+ case VpeNodeMapping.ELEMENT_MAPPING:
+ nsIDOMNode visualParent = visualDropContainer.getParentNode();
+ VpeNodeMapping oldMapping = mapping;
+ mapping = domMapping.getNearNodeMapping(visualParent);
+ if (mapping != null
+ && mapping.getType() == VpeNodeMapping.ELEMENT_MAPPING) {
+ ((VpeElementMapping) mapping).getTemplate()
+ .innerDrop(
+ pageContext,
+ new VpeSourceInnerDragInfo(dragNode, 0, 0),
+ new VpeSourceInnerDropInfo(container,
+ offset, true));
+ } else {
+ ((VpeElementMapping) oldMapping).getTemplate()
+ .innerDrop(
+ pageContext,
+ new VpeSourceInnerDragInfo(dragNode, 0, 0),
+ new VpeSourceInnerDropInfo(container,
+ offset, true));
+ }
+ }
+
+ }
+ }
+
+ void innerDrop(VpeSourceInnerDragInfo dragInfo,
+ VpeSourceInnerDropInfo dropInfo) {
+ dropper.drop(pageContext, dragInfo, dropInfo);
+ }
+
+ nsIDOMElement getNearDragElement(Element visualElement) {
+ VpeElementMapping elementMapping = domMapping
+ .getNearElementMapping(visualElement);
+ while (elementMapping != null) {
+ if (canInnerDrag(elementMapping.getVisualElement())) {
+ return elementMapping.getVisualElement();
+ }
+ elementMapping = domMapping.getNearElementMapping(elementMapping
+ .getVisualNode().getParentNode());
+ }
+ return null;
+ }
+
+ nsIDOMElement getDragElement(nsIDOMElement visualElement) {
+ VpeElementMapping elementMapping = domMapping
+ .getNearElementMapping(visualElement);
+ if (elementMapping != null
+ && canInnerDrag(elementMapping.getVisualElement())) {
+ return elementMapping.getVisualElement();
+ }
+ return null;
+ }
+
+ public boolean isTextEditable(nsIDOMNode visualNode) {
+ if (visualNode != null) {
+ nsIDOMNode parent = visualNode.getParentNode();
+ if (parent != null
+ && parent.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ nsIDOMElement element = (nsIDOMElement) parent
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ nsIDOMAttr style = element.getAttributeNode("style");
+ if (style != null) {
+ String styleValue = style.getNodeValue();
+ String[] items = styleValue.split(";");
+ for (int i = 0; i < items.length; i++) {
+ String[] item = items[i].split(":");
+ if ("-moz-user-modify".equals(item[0].trim())
+ && "read-only".equals(item[1].trim())) {
+ return false;
+ }
+ }
+ }
+ nsIDOMAttr classAttr = element.getAttributeNode("class");
+ if (classAttr != null) {
+ String classValue = classAttr.getNodeValue().trim();
+ if ("__any__tag__caption".equals(classValue)) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ VpeVisualInnerDropInfo getInnerDropInfo(Node sourceDropContainer,
+ int sourceDropOffset) {
+ nsIDOMNode visualDropContainer = null;
+ long visualDropOffset = 0;
+
+ switch (sourceDropContainer.getNodeType()) {
+ case Node.TEXT_NODE:
+ visualDropContainer = domMapping.getVisualNode(sourceDropContainer);
+ visualDropOffset = TextUtil.visualInnerPosition(sourceDropContainer
+ .getNodeValue(), sourceDropOffset);
+ break;
+ case Node.ELEMENT_NODE:
+ case Node.DOCUMENT_NODE:
+ NodeList sourceChildren = sourceDropContainer.getChildNodes();
+ if (sourceDropOffset < sourceChildren.getLength()) {
+ Node sourceChild = sourceChildren.item(sourceDropOffset);
+ nsIDOMNode visualChild = domMapping.getVisualNode(sourceChild);
+ if (visualChild != null) {
+ visualDropContainer = visualChild.getParentNode();
+
+ visualDropOffset = VisualDomUtil.getOffset(visualChild);
+ }
+ }
+ if (visualDropContainer == null) {
+ visualDropContainer = domMapping
+ .getNearVisualNode(sourceDropContainer);
+ nsIDOMNode visualChild = getLastAppreciableVisualChild(visualDropContainer);
+ if (visualChild != null) {
+ visualDropOffset = VisualDomUtil.getOffset(visualChild) + 1;
+ } else {
+ visualDropOffset = 0;
+ }
+ }
+ break;
+ case Node.ATTRIBUTE_NODE:
+ Element sourceElement = ((Attr) sourceDropContainer)
+ .getOwnerElement();
+ VpeElementMapping elementMapping = domMapping
+ .getNearElementMapping(sourceElement);
+ nsIDOMNode textNode = elementMapping.getTemplate()
+ .getOutputTextNode(pageContext, sourceElement,
+ elementMapping.getData());
+ if (textNode != null) {
+ visualDropContainer = textNode;
+ visualDropOffset = TextUtil.visualInnerPosition(
+ sourceDropContainer.getNodeValue(), sourceDropOffset);
+ }
+ break;
+ }
+ if (visualDropContainer == null) {
+ return null;
+ }
+ return new VpeVisualInnerDropInfo(visualDropContainer,
+ visualDropOffset, 0, 0);
+ }
+
+ protected void setTooltip(Element sourceElement, nsIDOMElement visualElement) {
+ if (visualElement != null && sourceElement != null
+ && !((ElementImpl) sourceElement).isJSPTag()) {
+ if (HTML.TAG_HTML.equalsIgnoreCase(sourceElement.getNodeName()))
+ return;
+ String titleValue = getTooltip(sourceElement);
+
+ if (titleValue != null) {
+ titleValue = titleValue.replaceAll("&", "&");
+ titleValue = titleValue.replaceAll("<", "<");
+ titleValue = titleValue.replaceAll(">", ">");
+ }
+
+ if (titleValue != null) {
+ // visualElement.setAttribute("title", titleValue);
+ setTooltip(visualElement, titleValue);
+ }
+ }
+ }
+
+ protected void setTooltip(nsIDOMElement visualElement, String titleValue) {
+ visualElement.setAttribute("title", titleValue);
+ nsIDOMNodeList children = visualElement.getChildNodes();
+ long len = children.getLength();
+ for (long i = 0; i < len; i++) {
+ nsIDOMNode child = children.item(i);
+ if (child.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ setTooltip(((nsIDOMElement) child
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID)),
+ titleValue);
+ }
+ }
+ }
+
+ private void resetTooltip(Element sourceElement, nsIDOMElement visualElement) {
+ if (visualElement != null && sourceElement != null
+ && !((ElementImpl) sourceElement).isJSPTag()) {
+ if (HTML.TAG_HTML.equalsIgnoreCase(sourceElement.getNodeName()))
+ return;
+ String titleValue = getTooltip(sourceElement);
+
+ if (titleValue != null) {
+ titleValue = titleValue.replaceAll("&", "&");
+ titleValue = titleValue.replaceAll("<", "<");
+ titleValue = titleValue.replaceAll(">", ">");
+ }
+
+ if (titleValue != null) {
+ resetTooltip(visualElement, titleValue);
+ }
+ }
+ }
+
+ private void resetTooltip(nsIDOMElement visualElement, String titleValue) {
+ visualElement.setAttribute("title", titleValue);
+ nsIDOMNodeList children = visualElement.getChildNodes();
+ long len = children.getLength();
+ for (long i = 0; i < len; i++) {
+ nsIDOMNode child = children.item(i);
+ if (child.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ if (domMapping.getNodeMapping(child) == null) {
+ resetTooltip((nsIDOMElement) child
+ .queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID),
+ titleValue);
+ }
+ }
+ }
+ }
+
+ private String getTooltip(Element sourceElement) {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append(sourceElement.getNodeName());
+ NamedNodeMap attrs = sourceElement.getAttributes();
+ int len = attrs.getLength();
+ for (int i = 0; i < len; i++) {
+ if (i == 7) {
+ return buffer.append("\n\t... ").toString();
+ }
+ int valueLength = attrs.item(i).getNodeValue().length();
+ if (valueLength > 30) {
+ StringBuffer temp = new StringBuffer();
+ temp.append(attrs.item(i).getNodeValue().substring(0, 15)
+ + " ... "
+ + attrs.item(i).getNodeValue().substring(
+ valueLength - 15, valueLength));
+ buffer.append("\n" + attrs.item(i).getNodeName() + ": " + temp);
+ } else
+ buffer.append("\n" + attrs.item(i).getNodeName() + ": "
+ + attrs.item(i).getNodeValue());
+
+ }
+
+ return buffer.toString();
+ }
+
+ Rectangle getNodeBounds(nsIDOMNode visualNode) {
+
+ return XulRunnerVpeUtils.getElementBounds(visualNode);
+ }
+
+ static boolean canInsertAfter(int x, int y, Rectangle rect) {
+ if (y > (rect.y + rect.height) || x > (rect.x + rect.width)) {
+ return true;
+ }
+ return y >= rect.x && x > (rect.x + rect.width / 2);
+ }
+
+ static nsIDOMNode getLastAppreciableVisualChild(nsIDOMNode visualParent) {
+ nsIDOMNode visualLastChild = null;
+ nsIDOMNodeList visualChildren = visualParent.getChildNodes();
+ long len = visualChildren.getLength();
+ for (long i = len - 1; i >= 0; i--) {
+ nsIDOMNode visualChild = visualChildren.item(i);
+ if (!isPseudoElement(visualChild) && !isAnonElement(visualChild)) {
+ visualLastChild = visualChild;
+ break;
+ }
+ }
+ return visualLastChild;
+ }
+
+ void correctVisualDropPosition(VpeVisualInnerDropInfo newVisualDropInfo,
+ VpeVisualInnerDropInfo oldVisualDropInfo) {
+ nsIDOMNode newVisualDropContainer = newVisualDropInfo
+ .getDropContainer();
+ nsIDOMNode oldVisualDropContainer = oldVisualDropInfo
+ .getDropContainer();
+
+ if (newVisualDropContainer.equals(oldVisualDropContainer)) {
+ newVisualDropInfo.setDropOffset(oldVisualDropInfo.getDropOffset());
+ return;
+ }
+
+ nsIDOMNode child = oldVisualDropContainer;
+ while (child != null && child.getNodeType() != Node.DOCUMENT_NODE) {
+ nsIDOMNode parent = child.getParentNode();
+ if (newVisualDropContainer.equals(parent)) {
+ long offset = VisualDomUtil.getOffset(child);
+ Rectangle rect = getNodeBounds(child);
+ if (canInsertAfter(oldVisualDropInfo.getMouseX(),
+ oldVisualDropInfo.getMouseY(), rect)) {
+ offset++;
+ }
+ newVisualDropInfo.setDropOffset(offset);
+ }
+ child = parent;
+ }
+ }
+
+ public nsIDOMRange createDOMRange() {
+ return xulRunnerEditor.createDOMRange();
+ }
+
+ public nsIDOMRange createDOMRange(nsIDOMNode selectedNode) {
+ nsIDOMRange range = createDOMRange();
+ range.selectNode(selectedNode);
+ return range;
+ }
+
+ public static boolean isIncludeElement(nsIDOMElement visualElement) {
+ return YES_STRING.equalsIgnoreCase(visualElement
+ .getAttribute(INCLUDE_ELEMENT_ATTR));
+ }
+
+ public static void markIncludeElement(nsIDOMElement visualElement) {
+ visualElement.setAttribute(INCLUDE_ELEMENT_ATTR, YES_STRING);
+ }
+
+ protected void setReadOnlyElement(nsIDOMElement node) {
+ String style = node.getAttribute(VpeStyleUtil.ATTRIBUTE_STYLE);
+ style = VpeStyleUtil.setParameterInStyle(style, "-moz-user-modify",
+ "read-only");
+ node.setAttribute(VpeStyleUtil.ATTRIBUTE_STYLE, style);
+ }
+
+ void setMoveCursor(nsIDOMMouseEvent mouseEvent) {
+
+ nsIDOMElement selectedElement = xulRunnerEditor
+ .getLastSelectedElement();
+ if (selectedElement != null && canInnerDrag(selectedElement)) {
+ String styleClasses = selectedElement.getAttribute(HTML.ATTR_CLASS);
+ if (inDragArea(getNodeBounds(selectedElement), VisualDomUtil
+ .getMousePoint(mouseEvent))) {
+ // change cursor
+ if (styleClasses == null
+ || !(styleClasses.contains(ATTR_DRAG_AVAILABLE_CLASS))) {
+ // change cursor style to move
+ styleClasses = ATTR_DRAG_AVAILABLE_CLASS + " "
+ + styleClasses;
+ }
+ } else {
+ // change cursor style to normal
+ if (styleClasses != null) {
+
+ styleClasses = styleClasses.replaceAll(
+ ATTR_DRAG_AVAILABLE_CLASS, "");
+ }
+ }
+ selectedElement.setAttribute(HTML.ATTR_CLASS, styleClasses);
+ }
+ }
+
+ private boolean inDragArea(Rectangle dragArea, Point mousePoint) {
+ // TODO add drag and drop support
+ return dragArea.contains(mousePoint)
+ && mousePoint.x < (dragArea.x + DRAG_AREA_WIDTH)
+ && mousePoint.y < (dragArea.y + DRAG_AREA_HEIGHT);
+ }
+
+ nsIDOMElement getDragElement(nsIDOMMouseEvent mouseEvent) {
+
+ nsIDOMElement selectedElement = xulRunnerEditor
+ .getLastSelectedElement();
+ if (selectedElement != null && canInnerDrag(selectedElement)) {
+ if (inDragArea(getNodeBounds(selectedElement), VisualDomUtil
+ .getMousePoint(mouseEvent))) {
+ return selectedElement;
+ }
+ }
+ return null;
+ }
+
+ VpeSourceInnerDragInfo getSourceInnerDragInfo(
+ VpeVisualInnerDragInfo visualDragInfo) {
+ nsIDOMNode visualNode = visualDragInfo.getNode();
+ int offset = visualDragInfo.getOffset();
+ int length = visualDragInfo.getLength();
+
+ VpeNodeMapping nodeMapping = domMapping.getNearNodeMapping(visualNode);
+ Node sourceNode = nodeMapping.getSourceNode();
+
+ if (sourceNode != null) {
+ switch (sourceNode.getNodeType()) {
+ case Node.TEXT_NODE:
+ int end = TextUtil.sourceInnerPosition(visualNode
+ .getNodeValue(), offset + length);
+ offset = TextUtil.sourceInnerPosition(
+ visualNode.getNodeValue(), offset);
+ length = end - offset;
+ break;
+ case Node.ELEMENT_NODE:
+ if (visualNode.getNodeType() == Node.TEXT_NODE) {
+ // it's attribute
+ sourceNode = null;
+ if (isTextEditable(visualNode)) {
+ String[] atributeNames = ((VpeElementMapping) nodeMapping)
+ .getTemplate().getOutputAtributeNames();
+ if (atributeNames != null && atributeNames.length > 0) {
+ Element sourceElement = (Element) nodeMapping
+ .getSourceNode();
+ sourceNode = sourceElement
+ .getAttributeNode(atributeNames[0]);
+ end = TextUtil.sourceInnerPosition(visualNode
+ .getNodeValue(), offset + length);
+ offset = TextUtil.sourceInnerPosition(visualNode
+ .getNodeValue(), offset);
+ length = end - offset;
+ }
+ }
+ }
+ break;
+ }
+ }
+ return new VpeSourceInnerDragInfo(sourceNode, offset, length);
+ }
+
+ public nsIDOMText getOutputTextNode(Attr attr) {
+ Element sourceElement = ((Attr) attr).getOwnerElement();
+ VpeElementMapping elementMapping = domMapping
+ .getNearElementMapping(sourceElement);
+ if (elementMapping != null) {
+ return elementMapping.getTemplate().getOutputTextNode(pageContext,
+ sourceElement, elementMapping.getData());
+ }
+ return null;
+ }
+
+ nsIDOMElement getLastSelectedElement() {
+
+ return xulRunnerEditor.getLastSelectedElement();
+ }
+
+ public void pushIncludeStack(VpeIncludeInfo includeInfo) {
+ includeStack.add(includeInfo);
+ }
+
+ public VpeIncludeInfo popIncludeStack() {
+ VpeIncludeInfo includeInfo = null;
+ if (includeStack.size() > 0) {
+ includeInfo = (VpeIncludeInfo) includeStack.remove(includeStack
+ .size() - 1);
+ }
+ return includeInfo;
+ }
+
+ public boolean isFileInIncludeStack(IFile file) {
+ if (file == null)
+ return false;
+ for (int i = 0; i < includeStack.size(); i++) {
+ if (file.equals(((VpeIncludeInfo) includeStack.get(i)).getFile())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected boolean isCurrentMainDocument() {
+ return includeStack.size() <= 1;
+ }
+
+ public int getCurrentMainIncludeOffset() {
+ if (includeStack.size() <= 1)
+ return -1;
+ VpeIncludeInfo info = (VpeIncludeInfo) includeStack.get(1);
+ return ((IndexedRegion) info.getElement()).getStartOffset();
+ }
+
+ public VpeIncludeInfo getCurrentIncludeInfo() {
+ if (includeStack.size() <= 0)
+ return null;
+ return (VpeIncludeInfo) includeStack.get(includeStack.size() - 1);
+ }
+
+ public VpeIncludeInfo getRootIncludeInfo() {
+ if (includeStack.size() <= 1)
+ return null;
+ return (VpeIncludeInfo) includeStack.get(1);
+ }
+
+ public void dispose() {
+ clearIncludeDocuments();
+ includeDocuments=null;
+ cleanHead();
+ domMapping.clear(visualContentArea);
+ pageContext.dispose();
+ super.dispose();
+ }
+
+ private void clearIncludeDocuments() {
+ Collection<Document> documents = includeDocuments.values();
+ for (Iterator iterator = documents.iterator(); iterator.hasNext();) {
+ Document document = (Document) iterator.next();
+ VpeCreatorUtil.releaseDocumentFromRead(document);
+ }
+ includeDocuments.clear();
+ }
+
+ protected Map createXmlns(Element sourceNode) {
+ NamedNodeMap attrs = ((Element) sourceNode).getAttributes();
+ if (attrs != null) {
+ Map xmlnsMap = new HashMap();
+ for (int i = 0; i < attrs.getLength(); i++) {
+ addTaglib(sourceNode, xmlnsMap, attrs.item(i).getNodeName(),
+ true);
+ }
+ if (xmlnsMap.size() > 0) {
+ return xmlnsMap;
+ }
+ }
+ return null;
+ }
+
+ private void setXmlnsAttribute(VpeElementMapping elementMapping,
+ String name, String value) {
+ Element sourceElement = (Element) elementMapping.getSourceNode();
+ if (sourceElement != null) {
+ Map xmlnsMap = elementMapping.getXmlnsMap();
+ if (xmlnsMap == null)
+ xmlnsMap = new HashMap();
+ addTaglib(sourceElement, xmlnsMap, name, true);
+ elementMapping.setXmlnsMap(xmlnsMap.size() > 0 ? xmlnsMap : null);
+ }
+ }
+
+ private void removeXmlnsAttribute(VpeElementMapping elementMapping,
+ String name) {
+ Element sourceElement = (Element) elementMapping.getSourceNode();
+ if (sourceElement != null) {
+ Map xmlnsMap = elementMapping.getXmlnsMap();
+ if (xmlnsMap != null) {
+ Object id = xmlnsMap.remove(name);
+ if (id != null) {
+ pageContext.setTaglib(((Integer) id).intValue(), null,
+ null, true);
+ elementMapping.setXmlnsMap(xmlnsMap.size() > 0 ? xmlnsMap
+ : null);
+ }
+ }
+ }
+ }
+
+ private void addTaglib(Element sourceElement, Map xmlnsMap,
+ String attrName, boolean ns) {
+ Attr attr = sourceElement.getAttributeNode(attrName);
+ if (ATTR_XMLNS.equals(attr.getPrefix())) {
+ xmlnsMap.put(attr.getNodeName(), Integer.valueOf(attr.hashCode()));
+ pageContext.setTaglib(attr.hashCode(), attr.getNodeValue(), attr
+ .getLocalName(), ns);
+ }
+ }
+
+ /**
+ * @return the dnd
+ */
+ public VpeDnD getDnd() {
+
+ return dnd;
+ }
+
+ /**
+ * @param dnd
+ * the dnd to set
+ */
+ public void setDnd(VpeDnD dnd) {
+
+ this.dnd = dnd;
+ }
+
+ /**
+ * @return the pageContext
+ */
+ protected VpePageContext getPageContext() {
+ return pageContext;
+ }
+
+ /**
+ * @param pageContext
+ * the pageContext to set
+ */
+ protected void setPageContext(VpePageContext pageContext) {
+ this.pageContext = pageContext;
+ }
+
+ /**
+ * @return the visualDocument
+ */
+ protected nsIDOMDocument getVisualDocument() {
+ return visualDocument;
+ }
+
+ /**
+ * @param visualDocument
+ * the visualDocument to set
+ */
+ protected void setVisualDocument(nsIDOMDocument visualDocument) {
+ this.visualDocument = visualDocument;
+ }
+
+ /**
+ * Check this file is facelet
+ *
+ * @return this if file is facelet, otherwize false
+ */
+ private boolean isFacelet() {
+ boolean isFacelet = false;
+
+ IEditorInput iEditorInput = pageContext.getEditPart().getEditorInput();
+ if (iEditorInput instanceof IFileEditorInput) {
+ IFileEditorInput iFileEditorInput = (IFileEditorInput) iEditorInput;
+
+ IFile iFile = iFileEditorInput.getFile();
+
+ IProject project = iFile.getProject();
+ IModelNature nature = EclipseResourceUtil.getModelNature(project);
+ if (nature != null) {
+ XModel model = nature.getModel();
+ XModelObject webXML = WebAppHelper.getWebApp(model);
+ XModelObject param = WebAppHelper.findWebAppContextParam(
+ webXML, "javax.faces.DEFAULT_SUFFIX");
+ if (param != null) {
+ String value = param.getAttributeValue("param-value");
+
+ if (value.length() != 0 && iFile.getName().endsWith(value)) {
+ isFacelet = true;
+ }
+ }
+ }
+ }
+
+ return isFacelet;
+ }
+
+ /**
+ * Create a visual element for text node
+ *
+ * @param sourceNode
+ * @param registerFlag
+ * @return a visual element for text node
+ */
+
+ protected nsIDOMNode createTextNode(Node sourceNode, boolean registerFlag) {
+ String sourceText = sourceNode.getNodeValue();
+
+ //Max Areshkau this code causes very slow work of visual editor
+ //when we editing in big files txt nodes.For example exmployee.xhtml from JBIDE1105
+// if (sourceText.trim().length() <= 0) {
+// if (registerFlag)
+// registerNodes(new VpeNodeMapping(sourceNode, null));
+// return null;
+// }
+
+ if (faceletFile) {
+ Matcher matcher_EL = REGEX_EL.matcher(sourceText);
+ if (matcher_EL.find()) {
+ BundleMap bundle = pageContext.getBundle();
+ int offset = pageContext.getVisualBuilder()
+ .getCurrentMainIncludeOffset();
+ if (offset == -1)
+ offset = ((IndexedRegion) sourceNode).getStartOffset();
+ String jsfValue = bundle.getBundleValue(sourceText, offset);
+ sourceText = jsfValue;
+ }
+ }
+ String visualText = TextUtil.visualText(sourceText);
+
+ nsIDOMNode visualNewTextNode = visualDocument
+ .createTextNode(visualText);
+ nsIDOMElement element = visualDocument.createElement(HTML.TAG_SPAN);
+ element.appendChild(visualNewTextNode);
+ if (registerFlag) {
+ registerNodes(new VpeNodeMapping(sourceNode, element));
+ }
+
+ return element;
+ }
+
+ /**
+ * @return the xulRunnerEditor
+ */
+ public XulRunnerEditor getXulRunnerEditor() {
+ return xulRunnerEditor;
+ }
+
+ /**
+ * @param xulRunnerEditor
+ * the xulRunnerEditor to set
+ */
+ public void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
+ this.xulRunnerEditor = xulRunnerEditor;
+ }
+
+ public Map<IFile, Document> getIncludeDocuments() {
+ return includeDocuments;
+ }
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/context/VpePageContext.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/context/VpePageContext.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/context/VpePageContext.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,443 +1,469 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor.context;
-
-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 org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jst.jsp.core.internal.contentmodel.TaglibController;
-import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager;
-import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TaglibTracker;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.jboss.tools.common.kb.KbConnectorFactory;
-import org.jboss.tools.common.kb.KbConnectorType;
-import org.jboss.tools.common.kb.KbTldResource;
-import org.jboss.tools.common.kb.wtp.JspWtpKbConnector;
-import org.jboss.tools.common.kb.wtp.TLDVersionHelper;
-import org.jboss.tools.common.kb.wtp.WtpKbConnector;
-import org.jboss.tools.common.model.XModel;
-import org.jboss.tools.common.model.project.IModelNature;
-import org.jboss.tools.common.model.util.EclipseResourceUtil;
-import org.jboss.tools.jst.jsp.editor.IVisualContext;
-import org.jboss.tools.jst.jsp.editor.TLDRegisterHelper;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.jst.web.tld.TaglibData;
-import org.jboss.tools.jst.web.tld.VpeTaglibListener;
-import org.jboss.tools.jst.web.tld.VpeTaglibManager;
-import org.jboss.tools.vpe.VpeDebug;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.VpeEditorPart;
-import org.jboss.tools.vpe.editor.VpeSourceDomBuilder;
-import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
-import org.jboss.tools.vpe.editor.bundle.BundleMap;
-import org.jboss.tools.vpe.editor.css.AbsoluteFolderReferenceList;
-import org.jboss.tools.vpe.editor.css.CSSReferenceList;
-import org.jboss.tools.vpe.editor.css.RelativeFolderReferenceList;
-import org.jboss.tools.vpe.editor.css.ResourceReference;
-import org.jboss.tools.vpe.editor.css.TaglibReferenceList;
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-import org.jboss.tools.vpe.editor.util.FileUtil;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Contains the information on edited page.
- */
-
-public class VpePageContext implements VpeTaglibManager, IVisualContext {
- private VpeTemplateManager templateManager;
- private ArrayList taglibs = new ArrayList();
- private Map taglibMap = new HashMap();
- private VpeTaglibListener[] taglibListeners = new VpeTaglibListener[0];
- private BundleMap bundle;
- private Set bundleDependencySet = new HashSet();
- private VpeSourceDomBuilder sourceBuilder;
- private VpeVisualDomBuilder visualBuilder;
- private VpeEditorPart editPart;
- private List lastTaglibs = new ArrayList();
- private boolean taglibChanged = false;
- WtpKbConnector connector;
- private nsIDOMNode currentVisualNode;
-
- public VpePageContext(VpeTemplateManager templateManager, BundleMap bundle, VpeEditorPart editPart) {
- this.templateManager = templateManager;
- this.bundle = bundle;
- this.editPart = editPart;
- }
-
- public VpeSourceDomBuilder getSourceBuilder(){
- return sourceBuilder;
- }
-
- public boolean isAbsolutePosition(){
- if("yes".equals(VpePreference.USE_ABSOLUTE_POSITION.getValue()))return true;
- else return false;
- }
-
- public void setSourceDomBuilder(VpeSourceDomBuilder sourceBuilder) {
- this.sourceBuilder = sourceBuilder;
- refreshConnector();
- }
-
- public void refreshConnector() {
- try {
- IDocument document = sourceBuilder.getStructuredTextViewer().getDocument();
- connector = (WtpKbConnector)KbConnectorFactory.getIntstance().createConnector(KbConnectorType.JSP_WTP_KB_CONNECTOR, document);
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- }
- }
-
- public VpeVisualDomBuilder getVisualBuilder(){
- return visualBuilder;
- }
-
- public void setVisualDomBuilder(VpeVisualDomBuilder visualBuilder) {
- this.visualBuilder = visualBuilder;
- }
-
- public VpeDomMapping getDomMapping () {
- return visualBuilder.getDomMapping();
- }
-
- public void clearAll() {
- taglibs.clear();
- taglibMap.clear();
- bundleDependencySet.clear();
- bundle.clearAll();
- }
-
- public void dispose() {
- bundle.dispose();
- clearAll();
- }
-
- public void setTaglib(int id, String newUri, String newPrefix, boolean ns) {
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- if (taglib.getId() == id) {
- if (newUri != null && newPrefix != null) {
- if (!newUri.equals(taglib.getUri()) || !newPrefix.equals(taglib.getPrefix())) {
- taglibs.set(i, new TaglibData(id, newUri, newPrefix, ns));
- rebuildTaglibMap();
- }
- } else {
- taglibs.remove(i);
- rebuildTaglibMap();
- }
- return;
- }
- }
- if (newUri != null && newPrefix != null) {
- taglibs.add(new TaglibData(id, newUri, newPrefix, ns));
- rebuildTaglibMap();
- }
- }
-
- public String getTemplateTaglibPrefix(String sourceTaglibPrefix) {
- return (String) taglibMap.get(sourceTaglibPrefix);
- }
-
- private void rebuildTaglibMap() {
- taglibMap.clear();
- Set prefixSet = new HashSet();
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- String prefix = taglib.getPrefix();
- if (!prefixSet.contains(prefix)) {
- String templatePrefix = templateManager.getTemplateTaglibPrefix(taglib.getUri());
- if (templatePrefix != null) {
- taglibMap.put(prefix, templatePrefix);
- }
- prefixSet.add(prefix);
- }
- }
- taglibChanged = true;
-
- try {
- registerTaglibs(connector, this, getSourceBuilder().getStructuredTextViewer().getDocument());
- } catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
- }
- }
-
- public void addTaglibListener(VpeTaglibListener listener) {
- if (listener != null) {
- VpeTaglibListener[] newTaglibListeners = new VpeTaglibListener[taglibListeners.length + 1];
- System.arraycopy(taglibListeners, 0, newTaglibListeners, 0, taglibListeners.length);
- taglibListeners = newTaglibListeners;
- taglibListeners[taglibListeners.length - 1] = listener;
- }
- }
-
- public void removeTaglibListener(VpeTaglibListener listener) {
- if (listener == null || taglibListeners.length == 0) return;
- int index = -1;
- for (int i = 0; i < taglibListeners.length; i++) {
- if (listener == taglibListeners[i]){
- index = i;
- break;
- }
- }
- if (index == -1) return;
- if (taglibListeners.length == 1) {
- taglibListeners = new VpeTaglibListener[0];
- return;
- }
- VpeTaglibListener[] newTaglibListeners = new VpeTaglibListener[taglibListeners.length - 1];
- System.arraycopy(taglibListeners, 0, newTaglibListeners, 0, index);
- System.arraycopy(taglibListeners, index + 1, newTaglibListeners, index, taglibListeners.length - index - 1);
- taglibListeners = newTaglibListeners;
- }
-
- public BundleMap getBundle() {
- return bundle;
- }
-
- public void addBundleDependency(Element sourceNode) {
- bundleDependencySet.add(sourceNode);
- }
-
- public void removeBundleDependency(Element sourceNode) {
- bundleDependencySet.remove(sourceNode);
- }
-
- public void refreshBundleValues() {
- Iterator iterator = bundleDependencySet.iterator();
- while (iterator.hasNext()) {
- Element sourceElement = (Element) iterator.next();
- visualBuilder.refreshBundleValues(sourceElement);
- }
- }
-
- public boolean isCorrectNS(Node sourceNode) {
- String sourcePrefix = sourceNode.getPrefix();
- if (sourcePrefix == null || ((ElementImpl)sourceNode).isJSPTag()) {
- return true;
- }
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- if (sourcePrefix.equals(taglib.getPrefix())) {
- return true;
- }
- }
- return false;
- }
-
- public String getSourceTaglibUri(Node sourceNode) {
- String sourcePrefix = sourceNode.getPrefix();
- if (sourcePrefix == null || ((ElementImpl)sourceNode).isJSPTag()) {
- return null;
- }
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- if (sourcePrefix.equals(taglib.getPrefix())) {
- return taglib.getUri();
- }
- }
- return null;
- }
-
- public VpeEditorPart getEditPart() {
- return editPart;
- }
-
- public void openIncludeFile(String file) {
- IEditorInput input = editPart.getEditorInput();
- IWorkbenchPage workbenchPage = VpePlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
- try{
- IFile f = FileUtil.getFile(input, file);
- if (f != null) {
- IDE.openEditor(workbenchPage, f, true);
- }
- }catch(Exception ex){
- VpePlugin.reportProblem(ex);
- }
- }
-
- public ResourceReference[] getIncludeTaglibs() {
- IEditorInput input = getEditPart().getEditorInput();
- IFile file = null;
- if (input instanceof IFileEditorInput) {
- file = ((IFileEditorInput)input).getFile();
- }
- ResourceReference[] resourceReferences = new ResourceReference[0];
- if (file != null) {
- resourceReferences = TaglibReferenceList.getInstance().getAllResources(file);
- }
- return resourceReferences;
- }
-
- public ResourceReference[] getIncludeCss() {
- IEditorInput input = getEditPart().getEditorInput();
- IFile file = null;
- if (input instanceof IFileEditorInput) {
- file = ((IFileEditorInput)input).getFile();
- }
- ResourceReference[] resourceReferences = new ResourceReference[0];
- if (file != null) {
- resourceReferences = CSSReferenceList.getInstance().getAllResources(file);
- }
- return resourceReferences;
- }
-
- public void installIncludeElements() {
- ResourceReference[] list = getIncludeTaglibs();
- for (int i = 0; i < list.length; i++) {
- ResourceReference reference = list[i];
- setTaglib(i, reference.getLocation(), reference.getProperties(), false);
- }
-
- list = getIncludeCss();
- for (int i = 0; i < list.length; i++) {
- visualBuilder.addLinkNodeToHead(list[i].getLocation(), "yes");
- }
- }
-
- public ResourceReference getRuntimeRelativeFolder(IFile file) {
- ResourceReference[] list = RelativeFolderReferenceList.getInstance().getAllResources(file);
- if (list.length > 0) {
- return list[list.length - 1];
- }
- return null;
- }
-
- public ResourceReference getRuntimeAbsoluteFolder(IFile file) {
- ResourceReference[] list = AbsoluteFolderReferenceList.getInstance().getAllResources(file);
- if (list.length > 0) {
- return list[list.length - 1];
- }
- return null;
- }
-
- public List<TaglibData> getTagLibs() {
- List<TaglibData> clone = new ArrayList<TaglibData>();
- Iterator iter = taglibs.iterator();
- while (iter.hasNext()) {
- TaglibData taglib = (TaglibData)iter.next();
- if (!taglib.inList(clone)) {
- clone.add(taglib);
- }
- }
- return clone;
- }
-
- private boolean buildTaglibsDifferences(List newTaglibs, List delTaglibs) {
- Iterator lastIter = lastTaglibs.iterator();
- while (lastIter.hasNext()) {
- TaglibData oldTaglib = (TaglibData)lastIter.next();
- Iterator newIter = newTaglibs.iterator();
- while (newIter.hasNext()) {
- if (oldTaglib.isEquals((TaglibData)newIter.next())) {
- newIter.remove();
- oldTaglib = null;
- break;
- }
- }
- if (oldTaglib != null) {
- delTaglibs.add(oldTaglib);
- }
- }
- return newTaglibs.size() > 0 || delTaglibs.size() > 0;
- }
-
- public void fireTaglibsChanged() {
- List newTaglibs = getTagLibs();
- List delTaglibs = new ArrayList();
- if (buildTaglibsDifferences(newTaglibs, delTaglibs)) {
- if (VpeDebug.PRINT_SOURCE_MUTATION_EVENT) {
- System.out.println(">>> TaglibsChanged");
- }
- for (int i = 0; i < taglibListeners.length; i++) {
- taglibListeners[i].taglibPrefixChanged(null);
- fireTaglibChanged(taglibListeners[i], newTaglibs, delTaglibs);
- }
- lastTaglibs = getTagLibs();
- }
- taglibChanged = false;
- }
-
- private void fireTaglibChanged(VpeTaglibListener taglibListener, List newTaglibs, List delTaglibs) {
- Iterator iter = delTaglibs.iterator();
- while (iter.hasNext()) {
- TaglibData taglib = (TaglibData)iter.next();
- taglibListener.removeTaglib(taglib.getUri(), taglib.getPrefix());
- }
- iter = newTaglibs.iterator();
- while (iter.hasNext()) {
- TaglibData taglib = (TaglibData)iter.next();
- taglibListener.addTaglib(taglib.getUri(), taglib.getPrefix());
- }
- }
-
- public boolean isTaglibChanged() {
- if (!taglibChanged) return false;
- List newTaglibs = getTagLibs();
- List delTaglibs = new ArrayList();
- return buildTaglibsDifferences(newTaglibs, delTaglibs);
- }
-
- public WtpKbConnector getConnector() {
- return connector;
- }
-
- boolean registerTaglibs(WtpKbConnector wtpKbConnector, VpeTaglibManager taglibManager, IDocument document) {
- if(wtpKbConnector == null) return false;
- TLDCMDocumentManager manager = TaglibController.getTLDCMDocumentManager(document);
- if(taglibManager != null) {
- List list = taglibManager.getTagLibs();
- if(list != null) {
- Iterator it = list.iterator();
- while(it.hasNext()) {
- TaglibData data = (TaglibData)it.next();
- IEditorInput ei = editPart.getEditorInput();
- TLDRegisterHelper.registerTld(data, (JspWtpKbConnector)wtpKbConnector, document, ei);
- }
- return true;
- }
- }
- if(manager != null) {
- List list = manager.getTaglibTrackers();
- for (int i = 0; i < list.size(); i++) {
- TaglibTracker tracker = (TaglibTracker)list.get(i);
- if(tracker == null) continue;
- String version = TLDVersionHelper.getTldVersion(tracker);
- KbTldResource resource = new KbTldResource(tracker.getURI(), "", tracker.getPrefix(), version);
- wtpKbConnector.registerResource(resource);
- }
- return true;
- }
- return false;
- }
-
- public nsIDOMNode getCurrentVisualNode() {
- return currentVisualNode;
- }
-
- public void setCurrentVisualNode(nsIDOMNode currentVisualNode) {
- this.currentVisualNode = currentVisualNode;
- }
-
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor.context;
+
+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 org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jst.jsp.core.internal.contentmodel.TaglibController;
+import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager;
+import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TaglibTracker;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.jboss.tools.common.kb.KbConnectorFactory;
+import org.jboss.tools.common.kb.KbConnectorType;
+import org.jboss.tools.common.kb.KbTldResource;
+import org.jboss.tools.common.kb.wtp.JspWtpKbConnector;
+import org.jboss.tools.common.kb.wtp.TLDVersionHelper;
+import org.jboss.tools.common.kb.wtp.WtpKbConnector;
+import org.jboss.tools.common.model.XModel;
+import org.jboss.tools.common.model.project.IModelNature;
+import org.jboss.tools.common.model.util.EclipseResourceUtil;
+import org.jboss.tools.jst.jsp.editor.IVisualContext;
+import org.jboss.tools.jst.jsp.editor.TLDRegisterHelper;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.jst.web.tld.TaglibData;
+import org.jboss.tools.jst.web.tld.VpeTaglibListener;
+import org.jboss.tools.jst.web.tld.VpeTaglibManager;
+import org.jboss.tools.vpe.VpeDebug;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.VpeEditorPart;
+import org.jboss.tools.vpe.editor.VpeSourceDomBuilder;
+import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
+import org.jboss.tools.vpe.editor.bundle.BundleMap;
+import org.jboss.tools.vpe.editor.css.AbsoluteFolderReferenceList;
+import org.jboss.tools.vpe.editor.css.CSSReferenceList;
+import org.jboss.tools.vpe.editor.css.RelativeFolderReferenceList;
+import org.jboss.tools.vpe.editor.css.ResourceReference;
+import org.jboss.tools.vpe.editor.css.TaglibReferenceList;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.jboss.tools.vpe.editor.util.FileUtil;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * Contains the information on edited page.
+ */
+
+public class VpePageContext implements VpeTaglibManager, IVisualContext {
+ private VpeTemplateManager templateManager;
+ private List taglibs = new ArrayList();
+ private Set connectorDocuments = new HashSet();
+ private Map taglibMap = new HashMap();
+ private VpeTaglibListener[] taglibListeners = new VpeTaglibListener[0];
+ private BundleMap bundle;
+ private Set bundleDependencySet = new HashSet();
+ private VpeSourceDomBuilder sourceBuilder;
+ private VpeVisualDomBuilder visualBuilder;
+ private VpeEditorPart editPart;
+ private List lastTaglibs = new ArrayList();
+ private boolean taglibChanged = false;
+ WtpKbConnector connector;
+ private nsIDOMNode currentVisualNode;
+
+ public VpePageContext(VpeTemplateManager templateManager, BundleMap bundle, VpeEditorPart editPart) {
+ this.templateManager = templateManager;
+ this.bundle = bundle;
+ this.editPart = editPart;
+ }
+
+ public VpeSourceDomBuilder getSourceBuilder(){
+ return sourceBuilder;
+ }
+
+ public boolean isAbsolutePosition(){
+ if("yes".equals(VpePreference.USE_ABSOLUTE_POSITION.getValue()))return true;
+ else return false;
+ }
+
+ public void setSourceDomBuilder(VpeSourceDomBuilder sourceBuilder) {
+ this.sourceBuilder = sourceBuilder;
+ refreshConnector();
+ }
+
+ public void refreshConnector() {
+ try {
+ IDocument document = sourceBuilder.getStructuredTextViewer().getDocument();
+ if (document!= null) {
+ connectorDocuments.add(document);
+ connector = (WtpKbConnector)KbConnectorFactory.getIntstance().createConnector(KbConnectorType.JSP_WTP_KB_CONNECTOR, document);
+ }
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+ }
+
+ public VpeVisualDomBuilder getVisualBuilder(){
+ return visualBuilder;
+ }
+
+ public void setVisualDomBuilder(VpeVisualDomBuilder visualBuilder) {
+ this.visualBuilder = visualBuilder;
+ }
+
+ public VpeDomMapping getDomMapping () {
+ return visualBuilder.getDomMapping();
+ }
+
+ public void clearAll() {
+ taglibs.clear();
+ taglibMap.clear();
+ bundleDependencySet.clear();
+ bundle.clearAll();
+ }
+
+ public void dispose() {
+ for (Iterator iterator = connectorDocuments.iterator(); iterator.hasNext();) {
+ IDocument document = (IDocument) iterator.next();
+ KbConnectorFactory.getIntstance().removeConnector(KbConnectorType.JSP_WTP_KB_CONNECTOR, document);
+ }
+ connectorDocuments.clear();
+ connectorDocuments = null;
+ bundle.dispose();
+ clearAll();
+ taglibListeners=null;
+ editPart=null;
+ connector=null;
+ sourceBuilder=null;
+ visualBuilder=null;
+ }
+
+ public void setTaglib(int id, String newUri, String newPrefix, boolean ns) {
+ if (newUri != null && newPrefix != null) {
+ TaglibData data = new TaglibData(id, newUri, newPrefix, ns);
+ if (!taglibs.contains(data)) {
+ taglibs.add(data);
+ rebuildTaglibMap();
+ }
+ }
+ /*for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ if (taglib.getId() == id) {
+ if (newUri != null && newPrefix != null) {
+ if (!newUri.equals(taglib.getUri()) || !newPrefix.equals(taglib.getPrefix())) {
+ taglibs.set(i, new TaglibData(id, newUri, newPrefix, ns));
+ rebuildTaglibMap();
+ }
+ } else {
+ taglibs.remove(i);
+ rebuildTaglibMap();
+ }
+ return;
+ }
+ }
+ if (newUri != null && newPrefix != null) {
+ taglibs.add(new TaglibData(id, newUri, newPrefix, ns));
+ rebuildTaglibMap();
+ }*/
+ }
+
+ public String getTemplateTaglibPrefix(String sourceTaglibPrefix) {
+ return (String) taglibMap.get(sourceTaglibPrefix);
+ }
+
+ private void rebuildTaglibMap() {
+ taglibMap.clear();
+ Set prefixSet = new HashSet();
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ String prefix = taglib.getPrefix();
+ if (!prefixSet.contains(prefix)) {
+ String templatePrefix = templateManager.getTemplateTaglibPrefix(taglib.getUri());
+ if (templatePrefix != null) {
+ taglibMap.put(prefix, templatePrefix);
+ }
+ prefixSet.add(prefix);
+ }
+ }
+ taglibChanged = true;
+
+ try {
+ registerTaglibs(connector, this, getSourceBuilder().getStructuredTextViewer().getDocument());
+ } catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+ }
+
+ public void addTaglibListener(VpeTaglibListener listener) {
+ if (listener != null) {
+ VpeTaglibListener[] newTaglibListeners = new VpeTaglibListener[taglibListeners.length + 1];
+ System.arraycopy(taglibListeners, 0, newTaglibListeners, 0, taglibListeners.length);
+ taglibListeners = newTaglibListeners;
+ taglibListeners[taglibListeners.length - 1] = listener;
+ }
+ }
+
+ public void removeTaglibListener(VpeTaglibListener listener) {
+ if (listener == null || taglibListeners.length == 0) return;
+ int index = -1;
+ for (int i = 0; i < taglibListeners.length; i++) {
+ if (listener == taglibListeners[i]){
+ index = i;
+ break;
+ }
+ }
+ if (index == -1) return;
+ if (taglibListeners.length == 1) {
+ taglibListeners = new VpeTaglibListener[0];
+ return;
+ }
+ VpeTaglibListener[] newTaglibListeners = new VpeTaglibListener[taglibListeners.length - 1];
+ System.arraycopy(taglibListeners, 0, newTaglibListeners, 0, index);
+ System.arraycopy(taglibListeners, index + 1, newTaglibListeners, index, taglibListeners.length - index - 1);
+ taglibListeners = newTaglibListeners;
+ }
+
+ public BundleMap getBundle() {
+ return bundle;
+ }
+
+ public void addBundleDependency(Element sourceNode) {
+ bundleDependencySet.add(sourceNode);
+ }
+
+ public void removeBundleDependency(Element sourceNode) {
+ bundleDependencySet.remove(sourceNode);
+ }
+
+ public void refreshBundleValues() {
+ Iterator iterator = bundleDependencySet.iterator();
+ while (iterator.hasNext()) {
+ Element sourceElement = (Element) iterator.next();
+ visualBuilder.refreshBundleValues(sourceElement);
+ }
+ }
+
+ public boolean isCorrectNS(Node sourceNode) {
+ String sourcePrefix = sourceNode.getPrefix();
+ if (sourcePrefix == null || ((ElementImpl)sourceNode).isJSPTag()) {
+ return true;
+ }
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ if (sourcePrefix.equals(taglib.getPrefix())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String getSourceTaglibUri(Node sourceNode) {
+ String sourcePrefix = sourceNode.getPrefix();
+ if (sourcePrefix == null || ((ElementImpl)sourceNode).isJSPTag()) {
+ return null;
+ }
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ if (sourcePrefix.equals(taglib.getPrefix())) {
+ return taglib.getUri();
+ }
+ }
+ return null;
+ }
+
+ public VpeEditorPart getEditPart() {
+ return editPart;
+ }
+
+ public void openIncludeFile(String file) {
+ IEditorInput input = editPart.getEditorInput();
+ IWorkbenchPage workbenchPage = VpePlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ try{
+ IFile f = FileUtil.getFile(input, file);
+ if (f != null) {
+ IDE.openEditor(workbenchPage, f, true);
+ }
+ }catch(Exception ex){
+ VpePlugin.reportProblem(ex);
+ }
+ }
+
+ public ResourceReference[] getIncludeTaglibs() {
+ IEditorInput input = getEditPart().getEditorInput();
+ IFile file = null;
+ if (input instanceof IFileEditorInput) {
+ file = ((IFileEditorInput)input).getFile();
+ }
+ ResourceReference[] resourceReferences = new ResourceReference[0];
+ if (file != null) {
+ resourceReferences = TaglibReferenceList.getInstance().getAllResources(file);
+ }
+ return resourceReferences;
+ }
+
+ public ResourceReference[] getIncludeCss() {
+ IEditorInput input = getEditPart().getEditorInput();
+ IFile file = null;
+ if (input instanceof IFileEditorInput) {
+ file = ((IFileEditorInput)input).getFile();
+ }
+ ResourceReference[] resourceReferences = new ResourceReference[0];
+ if (file != null) {
+ resourceReferences = CSSReferenceList.getInstance().getAllResources(file);
+ }
+ return resourceReferences;
+ }
+
+ public void installIncludeElements() {
+ ResourceReference[] list = getIncludeTaglibs();
+ for (int i = 0; i < list.length; i++) {
+ ResourceReference reference = list[i];
+ setTaglib(i, reference.getLocation(), reference.getProperties(), false);
+ }
+
+ list = getIncludeCss();
+ for (int i = 0; i < list.length; i++) {
+ visualBuilder.addLinkNodeToHead(list[i].getLocation(), "yes");
+ }
+ }
+
+ public ResourceReference getRuntimeRelativeFolder(IFile file) {
+ ResourceReference[] list = RelativeFolderReferenceList.getInstance().getAllResources(file);
+ if (list.length > 0) {
+ return list[list.length - 1];
+ }
+ return null;
+ }
+
+ public ResourceReference getRuntimeAbsoluteFolder(IFile file) {
+ ResourceReference[] list = AbsoluteFolderReferenceList.getInstance().getAllResources(file);
+ if (list.length > 0) {
+ return list[list.length - 1];
+ }
+ return null;
+ }
+
+ public List<TaglibData> getTagLibs() {
+ List<TaglibData> clone = new ArrayList<TaglibData>();
+ Iterator iter = taglibs.iterator();
+ while (iter.hasNext()) {
+ TaglibData taglib = (TaglibData)iter.next();
+ //if (!taglib.inList(clone)) {
+ if (!clone.contains(taglib)) {
+ clone.add(taglib);
+ }
+ }
+ return clone;
+ }
+
+ private boolean buildTaglibsDifferences(List newTaglibs, List delTaglibs) {
+ Iterator lastIter = lastTaglibs.iterator();
+ while (lastIter.hasNext()) {
+ TaglibData oldTaglib = (TaglibData)lastIter.next();
+ Iterator newIter = newTaglibs.iterator();
+ while (newIter.hasNext()) {
+ //if (oldTaglib.isEquals((TaglibData)newIter.next())) {
+ if (oldTaglib.equals((TaglibData)newIter.next())) {
+ newIter.remove();
+ oldTaglib = null;
+ break;
+ }
+ }
+ if (oldTaglib != null) {
+ delTaglibs.add(oldTaglib);
+ }
+ }
+ return newTaglibs.size() > 0 || delTaglibs.size() > 0;
+ }
+
+ public void fireTaglibsChanged() {
+ List newTaglibs = getTagLibs();
+ List delTaglibs = new ArrayList();
+ if (buildTaglibsDifferences(newTaglibs, delTaglibs)) {
+ if (VpeDebug.PRINT_SOURCE_MUTATION_EVENT) {
+ System.out.println(">>> TaglibsChanged");
+ }
+ for (int i = 0; i < taglibListeners.length; i++) {
+ taglibListeners[i].taglibPrefixChanged(null);
+ fireTaglibChanged(taglibListeners[i], newTaglibs, delTaglibs);
+ }
+ lastTaglibs = getTagLibs();
+ }
+ taglibChanged = false;
+ }
+
+ private void fireTaglibChanged(VpeTaglibListener taglibListener, List newTaglibs, List delTaglibs) {
+ Iterator iter = delTaglibs.iterator();
+ while (iter.hasNext()) {
+ TaglibData taglib = (TaglibData)iter.next();
+ taglibListener.removeTaglib(taglib.getUri(), taglib.getPrefix());
+ }
+ iter = newTaglibs.iterator();
+ while (iter.hasNext()) {
+ TaglibData taglib = (TaglibData)iter.next();
+ taglibListener.addTaglib(taglib.getUri(), taglib.getPrefix());
+ }
+ }
+
+ public boolean isTaglibChanged() {
+ //TODO Max Areshkau coused slow work vpe when we editing on source page text node
+// if (!taglibChanged) return false;
+// List newTaglibs = getTagLibs();
+// List delTaglibs = new ArrayList();
+// return buildTaglibsDifferences(newTaglibs, delTaglibs);
+ return false;
+ }
+
+ public WtpKbConnector getConnector() {
+ return connector;
+ }
+
+ boolean registerTaglibs(WtpKbConnector wtpKbConnector, VpeTaglibManager taglibManager, IDocument document) {
+ if(wtpKbConnector == null) return false;
+ TLDCMDocumentManager manager = TaglibController.getTLDCMDocumentManager(document);
+ if(taglibManager != null) {
+ List list = taglibManager.getTagLibs();
+ if(list != null) {
+ Iterator it = list.iterator();
+ while(it.hasNext()) {
+ TaglibData data = (TaglibData)it.next();
+ IEditorInput ei = editPart.getEditorInput();
+ TLDRegisterHelper.registerTld(data, (JspWtpKbConnector)wtpKbConnector, document, ei);
+ }
+ return true;
+ }
+ }
+ if(manager != null) {
+ List list = manager.getTaglibTrackers();
+ for (int i = 0; i < list.size(); i++) {
+ TaglibTracker tracker = (TaglibTracker)list.get(i);
+ if(tracker == null) continue;
+ String version = TLDVersionHelper.getTldVersion(tracker);
+ KbTldResource resource = new KbTldResource(tracker.getURI(), "", tracker.getPrefix(), version);
+ wtpKbConnector.registerResource(resource);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ public nsIDOMNode getCurrentVisualNode() {
+ return currentVisualNode;
+ }
+
+ public void setCurrentVisualNode(nsIDOMNode currentVisualNode) {
+ this.currentVisualNode = currentVisualNode;
+ }
+
}
\ No newline at end of file
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaDomEventListener.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaDomEventListener.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaDomEventListener.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -123,7 +123,7 @@
*/
public void handleEvent(nsIDOMEvent domEvent) {
try{
-
+
if(getEditorDomEventListener()==null){
return;
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaEditor.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaEditor.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaEditor.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,590 +1,604 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor.mozilla;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.graphics.Color;
-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.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IReusableEditor;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.editors.text.ILocationProvider;
-import org.eclipse.ui.part.EditorPart;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.VpeController;
-import org.jboss.tools.vpe.editor.css.VpeResourcesDialog;
-import org.jboss.tools.vpe.editor.preferences.VpeEditorPreferencesPage;
-import org.jboss.tools.vpe.editor.toolbar.IVpeToolBarManager;
-import org.jboss.tools.vpe.editor.toolbar.VpeToolBarManager;
-import org.jboss.tools.vpe.editor.toolbar.format.FormatControllerManager;
-import org.jboss.tools.vpe.editor.toolbar.format.TextFormattingToolBar;
-import org.jboss.tools.vpe.editor.util.HTML;
-import org.jboss.tools.vpe.messages.VpeUIMessages;
-import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
-import org.mozilla.interfaces.nsIClipboardDragDropHookList;
-import org.mozilla.interfaces.nsIDOMDocument;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMEventTarget;
-import org.mozilla.interfaces.nsIDOMNamedNodeMap;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.mozilla.interfaces.nsIDOMNodeList;
-import org.mozilla.interfaces.nsISelection;
-import org.mozilla.interfaces.nsISelectionPrivate;
-
-public class MozillaEditor extends EditorPart implements IReusableEditor {
- protected static final String INIT_URL = "file://" + (new File(VpePlugin.getDefault().getResourcePath("ve"), "init.html")).getAbsolutePath();
-// private static final String INIT_URL = "chrome://vpe/content/init.html"; //$NON-NLS-1$
- private static final String CONTENT_AREA_ID = "__content__area__"; //$NON-NLS-1$
-
- static String SELECT_BAR = "SELECT_LBAR"; //$NON-NLS-1$
- private XulRunnerEditor xulRunnerEditor;
- private nsIDOMDocument domDocument;
- private nsIDOMEventTarget documentEventTarget;
- private nsIDOMElement contentArea;
- private nsIDOMNode headNode;
- private nsIDOMEventTarget contentAreaEventTarget;
- private MozillaDomEventListener contentAreaEventListener = new MozillaDomEventListener();
- //TODO Max Areshkau may be we need delete this
- //private MozillaBaseEventListener baseEventListener = null;
- private EditorLoadWindowListener editorLoadWindowListener;
- //
- private EditorDomEventListener editorDomEventListener;
- private IVpeToolBarManager vpeToolBarManager;
- private FormatControllerManager formatControllerManager = new FormatControllerManager();
- private VpeController controller;
- private Link link = null;
-
- public void doSave(IProgressMonitor monitor) {
- }
-
- public void doSaveAs() {
- }
-
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- super.setInput(input);
- }
-
- public void setInput(IEditorInput input) {
- boolean isVisualRefreshRequired = (getEditorInput() != null && getEditorInput() != input && controller != null);
- super.setInput(input);
- if(isVisualRefreshRequired) controller.visualRefresh();
- }
-
- public boolean isDirty() {
- return false;
- }
-
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- public void setController(VpeController controller){
- this.controller = controller;
- formatControllerManager.setVpeController(controller);
- controller.setToolbarFormatControllerManager(formatControllerManager);
- }
-
- public void createPartControl(final Composite parent) {
- vpeToolBarManager = new VpeToolBarManager();
- //Setting Layout for the parent Composite
- GridLayout layout = new GridLayout(2,false);
- layout.marginHeight = 0;
- layout.marginWidth = 2;
- layout.verticalSpacing = 2;
- layout.horizontalSpacing = 2;
- layout.marginBottom = 0;
- parent.setLayout(layout);
-
- // Composite for the left Vertical toolbar
- Composite cmpVerticalToolbar = new Composite(parent, SWT.NONE);
- layout = new GridLayout(1,false);
- layout.marginHeight = 2;
- layout.marginWidth = 0;
- layout.verticalSpacing = 0;
- cmpVerticalToolbar.setLayout(layout);
- cmpVerticalToolbar.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- // Editors and Toolbar composite
- Composite cmpEdTl = new Composite(parent, SWT.NONE);
- GridLayout layoutEdTl = new GridLayout(1, false);
- layoutEdTl.verticalSpacing = 0;
- layoutEdTl.marginHeight = 0;
- layoutEdTl.marginBottom = 3;
- layoutEdTl.marginWidth = 0;
- cmpEdTl.setLayout(layoutEdTl);
- cmpEdTl.setLayoutData(new GridData(GridData.FILL_BOTH));
-
-
- // Use vpeToolBarManager to create a horizontal toolbar.
- if(vpeToolBarManager!=null) {
- vpeToolBarManager.createToolBarComposite(cmpEdTl);
- vpeToolBarManager.addToolBar(new TextFormattingToolBar(formatControllerManager));
- // Create a Toolbar menu button
- vpeToolBarManager.createMenuComposite(cmpVerticalToolbar);
- }
-
- // The Left standalone Vertical Tool Bar
- final ToolBar verBar = new ToolBar(cmpVerticalToolbar, SWT.VERTICAL|SWT.FLAT);
- verBar.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- ToolItem item = null;
- item = createToolItem(verBar, SWT.BUTTON1, "icons/preference.gif", VpeUIMessages.PREFERENCES); //$NON-NLS-1$
- item.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- VpeEditorPreferencesPage.openPreferenceDialog();
- }
- });
-
- item = createToolItem(verBar, SWT.BUTTON1, "icons/refresh.gif", VpeUIMessages.REFRESH); //$NON-NLS-1$
- item.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- if(controller!=null) {
- controller.visualRefresh();
- }
- }
- });
- item = createToolItem(verBar, SWT.BUTTON1, "icons/point_to_css.gif", VpeUIMessages.PAGE_DESIGN_OPTIONS); //$NON-NLS-1$
- item.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- IEditorInput input = getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) input).getFile();
- VpeResourcesDialog.run(file);
- } else if (input instanceof ILocationProvider) {
- ILocationProvider provider = (ILocationProvider) input;
- IPath path = provider.getPath(input);
- if (path != null)
- VpeResourcesDialog.run(path);
- }
- }
- });
- verBar.pack();
-
- //Create a composite to the Editor
- Composite cmpEd = new Composite (cmpEdTl, SWT.NATIVE);
- GridLayout layoutEd = new GridLayout(1, false);
- layoutEd.marginBottom = 0;
- layoutEd.marginHeight = 1;
- layoutEd.marginWidth = 0;
- layoutEd.marginRight = 0;
- layoutEd.marginLeft = 1;
- layoutEd.verticalSpacing = 0;
- layoutEd.horizontalSpacing = 0;
- cmpEd.setLayout(layoutEd);
- cmpEd.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- //TODO Add a paintListener to cmpEd and give him a border top and left only
- Color buttonDarker = parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
- cmpEd.setBackground(buttonDarker);
-
- try {
- xulRunnerEditor = new XulRunnerEditor(cmpEd) {
- public void onLoadWindow() {
- super.onLoadWindow();
- MozillaEditor.this.onLoadWindow();
- }
- public void onElementResize(nsIDOMElement element, int resizerConstrains, int top, int left, int width, int height) {
- if (editorDomEventListener != null) {
- editorDomEventListener.elementResized(element, resizerConstrains, top, left, width, height);
- }
- }
- public void onShowTooltip(int x, int y, String text) {
- if (editorDomEventListener != null) {
- editorDomEventListener.onShowTooltip(x, y, text);
- }
- }
- public void onHideTooltip() {
- if (editorDomEventListener != null) {
- editorDomEventListener.onHideTooltip();
- }
- }
- };
-
- xulRunnerEditor.setURL(INIT_URL);
- xulRunnerEditor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- }
- catch (Exception e) {
- VpePlugin.getPluginLog().logError(e);
-
- layout.verticalSpacing = 10;
- Label title = new Label(cmpEd, SWT.WRAP);
- title.setText(VpeUIMessages.MOZILLA_LOADING_ERROR);
- title.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- link = new Link(cmpEd, SWT.WRAP);
- link.setText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK_TEXT);
- link.setToolTipText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
- link.setForeground(link.getDisplay().getSystemColor(SWT.COLOR_BLUE));
- link.addMouseListener(new MouseListener() {
- public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
- BusyIndicator.showWhile(link.getDisplay(), new Runnable() {
- public void run() {
- URL theURL=null;;
- try {
- theURL = new URL(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
- } catch (MalformedURLException e) {
- VpePlugin.reportProblem(e);
- }
- IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
- try {
- support.getExternalBrowser().openURL(theURL);
- } catch (PartInitException e) {
- VpePlugin.reportProblem(e);
- }
- }
- });
- }
-
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
-
- }
-
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
-
- }
- });
- link.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label fill = new Label(cmpEd, SWT.WRAP);
- fill.setLayoutData(new GridData(GridData.FILL_BOTH));
- }
- }
-
- private ToolItem createToolItem(ToolBar parent, int type, String image, String toolTipText) {
- ToolItem item = new ToolItem(parent, type);
- item.setImage(ImageDescriptor.createFromFile(MozillaEditor.class, image).createImage());
- item.setToolTipText(toolTipText);
- return item;
- }
-
- public void setFocus() {
- if(xulRunnerEditor!=null) {
- xulRunnerEditor.setFocus();
- } else {
- //link.setFocus();
- }
- }
-
- public void dispose() {
- removeDomEventListeners();
- if(getController()!=null) {
- controller.dispose();
- controller=null;
- }
- if (xulRunnerEditor != null) {
- xulRunnerEditor.getBrowser().dispose();
- xulRunnerEditor = null;
- }
-
- super.dispose();
-
- }
-
- public void setEditorLoadWindowListener(EditorLoadWindowListener listener) {
- editorLoadWindowListener = listener;
- }
-
- public void setEditorDomEventListener(EditorDomEventListener listener) {
- editorDomEventListener = listener;
- if (contentAreaEventListener != null) {
- contentAreaEventListener.setEditorDomEventListener(listener);
- }
- }
-
- public nsIDOMDocument getDomDocument() {
- if (domDocument == null) {
- domDocument = xulRunnerEditor.getDOMDocument();
- }
- return domDocument;
- }
-
- /**
- * @param domDocument the domDocument to set
- */
- protected void setDomDocument(nsIDOMDocument domDocument) {
-
- this.domDocument = domDocument;
- }
-
- public nsIDOMElement getContentArea() {
- return contentArea;
- }
- /**
- * Sets content area element
- * @return
- */
- protected void setContentArea(nsIDOMElement element) {
-
- this.contentArea=element;
- }
-
- public nsIDOMNode getHeadNode() {
- return headNode;
- }
-
- public Menu getMenu() {
- return xulRunnerEditor.getBrowser().getMenu();
- }
-
- public Control getControl() {
- return xulRunnerEditor.getBrowser();
- }
-
- protected nsIDOMElement findContentArea() {
- nsIDOMElement area = xulRunnerEditor.getDOMDocument().getDocumentElement();
- nsIDOMNodeList nodeList = xulRunnerEditor.getDOMDocument().getElementsByTagName(HTML.TAG_BODY);
- long length = nodeList.getLength();
- for(long i=0; i<length; i++) {
- nsIDOMNode node = nodeList.item(i);
- if (isContentArea(node)) {
- if (node.getNodeType() != nsIDOMNode.ELEMENT_NODE) {
- throw new RuntimeException("The content area node should by element node.");
- }
-
- area = (nsIDOMElement) node.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
- break;
- }
- }
-// area = findContentArea(root);
- if (area == null) {
- return null;
- }
-
- nsIDOMNode root = xulRunnerEditor.getDOMDocument().getDocumentElement();
- headNode = findHeadNode(root);
-
-
- return area;
- }
-
- private nsIDOMNode findHeadNode(nsIDOMNode root){
- nsIDOMNode headNode = findChildNode(root, HTML.TAG_HEAD); //$NON-NLS-1$
- return headNode;
- }
-
- private nsIDOMNode findChildNode(nsIDOMNode parent, String name) {
- nsIDOMNodeList list = parent.getChildNodes();
- nsIDOMNode node;
- for (int i=0;i<list.getLength();i++) {
- node = list.item(i);
- if (node.getNodeName().equalsIgnoreCase(name)) {
- return node;
- }
- }
- return null;
- }
-
- private nsIDOMElement findContentArea(nsIDOMNode node) {
- nsIDOMElement area = null;
- if (node != null && node.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
- nsIDOMNodeList children = node.getChildNodes();
- if (children != null) {
- long length = children.getLength();
- for (long i = 0; i < length; i++) {
- nsIDOMNode child = children.item(i);
- if (isContentArea(child)) {
- if (child.getNodeType() != nsIDOMNode.ELEMENT_NODE) {
- throw new RuntimeException("The content area node should by element node.");
- }
- area = (nsIDOMElement)child;
- break;
- }
- area = findContentArea(child);
- if (area != null) {
- break;
- }
- }
- }
- }
- return area;
- }
-
- private boolean isContentArea(nsIDOMNode node) {
- boolean ret = false;
- if (HTML.TAG_BODY.equalsIgnoreCase(node.getNodeName())) {
- nsIDOMNamedNodeMap map = node.getAttributes();
- if (map != null) {
- long length = map.getLength();
- for (int i = 0; i < length; i++) {
- nsIDOMNode attr = map.item(i);
- ret = attr.getNodeType() == nsIDOMNode.ATTRIBUTE_NODE
- && HTML.ATTR_ID.equalsIgnoreCase(attr.getNodeName())
- && CONTENT_AREA_ID.equalsIgnoreCase(attr.getNodeValue());
- if (ret) {
- break;
- }
- }
- }
- }
- return ret;
- }
-
- private void onLoadWindow() {
- contentArea = findContentArea();
- addDomEventListeners();
- addSelectionListener();
- if (editorLoadWindowListener != null) {
- editorLoadWindowListener.load();
- }
- }
-
- private void addDomEventListeners() {
- if (contentArea != null) {
- if (contentAreaEventListener != null) {
- contentAreaEventListener.setVisualEditor(xulRunnerEditor);
- contentAreaEventTarget = (nsIDOMEventTarget) contentArea.queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
-
- //add mozilla event handlers
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.CLICKEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEDOWNEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEUPEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEMOVEEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.CONTEXTMENUEVENTTYPE, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGDROPEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGENTEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGEXITEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGGESTUREEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGOVEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.addEventListener(MozillaDomEventListener.DBLCLICK, contentAreaEventListener, false);//$NON-NLS-1$
- documentEventTarget = (nsIDOMEventTarget) getDomDocument().queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
- documentEventTarget.addEventListener(MozillaDomEventListener.KEYPRESS, contentAreaEventListener, false); //$NON-NLS-1$
- } else {
- //baseEventListener = new MozillaBaseEventListener();
- }
- }
- }
-
- private void removeDomEventListeners() {
- if (contentAreaEventTarget != null && contentAreaEventListener != null) {
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.CLICKEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEDOWNEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEUPEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEMOVEEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.CONTEXTMENUEVENTTYPE, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGDROPEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGENTEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGEXITEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGGESTUREEVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGOVEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
- contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DBLCLICK, contentAreaEventListener, false);//$NON-NLS-1$
-
- }
- if (domDocument != null && documentEventTarget != null) {
- documentEventTarget.removeEventListener(MozillaDomEventListener.KEYPRESS, contentAreaEventListener, false); //$NON-NLS-1$
- }
- }
-
- private void addSelectionListener() {
- if (contentAreaEventListener != null&&xulRunnerEditor!=null) {
-
- nsISelection selection = xulRunnerEditor.getSelection();
- nsISelectionPrivate selectionPrivate = (nsISelectionPrivate) selection.queryInterface(nsISelectionPrivate.NS_ISELECTIONPRIVATE_IID);
- selectionPrivate.addSelectionListener(contentAreaEventListener);
-
- }
- }
-
- private void removeSelectionListener() {
- if (contentAreaEventListener != null&&xulRunnerEditor!=null) {
-
- nsISelection selection = xulRunnerEditor.getSelection();
- nsISelectionPrivate selectionPrivate = (nsISelectionPrivate) selection.queryInterface(nsISelectionPrivate.NS_ISELECTIONPRIVATE_IID);
- selectionPrivate.removeSelectionListener(contentAreaEventListener);
- }
- }
-
- public void setSelectionRectangle(nsIDOMElement element, int resizerConstrains, boolean scroll) {
- if (contentAreaEventListener != null) {
- xulRunnerEditor.setSelectionRectangle((nsIDOMElement)element, resizerConstrains, scroll);
- }
- }
-
- /**
- * Show resizer markers
- */
- public void showResizer() {
- if (contentAreaEventListener != null) {
- xulRunnerEditor.showResizer();
- }
- }
-
- /**
- * Hide resizer markers
- */
- public void hideResizer() {
- if (contentAreaEventListener != null) {
- xulRunnerEditor.hideResizer();
- }
- }
-
- /**
- * @return the xulRunnerEditor
- */
- public XulRunnerEditor getXulRunnerEditor() {
- return xulRunnerEditor;
- }
-
- /**
- * @param xulRunnerEditor the xulRunnerEditor to set
- */
- protected void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
- this.xulRunnerEditor = xulRunnerEditor;
- }
-
- /**
- * @return the controller
- */
- public VpeController getController() {
- return controller;
- }
-
- /**
- * @return the link
- */
- protected Link getLink() {
- return link;
- }
-
- /**
- * @param link the link to set
- */
- protected void setLink(Link link) {
- this.link = link;
- }
-
-
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor.mozilla;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.graphics.Color;
+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.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Link;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.IReusableEditor;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
+import org.eclipse.ui.editors.text.ILocationProvider;
+import org.eclipse.ui.part.EditorPart;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.VpeController;
+import org.jboss.tools.vpe.editor.css.VpeResourcesDialog;
+import org.jboss.tools.vpe.editor.preferences.VpeEditorPreferencesPage;
+import org.jboss.tools.vpe.editor.toolbar.IVpeToolBarManager;
+import org.jboss.tools.vpe.editor.toolbar.VpeToolBarManager;
+import org.jboss.tools.vpe.editor.toolbar.format.FormatControllerManager;
+import org.jboss.tools.vpe.editor.toolbar.format.TextFormattingToolBar;
+import org.jboss.tools.vpe.editor.util.HTML;
+import org.jboss.tools.vpe.messages.VpeUIMessages;
+import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
+import org.mozilla.interfaces.nsIClipboardDragDropHookList;
+import org.mozilla.interfaces.nsIDOMDocument;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMEventTarget;
+import org.mozilla.interfaces.nsIDOMNamedNodeMap;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.mozilla.interfaces.nsIDOMNodeList;
+import org.mozilla.interfaces.nsISelection;
+import org.mozilla.interfaces.nsISelectionPrivate;
+
+public class MozillaEditor extends EditorPart implements IReusableEditor {
+ protected static final String INIT_URL = "file://" + (new File(VpePlugin.getDefault().getResourcePath("ve"), "init.html")).getAbsolutePath();
+// private static final String INIT_URL = "chrome://vpe/content/init.html"; //$NON-NLS-1$
+ private static final String CONTENT_AREA_ID = "__content__area__"; //$NON-NLS-1$
+
+ static String SELECT_BAR = "SELECT_LBAR"; //$NON-NLS-1$
+ private XulRunnerEditor xulRunnerEditor;
+ private nsIDOMDocument domDocument;
+ private nsIDOMEventTarget documentEventTarget;
+ private nsIDOMElement contentArea;
+ private nsIDOMNode headNode;
+ private nsIDOMEventTarget contentAreaEventTarget;
+ private MozillaDomEventListener contentAreaEventListener = new MozillaDomEventListener();
+ //TODO Max Areshkau may be we need delete this
+ //private MozillaBaseEventListener baseEventListener = null;
+ private EditorLoadWindowListener editorLoadWindowListener;
+ //
+ private EditorDomEventListener editorDomEventListener;
+ private IVpeToolBarManager vpeToolBarManager;
+ private FormatControllerManager formatControllerManager = new FormatControllerManager();
+ private VpeController controller;
+ private Link link = null;
+
+ public void doSave(IProgressMonitor monitor) {
+ }
+
+ public void doSaveAs() {
+ }
+
+ public void init(IEditorSite site, IEditorInput input) throws PartInitException {
+ super.setInput(input);
+ }
+
+ public void setInput(IEditorInput input) {
+ boolean isVisualRefreshRequired = (getEditorInput() != null && getEditorInput() != input && controller != null);
+ super.setInput(input);
+ if(isVisualRefreshRequired) controller.visualRefresh();
+ }
+
+ public boolean isDirty() {
+ return false;
+ }
+
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
+
+ public void setController(VpeController controller){
+ this.controller = controller;
+ formatControllerManager.setVpeController(controller);
+ controller.setToolbarFormatControllerManager(formatControllerManager);
+ }
+
+ public void createPartControl(final Composite parent) {
+ vpeToolBarManager = new VpeToolBarManager();
+ //Setting Layout for the parent Composite
+ GridLayout layout = new GridLayout(2,false);
+ layout.marginHeight = 0;
+ layout.marginWidth = 2;
+ layout.verticalSpacing = 2;
+ layout.horizontalSpacing = 2;
+ layout.marginBottom = 0;
+ parent.setLayout(layout);
+
+ // Composite for the left Vertical toolbar
+ Composite cmpVerticalToolbar = new Composite(parent, SWT.NONE);
+ layout = new GridLayout(1,false);
+ layout.marginHeight = 2;
+ layout.marginWidth = 0;
+ layout.verticalSpacing = 0;
+ cmpVerticalToolbar.setLayout(layout);
+ cmpVerticalToolbar.setLayoutData(new GridData(GridData.FILL_VERTICAL));
+
+ // Editors and Toolbar composite
+ Composite cmpEdTl = new Composite(parent, SWT.NONE);
+ GridLayout layoutEdTl = new GridLayout(1, false);
+ layoutEdTl.verticalSpacing = 0;
+ layoutEdTl.marginHeight = 0;
+ layoutEdTl.marginBottom = 3;
+ layoutEdTl.marginWidth = 0;
+ cmpEdTl.setLayout(layoutEdTl);
+ cmpEdTl.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+
+ // Use vpeToolBarManager to create a horizontal toolbar.
+ if(vpeToolBarManager!=null) {
+ vpeToolBarManager.createToolBarComposite(cmpEdTl);
+ vpeToolBarManager.addToolBar(new TextFormattingToolBar(formatControllerManager));
+ // Create a Toolbar menu button
+ vpeToolBarManager.createMenuComposite(cmpVerticalToolbar);
+ }
+
+ // The Left standalone Vertical Tool Bar
+ ToolBar verBar = new ToolBar(cmpVerticalToolbar, SWT.VERTICAL|SWT.FLAT);
+ verBar.setLayoutData(new GridData(GridData.FILL_VERTICAL));
+
+ ToolItem item = null;
+ item = createToolItem(verBar, SWT.BUTTON1, "icons/preference.gif", VpeUIMessages.PREFERENCES); //$NON-NLS-1$
+ item.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ VpeEditorPreferencesPage.openPreferenceDialog();
+ }
+ });
+
+ item = createToolItem(verBar, SWT.BUTTON1, "icons/refresh.gif", VpeUIMessages.REFRESH); //$NON-NLS-1$
+ item.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ if(controller!=null) {
+ controller.visualRefresh();
+ }
+ }
+ });
+ item = createToolItem(verBar, SWT.BUTTON1, "icons/point_to_css.gif", VpeUIMessages.PAGE_DESIGN_OPTIONS); //$NON-NLS-1$
+ item.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ IEditorInput input = getEditorInput();
+ if (input instanceof IFileEditorInput) {
+ IFile file = ((IFileEditorInput) input).getFile();
+ VpeResourcesDialog.run(file);
+ } else if (input instanceof ILocationProvider) {
+ ILocationProvider provider = (ILocationProvider) input;
+ IPath path = provider.getPath(input);
+ if (path != null)
+ VpeResourcesDialog.run(path);
+ }
+ }
+ });
+ verBar.pack();
+
+ //Create a composite to the Editor
+ Composite cmpEd = new Composite (cmpEdTl, SWT.NATIVE);
+ GridLayout layoutEd = new GridLayout(1, false);
+ layoutEd.marginBottom = 0;
+ layoutEd.marginHeight = 1;
+ layoutEd.marginWidth = 0;
+ layoutEd.marginRight = 0;
+ layoutEd.marginLeft = 1;
+ layoutEd.verticalSpacing = 0;
+ layoutEd.horizontalSpacing = 0;
+ cmpEd.setLayout(layoutEd);
+ cmpEd.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ //TODO Add a paintListener to cmpEd and give him a border top and left only
+ Color buttonDarker = parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
+ cmpEd.setBackground(buttonDarker);
+
+ try {
+ xulRunnerEditor = new XulRunnerEditor(cmpEd) {
+ public void onLoadWindow() {
+ super.onLoadWindow();
+ MozillaEditor.this.onLoadWindow();
+ }
+ public void onElementResize(nsIDOMElement element, int resizerConstrains, int top, int left, int width, int height) {
+ if (editorDomEventListener != null) {
+ editorDomEventListener.elementResized(element, resizerConstrains, top, left, width, height);
+ }
+ }
+ public void onShowTooltip(int x, int y, String text) {
+ if (editorDomEventListener != null) {
+ editorDomEventListener.onShowTooltip(x, y, text);
+ }
+ }
+ public void onHideTooltip() {
+ if (editorDomEventListener != null) {
+ editorDomEventListener.onHideTooltip();
+ }
+ }
+ public void onDispose() {
+ removeDomEventListeners();
+ super.onDispose();
+ }
+ };
+
+ xulRunnerEditor.setURL(INIT_URL);
+ xulRunnerEditor.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ }
+ catch (Exception e) {
+ VpePlugin.getPluginLog().logError(e);
+
+ layout.verticalSpacing = 10;
+ Label title = new Label(cmpEd, SWT.WRAP);
+ title.setText(VpeUIMessages.MOZILLA_LOADING_ERROR);
+ title.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ link = new Link(cmpEd, SWT.WRAP);
+ link.setText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK_TEXT);
+ link.setToolTipText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
+ link.setForeground(link.getDisplay().getSystemColor(SWT.COLOR_BLUE));
+ link.addMouseListener(new MouseListener() {
+ public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
+ BusyIndicator.showWhile(link.getDisplay(), new Runnable() {
+ public void run() {
+ URL theURL=null;;
+ try {
+ theURL = new URL(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
+ } catch (MalformedURLException e) {
+ VpePlugin.reportProblem(e);
+ }
+ IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
+ try {
+ support.getExternalBrowser().openURL(theURL);
+ } catch (PartInitException e) {
+ VpePlugin.reportProblem(e);
+ }
+ }
+ });
+ }
+
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+
+ }
+ });
+ link.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label fill = new Label(cmpEd, SWT.WRAP);
+ fill.setLayoutData(new GridData(GridData.FILL_BOTH));
+ }
+ }
+
+ private ToolItem createToolItem(ToolBar parent, int type, String image, String toolTipText) {
+ ToolItem item = new ToolItem(parent, type);
+ item.setImage(ImageDescriptor.createFromFile(MozillaEditor.class, image).createImage());
+ item.setToolTipText(toolTipText);
+ return item;
+ }
+
+ public void setFocus() {
+ if(xulRunnerEditor!=null) {
+ xulRunnerEditor.setFocus();
+ } else {
+ //link.setFocus();
+ }
+ }
+
+ public void dispose() {
+ if (vpeToolBarManager != null) {
+ vpeToolBarManager.dispose();
+ vpeToolBarManager = null;
+ }
+
+ //removeDomEventListeners();
+ if(getController()!=null) {
+ controller.dispose();
+ controller=null;
+ }
+ if (xulRunnerEditor != null) {
+ xulRunnerEditor.getBrowser().dispose();
+ xulRunnerEditor = null;
+ }
+
+ this.controller = null;
+ formatControllerManager.setVpeController(null);
+ formatControllerManager=null;
+ super.dispose();
+
+ }
+
+ public void setEditorLoadWindowListener(EditorLoadWindowListener listener) {
+ editorLoadWindowListener = listener;
+ }
+
+ public void setEditorDomEventListener(EditorDomEventListener listener) {
+ editorDomEventListener = listener;
+ if (contentAreaEventListener != null) {
+ contentAreaEventListener.setEditorDomEventListener(listener);
+ }
+ }
+
+ public nsIDOMDocument getDomDocument() {
+ if (domDocument == null) {
+ domDocument = xulRunnerEditor.getDOMDocument();
+ }
+ return domDocument;
+ }
+
+ /**
+ * @param domDocument the domDocument to set
+ */
+ protected void setDomDocument(nsIDOMDocument domDocument) {
+
+ this.domDocument = domDocument;
+ }
+
+ public nsIDOMElement getContentArea() {
+ return contentArea;
+ }
+ /**
+ * Sets content area element
+ * @return
+ */
+ protected void setContentArea(nsIDOMElement element) {
+
+ this.contentArea=element;
+ }
+
+ public nsIDOMNode getHeadNode() {
+ return headNode;
+ }
+
+ public Menu getMenu() {
+ return xulRunnerEditor.getBrowser().getMenu();
+ }
+
+ public Control getControl() {
+ return xulRunnerEditor.getBrowser();
+ }
+
+ protected nsIDOMElement findContentArea() {
+ nsIDOMElement area = xulRunnerEditor.getDOMDocument().getDocumentElement();
+ nsIDOMNodeList nodeList = xulRunnerEditor.getDOMDocument().getElementsByTagName(HTML.TAG_BODY);
+ long length = nodeList.getLength();
+ for(long i=0; i<length; i++) {
+ nsIDOMNode node = nodeList.item(i);
+ if (isContentArea(node)) {
+ if (node.getNodeType() != nsIDOMNode.ELEMENT_NODE) {
+ throw new RuntimeException("The content area node should by element node.");
+ }
+
+ area = (nsIDOMElement) node.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
+ break;
+ }
+ }
+// area = findContentArea(root);
+ if (area == null) {
+ return null;
+ }
+
+ nsIDOMNode root = xulRunnerEditor.getDOMDocument().getDocumentElement();
+ headNode = findHeadNode(root);
+
+
+ return area;
+ }
+
+ private nsIDOMNode findHeadNode(nsIDOMNode root){
+ nsIDOMNode headNode = findChildNode(root, HTML.TAG_HEAD); //$NON-NLS-1$
+ return headNode;
+ }
+
+ private nsIDOMNode findChildNode(nsIDOMNode parent, String name) {
+ nsIDOMNodeList list = parent.getChildNodes();
+ nsIDOMNode node;
+ for (int i=0;i<list.getLength();i++) {
+ node = list.item(i);
+ if (node.getNodeName().equalsIgnoreCase(name)) {
+ return node;
+ }
+ }
+ return null;
+ }
+
+ private nsIDOMElement findContentArea(nsIDOMNode node) {
+ nsIDOMElement area = null;
+ if (node != null && node.getNodeType() == nsIDOMNode.ELEMENT_NODE) {
+ nsIDOMNodeList children = node.getChildNodes();
+ if (children != null) {
+ long length = children.getLength();
+ for (long i = 0; i < length; i++) {
+ nsIDOMNode child = children.item(i);
+ if (isContentArea(child)) {
+ if (child.getNodeType() != nsIDOMNode.ELEMENT_NODE) {
+ throw new RuntimeException("The content area node should by element node.");
+ }
+ area = (nsIDOMElement)child;
+ break;
+ }
+ area = findContentArea(child);
+ if (area != null) {
+ break;
+ }
+ }
+ }
+ }
+ return area;
+ }
+
+ private boolean isContentArea(nsIDOMNode node) {
+ boolean ret = false;
+ if (HTML.TAG_BODY.equalsIgnoreCase(node.getNodeName())) {
+ nsIDOMNamedNodeMap map = node.getAttributes();
+ if (map != null) {
+ long length = map.getLength();
+ for (int i = 0; i < length; i++) {
+ nsIDOMNode attr = map.item(i);
+ ret = attr.getNodeType() == nsIDOMNode.ATTRIBUTE_NODE
+ && HTML.ATTR_ID.equalsIgnoreCase(attr.getNodeName())
+ && CONTENT_AREA_ID.equalsIgnoreCase(attr.getNodeValue());
+ if (ret) {
+ break;
+ }
+ }
+ }
+ }
+ return ret;
+ }
+
+ private void onLoadWindow() {
+ contentArea = findContentArea();
+ addDomEventListeners();
+ addSelectionListener();
+ if (editorLoadWindowListener != null) {
+ editorLoadWindowListener.load();
+ }
+ }
+
+ private void addDomEventListeners() {
+ if (contentArea != null) {
+ if (contentAreaEventListener != null) {
+ contentAreaEventListener.setVisualEditor(xulRunnerEditor);
+ contentAreaEventTarget = (nsIDOMEventTarget) contentArea.queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
+
+ //add mozilla event handlers
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.CLICKEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEDOWNEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEUPEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.MOUSEMOVEEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.CONTEXTMENUEVENTTYPE, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGDROPEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGENTEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGEXITEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGGESTUREEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DRAGOVEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.addEventListener(MozillaDomEventListener.DBLCLICK, contentAreaEventListener, false);//$NON-NLS-1$
+ documentEventTarget = (nsIDOMEventTarget) getDomDocument().queryInterface(nsIDOMEventTarget.NS_IDOMEVENTTARGET_IID);
+ documentEventTarget.addEventListener(MozillaDomEventListener.KEYPRESS, contentAreaEventListener, false); //$NON-NLS-1$
+ } else {
+ //baseEventListener = new MozillaBaseEventListener();
+ }
+ }
+ }
+
+ protected void removeDomEventListeners() {
+ if (contentAreaEventTarget != null && contentAreaEventListener != null) {
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.CLICKEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEDOWNEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEUPEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.MOUSEMOVEEVENTTYPE, contentAreaEventListener, false); //$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.CONTEXTMENUEVENTTYPE, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGDROPEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGENTEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGEXITEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGGESTUREEVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DRAGOVEREVENT, contentAreaEventListener, false);//$NON-NLS-1$
+ contentAreaEventTarget.removeEventListener(MozillaDomEventListener.DBLCLICK, contentAreaEventListener, false);//$NON-NLS-1$
+
+ if (domDocument != null && documentEventTarget != null) {
+ documentEventTarget.removeEventListener(MozillaDomEventListener.KEYPRESS, contentAreaEventListener, false); //$NON-NLS-1$
+ }
+ contentAreaEventListener.setVisualEditor(null);
+ contentAreaEventTarget = null;
+ contentAreaEventListener = null;
+ documentEventTarget = null;
+ }
+ }
+
+ private void addSelectionListener() {
+ if (contentAreaEventListener != null&&xulRunnerEditor!=null) {
+
+ xulRunnerEditor.addSelectionListener(contentAreaEventListener);
+
+ }
+ }
+
+ /*private void removeSelectionListener() {
+ if (contentAreaEventListener != null&&xulRunnerEditor!=null) {
+
+ nsISelection selection = xulRunnerEditor.getSelection();
+ nsISelectionPrivate selectionPrivate = (nsISelectionPrivate) selection.queryInterface(nsISelectionPrivate.NS_ISELECTIONPRIVATE_IID);
+ selectionPrivate.removeSelectionListener(contentAreaEventListener);
+ }
+ }*/
+
+ public void setSelectionRectangle(nsIDOMElement element, int resizerConstrains, boolean scroll) {
+ if (contentAreaEventListener != null) {
+ xulRunnerEditor.setSelectionRectangle((nsIDOMElement)element, resizerConstrains, scroll);
+ }
+ }
+
+ /**
+ * Show resizer markers
+ */
+ public void showResizer() {
+ if (contentAreaEventListener != null) {
+ xulRunnerEditor.showResizer();
+ }
+ }
+
+ /**
+ * Hide resizer markers
+ */
+ public void hideResizer() {
+ if (contentAreaEventListener != null) {
+ xulRunnerEditor.hideResizer();
+ }
+ }
+
+ /**
+ * @return the xulRunnerEditor
+ */
+ public XulRunnerEditor getXulRunnerEditor() {
+ return xulRunnerEditor;
+ }
+
+ /**
+ * @param xulRunnerEditor the xulRunnerEditor to set
+ */
+ protected void setXulRunnerEditor(XulRunnerEditor xulRunnerEditor) {
+ this.xulRunnerEditor = xulRunnerEditor;
+ }
+
+ /**
+ * @return the controller
+ */
+ public VpeController getController() {
+ return controller;
+ }
+
+ /**
+ * @return the link
+ */
+ protected Link getLink() {
+ return link;
+ }
+
+ /**
+ * @param link the link to set
+ */
+ protected void setLink(Link link) {
+ this.link = link;
+ }
+
+
}
\ No newline at end of file
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaPreview.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaPreview.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/mozilla/MozillaPreview.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,267 +1,288 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor.mozilla;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.VpeEditorPart;
-import org.jboss.tools.vpe.editor.VpePreviewDomBuilder;
-import org.jboss.tools.vpe.editor.VpeSourceDomBuilder;
-import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
-import org.jboss.tools.vpe.editor.bundle.BundleMap;
-import org.jboss.tools.vpe.editor.context.VpePageContext;
-import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
-import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
-import org.jboss.tools.vpe.messages.VpeUIMessages;
-import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
-
-/**
- * a class implementation of mozilla preview
- * @author A. Yukhovich
- */
-public class MozillaPreview extends MozillaEditor {
-
- private EditorLoadWindowListener editorLoadWindowListener;
- private EditorDomEventListener editorDomEventListener;
- private VpeTemplateManager templateManager;
- private VpePageContext pageContext;
- private StructuredTextEditor sourceEditor;
- private VpeEditorPart editPart;
- private IDOMDocument sourceDocument;
-
- public MozillaPreview(VpeEditorPart editPart, StructuredTextEditor sourceEditor) {
- setTemplateManager(VpeTemplateManager.getInstance());
- setSourceEditor(sourceEditor);
- setEditPart(editPart);
- }
-
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
- */
- @Override
- public void createPartControl(final Composite parent) {
- try {
- setXulRunnerEditor(new XulRunnerEditor(parent) {
- public void onLoadWindow() {
- super.onLoadWindow();
- MozillaPreview.this.onLoadWindow();
- }
-
- public void onShowTooltip(int x, int y, String text) {
- if (editorDomEventListener != null) {
- editorDomEventListener.onShowTooltip(x, y, text);
- }
- }
- public void onHideTooltip() {
- if (editorDomEventListener != null) {
- editorDomEventListener.onHideTooltip();
- }
- }
- });
- getXulRunnerEditor().setURL(INIT_URL);
- getXulRunnerEditor().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- } catch (Exception e) {
- Label title = new Label(parent, SWT.WRAP);
- title.setText(VpeUIMessages.MOZILLA_LOADING_ERROR);
- title.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- setLink(new Link(parent, SWT.WRAP));
- getLink().setText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK_TEXT);
- getLink().setToolTipText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
- getLink().setForeground(getLink().getDisplay().getSystemColor(SWT.COLOR_BLUE));
- getLink().addMouseListener(new MouseListener() {
- public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
- BusyIndicator.showWhile(getLink().getDisplay(), new Runnable() {
- public void run() {
- URL theURL=null;;
- try {
- theURL = new URL(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
- } catch (MalformedURLException e) {
- VpePlugin.reportProblem(e);
- }
- IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
- try {
- support.getExternalBrowser().openURL(theURL);
- } catch (PartInitException e) {
- VpePlugin.reportProblem(e);
- }
- }
- });
- }
-
- public void mouseDoubleClick(MouseEvent e) {
- }
-
- public void mouseUp(MouseEvent e) {
- }
- });
- getLink().setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label fill = new Label(parent, SWT.WRAP);
- fill.setLayoutData(new GridData(GridData.FILL_BOTH));
- }
- }
-
- @Override
- public void setEditorLoadWindowListener(EditorLoadWindowListener listener) {
- editorLoadWindowListener = listener;
- }
-
-
- /**
- *
- */
- private void onLoadWindow() {
-
- setContentArea(findContentArea());
- if (editorLoadWindowListener != null) {
- editorLoadWindowListener.load();
- }
- }
- @Override
- public void showResizer() {
- }
-
- @Override
- public void hideResizer() {
- }
-
- //TODO Max Areshkau logic error (we should first call buildDom and only then we can call rebuildDom)
- public void rebuildDom() {
- if(getPageContext()!=null&&getPageContext().getVisualBuilder()!=null&&getSourceDocument()!=null) {
-
- getPageContext().getVisualBuilder().rebuildDom(getSourceDocument());
- }
- }
-
- //TODO Max Areshkau logic error (we should first call buildDom and only then we can call rebuildDom)
- public void buildDom() {
- BundleMap bundle = new BundleMap();
- bundle.init(getSourceEditor());
-
- setPageContext(new VpePageContext(getTemplateManager(), bundle, getEditPart()));
-
- VpeDomMapping domMapping = new VpeDomMapping(getPageContext());
- VpeSourceDomBuilder sourceBuilder = new VpeSourceDomBuilder(domMapping, null, getTemplateManager(), getSourceEditor(), getPageContext());
- VpeVisualDomBuilder visualBuilder = new VpePreviewDomBuilder(domMapping, null, getTemplateManager(), this, getPageContext());
- getPageContext().setSourceDomBuilder(sourceBuilder);
- getPageContext().setVisualDomBuilder(visualBuilder);
-
- IDOMModel sourceModel = (IDOMModel)getSourceEditor().getModel();
- setSourceDocument(sourceModel.getDocument());
-
- visualBuilder.buildDom(getSourceDocument());
- }
-
- /**
- * @return the sourceDocument
- */
- protected IDOMDocument getSourceDocument() {
- return sourceDocument;
- }
-
- /**
- * @param sourceDocument the sourceDocument to set
- */
- protected void setSourceDocument(IDOMDocument sourceDocument) {
- this.sourceDocument = sourceDocument;
- }
-
-
-
- /**
- * @return the pageContext
- */
- private VpePageContext getPageContext() {
- return pageContext;
- }
-
-
-
- /**
- * @param pageContext the pageContext to set
- */
- private void setPageContext(VpePageContext pageContext) {
- this.pageContext = pageContext;
- }
-
-
-
- /**
- * @return the editPart
- */
- private VpeEditorPart getEditPart() {
- return editPart;
- }
-
-
-
- /**
- * @param editPart the editPart to set
- */
- private void setEditPart(VpeEditorPart editPart) {
- this.editPart = editPart;
- }
-
-
-
- /**
- * @return the templateManager
- */
- private VpeTemplateManager getTemplateManager() {
- return templateManager;
- }
-
-
-
- /**
- * @param templateManager the templateManager to set
- */
- private void setTemplateManager(VpeTemplateManager templateManager) {
- this.templateManager = templateManager;
- }
-
-
-
- /**
- * @return the sourceEditor
- */
- private StructuredTextEditor getSourceEditor() {
- return sourceEditor;
- }
-
-
-
- /**
- * @param sourceEditor the sourceEditor to set
- */
- private void setSourceEditor(StructuredTextEditor sourceEditor) {
- this.sourceEditor = sourceEditor;
- }
-
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor.mozilla;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Link;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.VpeEditorPart;
+import org.jboss.tools.vpe.editor.VpePreviewDomBuilder;
+import org.jboss.tools.vpe.editor.VpeSourceDomBuilder;
+import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
+import org.jboss.tools.vpe.editor.bundle.BundleMap;
+import org.jboss.tools.vpe.editor.context.VpePageContext;
+import org.jboss.tools.vpe.editor.mapping.VpeDomMapping;
+import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+import org.jboss.tools.vpe.messages.VpeUIMessages;
+import org.jboss.tools.vpe.xulrunner.editor.XulRunnerEditor;
+
+/**
+ * a class implementation of mozilla preview
+ * @author A. Yukhovich
+ */
+public class MozillaPreview extends MozillaEditor {
+
+ private EditorLoadWindowListener editorLoadWindowListener;
+ private EditorDomEventListener editorDomEventListener;
+ private VpeTemplateManager templateManager;
+ private VpePageContext pageContext;
+ private StructuredTextEditor sourceEditor;
+ private VpeEditorPart editPart;
+ private IDOMDocument sourceDocument;
+
+ public MozillaPreview(VpeEditorPart editPart, StructuredTextEditor sourceEditor) {
+ setTemplateManager(VpeTemplateManager.getInstance());
+ setSourceEditor(sourceEditor);
+ setEditPart(editPart);
+ }
+
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void createPartControl(final Composite parent) {
+ try {
+ setXulRunnerEditor(new XulRunnerEditor(parent) {
+ public void onLoadWindow() {
+ super.onLoadWindow();
+ MozillaPreview.this.onLoadWindow();
+ }
+
+ public void onShowTooltip(int x, int y, String text) {
+ if (editorDomEventListener != null) {
+ editorDomEventListener.onShowTooltip(x, y, text);
+ }
+ }
+ public void onHideTooltip() {
+ if (editorDomEventListener != null) {
+ editorDomEventListener.onHideTooltip();
+ }
+ }
+ public void onDispose() {
+ removeDomEventListeners();
+ super.onDispose();
+ }
+ });
+ getXulRunnerEditor().setURL(INIT_URL);
+ getXulRunnerEditor().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ } catch (Exception e) {
+ Label title = new Label(parent, SWT.WRAP);
+ title.setText(VpeUIMessages.MOZILLA_LOADING_ERROR);
+ title.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ setLink(new Link(parent, SWT.WRAP));
+ getLink().setText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK_TEXT);
+ getLink().setToolTipText(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
+ getLink().setForeground(getLink().getDisplay().getSystemColor(SWT.COLOR_BLUE));
+ getLink().addMouseListener(new MouseListener() {
+ public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
+ BusyIndicator.showWhile(getLink().getDisplay(), new Runnable() {
+ public void run() {
+ URL theURL=null;;
+ try {
+ theURL = new URL(VpeUIMessages.MOZILLA_LOADING_ERROR_LINK);
+ } catch (MalformedURLException e) {
+ VpePlugin.reportProblem(e);
+ }
+ IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
+ try {
+ support.getExternalBrowser().openURL(theURL);
+ } catch (PartInitException e) {
+ VpePlugin.reportProblem(e);
+ }
+ }
+ });
+ }
+
+ public void mouseDoubleClick(MouseEvent e) {
+ }
+
+ public void mouseUp(MouseEvent e) {
+ }
+ });
+ getLink().setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label fill = new Label(parent, SWT.WRAP);
+ fill.setLayoutData(new GridData(GridData.FILL_BOTH));
+ }
+ }
+
+ @Override
+ public void setEditorLoadWindowListener(EditorLoadWindowListener listener) {
+ editorLoadWindowListener = listener;
+ }
+
+
+ /**
+ *
+ */
+ private void onLoadWindow() {
+
+ setContentArea(findContentArea());
+ if (editorLoadWindowListener != null) {
+ editorLoadWindowListener.load();
+ }
+ }
+ @Override
+ public void showResizer() {
+ }
+
+ @Override
+ public void hideResizer() {
+ }
+
+ //TODO Max Areshkau logic error (we should first call buildDom and only then we can call rebuildDom)
+ public void rebuildDom() {
+ if(getPageContext()!=null&&getPageContext().getVisualBuilder()!=null&&getSourceDocument()!=null) {
+
+ getPageContext().getVisualBuilder().rebuildDom(getSourceDocument());
+ }
+ }
+
+ //TODO Max Areshkau logic error (we should first call buildDom and only then we can call rebuildDom)
+ public void buildDom() {
+ BundleMap bundle = new BundleMap();
+ bundle.init(getSourceEditor());
+
+ setPageContext(new VpePageContext(getTemplateManager(), bundle, getEditPart()));
+
+ VpeDomMapping domMapping = new VpeDomMapping(getPageContext());
+ VpeSourceDomBuilder sourceBuilder = new VpeSourceDomBuilder(domMapping, null, getTemplateManager(), getSourceEditor(), getPageContext());
+ VpeVisualDomBuilder visualBuilder = new VpePreviewDomBuilder(domMapping, null, getTemplateManager(), this, getPageContext());
+ getPageContext().setSourceDomBuilder(sourceBuilder);
+ getPageContext().setVisualDomBuilder(visualBuilder);
+
+ IDOMModel sourceModel = (IDOMModel)getSourceEditor().getModel();
+ setSourceDocument(sourceModel.getDocument());
+
+ visualBuilder.buildDom(getSourceDocument());
+ }
+
+ /**
+ * @return the sourceDocument
+ */
+ protected IDOMDocument getSourceDocument() {
+ return sourceDocument;
+ }
+
+ /**
+ * @param sourceDocument the sourceDocument to set
+ */
+ protected void setSourceDocument(IDOMDocument sourceDocument) {
+ this.sourceDocument = sourceDocument;
+ }
+
+
+
+ /**
+ * @return the pageContext
+ */
+ private VpePageContext getPageContext() {
+ return pageContext;
+ }
+
+
+
+ /**
+ * @param pageContext the pageContext to set
+ */
+ private void setPageContext(VpePageContext pageContext) {
+ this.pageContext = pageContext;
+ }
+
+
+
+ /**
+ * @return the editPart
+ */
+ private VpeEditorPart getEditPart() {
+ return editPart;
+ }
+
+
+
+ /**
+ * @param editPart the editPart to set
+ */
+ private void setEditPart(VpeEditorPart editPart) {
+ this.editPart = editPart;
+ }
+
+
+
+ /**
+ * @return the templateManager
+ */
+ private VpeTemplateManager getTemplateManager() {
+ return templateManager;
+ }
+
+
+
+ /**
+ * @param templateManager the templateManager to set
+ */
+ private void setTemplateManager(VpeTemplateManager templateManager) {
+ this.templateManager = templateManager;
+ }
+
+
+
+ /**
+ * @return the sourceEditor
+ */
+ private StructuredTextEditor getSourceEditor() {
+ return sourceEditor;
+ }
+
+
+
+ /**
+ * @param sourceEditor the sourceEditor to set
+ */
+ private void setSourceEditor(StructuredTextEditor sourceEditor) {
+ this.sourceEditor = sourceEditor;
+ }
+
+ public void dispose() {
+ setEditorDomEventListener(null);
+ setEditorLoadWindowListener(null);
+ if (pageContext != null) {
+ pageContext.dispose();
+ pageContext=null;
+ }
+ if (getXulRunnerEditor() != null) {
+ getXulRunnerEditor().dispose();
+ setXulRunnerEditor(null);
+ }
+ sourceDocument=null;
+ sourceEditor=null;
+ editPart=null;
+ //super.dispose();
+ }
+
}
\ No newline at end of file
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/template/VpeIncludeTemplate.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/template/VpeIncludeTemplate.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/template/VpeIncludeTemplate.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,138 +1,143 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor.template;
-
-import org.eclipse.core.resources.IFile;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.VpeIncludeInfo;
-import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
-import org.jboss.tools.vpe.editor.context.VpePageContext;
-import org.jboss.tools.vpe.editor.template.expression.VpeExpression;
-import org.jboss.tools.vpe.editor.template.expression.VpeExpressionBuilder;
-import org.jboss.tools.vpe.editor.template.expression.VpeExpressionBuilderException;
-import org.jboss.tools.vpe.editor.template.expression.VpeValue;
-import org.jboss.tools.vpe.editor.util.FileUtil;
-import org.jboss.tools.vpe.editor.util.HTML;
-import org.mozilla.interfaces.nsIDOMDocument;
-import org.mozilla.interfaces.nsIDOMElement;
-import org.mozilla.interfaces.nsIDOMNode;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-public class VpeIncludeTemplate extends VpeAbstractTemplate {
- private static final String ATTR_FILE = "file";
- private VpeExpression fileNameExpression;
-
- protected void init(Element templateElement) {
- modify = false;
- Attr fileAttr = ((Element)templateElement).getAttributeNode(ATTR_FILE);
- if (fileAttr != null && fileAttr.getValue().trim().length() > 0) {
- try {
- fileNameExpression = VpeExpressionBuilder.buildCompletedExpression(fileAttr.getValue().trim(), caseSensitive).getExpression();
- } catch(VpeExpressionBuilderException e) {
- VpePlugin.reportProblem(e);
- }
- }
- initTemplateSections(templateElement, false, true, false, false, false);
- }
-
- public VpeCreationData create(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument) {
- String fileName = null;
- if (fileNameExpression != null) {
- VpeValue vpeValue = fileNameExpression.exec(pageContext, sourceNode);
- if (vpeValue != null && vpeValue.stringValue().length() > 0) {
- fileName = vpeValue.stringValue();
- VpeIncludeInfo info = pageContext.getVisualBuilder().getCurrentIncludeInfo();
- if(info != null) {
- IFile templateFile = info.getFile();
- IFile file = FileUtil.getFile(fileName, templateFile);
-
- if (file != null) {
- if (!pageContext.getVisualBuilder().isFileInIncludeStack(file)) {
- Document document = VpeCreatorUtil.getDocumentForRead(file, pageContext);
- if (document != null) {
- VpeCreationData creationData = createInclude(document, visualDocument);
- creationData.setData(file);
- pageContext.getVisualBuilder().pushIncludeStack(new VpeIncludeInfo((Element)sourceNode, file, document));
- return creationData;
- }
- }
- }
- }
- }
- }
-
- VpeCreationData creationData = createStub(fileName, visualDocument);
- creationData.setData(null);
- return creationData;
- }
-
- public void validate(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument, VpeCreationData data) {
- if (data.getData() != null) {
- VpeIncludeInfo includeInfo = pageContext.getVisualBuilder().popIncludeStack();
- if (includeInfo != null) {
- VpeCreatorUtil.releaseDocumentFromRead(includeInfo.getDocument());
- }
- }
- }
-
- public void beforeRemove(VpePageContext pageContext, Node sourceNode, nsIDOMNode visualNode, Object data) {
- IFile file = (IFile)data;
- if (file != null) {
- pageContext.getEditPart().getController().getIncludeList().removeIncludeModel(file);
- }
- }
-
- public boolean isRecreateAtAttrChange(VpePageContext pageContext, Element sourceElement, nsIDOMDocument visualDocument, nsIDOMElement visualNode, Object data, String name, String value) {
- return true;
- }
-
- private VpeCreationData createInclude(Document sourceDocument, nsIDOMDocument visualDocument) {
- nsIDOMElement visualNewElement = visualDocument.createElement(HTML.TAG_DIV);
- VpeVisualDomBuilder.markIncludeElement(visualNewElement);
- VpeCreationData creationData = new VpeCreationData(visualNewElement);
- if (children) {
- VpeChildrenInfo childrenInfo = new VpeChildrenInfo(visualNewElement);
- NodeList sourceChildren = sourceDocument.getChildNodes();
- int len = sourceChildren.getLength();
- for (int i = 0; i < len; i++) {
- childrenInfo.addSourceChild(sourceChildren.item(i));
- }
- creationData.addChildrenInfo(childrenInfo);
- }
- return creationData;
- }
-
- private VpeCreationData createStub(String fileName, nsIDOMDocument visualDocument) {
- nsIDOMElement visualNewElement = visualDocument.createElement(HTML.TAG_DIV);
- visualNewElement.setAttribute("style", "background-color:#ECF3FF;cursor:pointer;padding:0 5px;margin:3px 0;font-style:italic;color:#0051DD;");
- VpeVisualDomBuilder.markIncludeElement(visualNewElement);
- if (fileName != null) {
- visualNewElement.appendChild(visualDocument.createTextNode(fileName));
- }
- return new VpeCreationData(visualNewElement);
- }
-
- public void openIncludeEditor(VpePageContext pageContext, Element sourceElement, Object data) {
- if (sourceElement != null && fileNameExpression != null) {
- VpeValue vpeValue = fileNameExpression.exec(pageContext, sourceElement);
- if (vpeValue != null && vpeValue.stringValue().length() > 0) {
- pageContext.openIncludeFile(vpeValue.stringValue());
- }
- }
- }
-
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor.template;
+
+import org.eclipse.core.resources.IFile;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.VpeIncludeInfo;
+import org.jboss.tools.vpe.editor.VpeVisualDomBuilder;
+import org.jboss.tools.vpe.editor.context.VpePageContext;
+import org.jboss.tools.vpe.editor.template.expression.VpeExpression;
+import org.jboss.tools.vpe.editor.template.expression.VpeExpressionBuilder;
+import org.jboss.tools.vpe.editor.template.expression.VpeExpressionBuilderException;
+import org.jboss.tools.vpe.editor.template.expression.VpeValue;
+import org.jboss.tools.vpe.editor.util.FileUtil;
+import org.jboss.tools.vpe.editor.util.HTML;
+import org.mozilla.interfaces.nsIDOMDocument;
+import org.mozilla.interfaces.nsIDOMElement;
+import org.mozilla.interfaces.nsIDOMNode;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class VpeIncludeTemplate extends VpeAbstractTemplate {
+ private static final String ATTR_FILE = "file";
+ private VpeExpression fileNameExpression;
+
+ protected void init(Element templateElement) {
+ modify = false;
+ Attr fileAttr = ((Element)templateElement).getAttributeNode(ATTR_FILE);
+ if (fileAttr != null && fileAttr.getValue().trim().length() > 0) {
+ try {
+ fileNameExpression = VpeExpressionBuilder.buildCompletedExpression(fileAttr.getValue().trim(), caseSensitive).getExpression();
+ } catch(VpeExpressionBuilderException e) {
+ VpePlugin.reportProblem(e);
+ }
+ }
+ initTemplateSections(templateElement, false, true, false, false, false);
+ }
+
+ public VpeCreationData create(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument) {
+ String fileName = null;
+ if (fileNameExpression != null) {
+ VpeValue vpeValue = fileNameExpression.exec(pageContext, sourceNode);
+ if (vpeValue != null && vpeValue.stringValue().length() > 0) {
+ fileName = vpeValue.stringValue();
+ VpeIncludeInfo info = pageContext.getVisualBuilder().getCurrentIncludeInfo();
+ if(info != null) {
+ IFile templateFile = info.getFile();
+ IFile file = FileUtil.getFile(fileName, templateFile);
+
+ if (file != null) {
+ if (!pageContext.getVisualBuilder().isFileInIncludeStack(file)) {
+ Document document = pageContext.getVisualBuilder().getIncludeDocuments().get(file);
+ if (document == null) {
+ document = VpeCreatorUtil.getDocumentForRead(file, pageContext);
+ if (document != null)
+ pageContext.getVisualBuilder().getIncludeDocuments().put(file, document);
+ }
+ if (document != null) {
+ VpeCreationData creationData = createInclude(document, visualDocument);
+ creationData.setData(file);
+ pageContext.getVisualBuilder().pushIncludeStack(new VpeIncludeInfo((Element)sourceNode, file, document));
+ return creationData;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ VpeCreationData creationData = createStub(fileName, visualDocument);
+ creationData.setData(null);
+ return creationData;
+ }
+
+ public void validate(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument, VpeCreationData data) {
+ if (data.getData() != null) {
+ VpeIncludeInfo includeInfo = pageContext.getVisualBuilder().popIncludeStack();
+ if (includeInfo != null) {
+ //VpeCreatorUtil.releaseDocumentFromRead(includeInfo.getDocument());
+ }
+ }
+ }
+
+ public void beforeRemove(VpePageContext pageContext, Node sourceNode, nsIDOMNode visualNode, Object data) {
+ IFile file = (IFile)data;
+ if (file != null) {
+ pageContext.getEditPart().getController().getIncludeList().removeIncludeModel(file);
+ }
+ }
+
+ public boolean isRecreateAtAttrChange(VpePageContext pageContext, Element sourceElement, nsIDOMDocument visualDocument, nsIDOMElement visualNode, Object data, String name, String value) {
+ return true;
+ }
+
+ private VpeCreationData createInclude(Document sourceDocument, nsIDOMDocument visualDocument) {
+ nsIDOMElement visualNewElement = visualDocument.createElement(HTML.TAG_DIV);
+ VpeVisualDomBuilder.markIncludeElement(visualNewElement);
+ VpeCreationData creationData = new VpeCreationData(visualNewElement);
+ if (children) {
+ VpeChildrenInfo childrenInfo = new VpeChildrenInfo(visualNewElement);
+ NodeList sourceChildren = sourceDocument.getChildNodes();
+ int len = sourceChildren.getLength();
+ for (int i = 0; i < len; i++) {
+ childrenInfo.addSourceChild(sourceChildren.item(i));
+ }
+ creationData.addChildrenInfo(childrenInfo);
+ }
+ return creationData;
+ }
+
+ private VpeCreationData createStub(String fileName, nsIDOMDocument visualDocument) {
+ nsIDOMElement visualNewElement = visualDocument.createElement(HTML.TAG_DIV);
+ visualNewElement.setAttribute("style", "background-color:#ECF3FF;cursor:pointer;padding:0 5px;margin:3px 0;font-style:italic;color:#0051DD;");
+ VpeVisualDomBuilder.markIncludeElement(visualNewElement);
+ if (fileName != null) {
+ visualNewElement.appendChild(visualDocument.createTextNode(fileName));
+ }
+ return new VpeCreationData(visualNewElement);
+ }
+
+ public void openIncludeEditor(VpePageContext pageContext, Element sourceElement, Object data) {
+ if (sourceElement != null && fileNameExpression != null) {
+ VpeValue vpeValue = fileNameExpression.exec(pageContext, sourceElement);
+ if (vpeValue != null && vpeValue.stringValue().length() > 0) {
+ pageContext.openIncludeFile(vpeValue.stringValue());
+ }
+ }
+ }
+
+
+
+}
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/IVpeToolBarManager.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/IVpeToolBarManager.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/IVpeToolBarManager.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,44 +1,46 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-
-package org.jboss.tools.vpe.editor.toolbar;
-
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * This interface create a toolbarmanager for swt toolbar in the VPE.
- * To use it procede only in the following order: first call
- * createToolBarComposite(composite) where composite is the parent for the future toolbar
- * then call addToolBar(IvpeToolbar) to add it and finally createMenuComposite(Composite) to add it to the menu bar.
- * @author Igels
- */
-public interface IVpeToolBarManager {
-
- /**
- * This method create a splitter in the given composite
- * @param parent
- * @return
- */
- public Composite createToolBarComposite(Composite parent);
-
- /**
- * This method add the Toolbar to the splitter with the scpecified layout
- * @param bar
- */
- public void addToolBar(IVpeToolBar bar);
-
- /**
- * This method create and add a new menuitem to the toolbars Menu.
- * @param parent
- * @return
- */
- public Composite createMenuComposite(Composite parent);
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+
+package org.jboss.tools.vpe.editor.toolbar;
+
+import org.eclipse.swt.widgets.Composite;
+
+/**
+ * This interface create a toolbarmanager for swt toolbar in the VPE.
+ * To use it procede only in the following order: first call
+ * createToolBarComposite(composite) where composite is the parent for the future toolbar
+ * then call addToolBar(IvpeToolbar) to add it and finally createMenuComposite(Composite) to add it to the menu bar.
+ * @author Igels
+ */
+public interface IVpeToolBarManager {
+
+ /**
+ * This method create a splitter in the given composite
+ * @param parent
+ * @return
+ */
+ public Composite createToolBarComposite(Composite parent);
+
+ /**
+ * This method add the Toolbar to the splitter with the scpecified layout
+ * @param bar
+ */
+ public void addToolBar(IVpeToolBar bar);
+
+ /**
+ * This method create and add a new menuitem to the toolbars Menu.
+ * @param parent
+ * @return
+ */
+ public Composite createMenuComposite(Composite parent);
+
+ public void dispose();
}
\ No newline at end of file
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/VpeToolBarManager.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/VpeToolBarManager.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/editor/toolbar/VpeToolBarManager.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,223 +1,238 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.editor.toolbar;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.eclipse.compare.Splitter;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-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.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
-import org.jboss.tools.vpe.messages.VpeUIMessages;
-
-/**
- * @author Erick
- * Created on 14.07.2005
- * @see IVpeToolBarManager
- */
-public class VpeToolBarManager implements IVpeToolBarManager {
-
- static String TOOLBAR = "VPE_TOOLBAR";
- static String HIDE = "HIDE";
-
- private Splitter splitter;
- private Composite cmpTlEmpty;
- private List toolbarContainers = new ArrayList();
- private MenuItem hideMenuItem;
- private VpePlugin plugin = VpePlugin.getDefault();
-
- public VpeToolBarManager() {
- }
-
- public Composite createToolBarComposite(Composite parent) {
- splitter = new Splitter(parent, SWT.NONE);
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
- splitter.setLayoutData(data);
-
- /*
- * The empty composite
- */
- cmpTlEmpty = new Composite(splitter, SWT.NONE) {
- public Point computeSize (int wHint, int hHint, boolean changed) {
- Point point = super.computeSize(wHint, hHint, changed);
- point.y = 1;
- return point;
- }
- };
- cmpTlEmpty.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- splitter.setVisible(cmpTlEmpty, false);
- return splitter;
- }
-
- public void addToolBar(IVpeToolBar bar) {
- Composite cmpToolBar = new Composite(splitter, SWT.NONE);
- GridLayout layoutTl = new GridLayout(2, false);
- layoutTl.marginBottom = 0;
- layoutTl.marginHeight = 2;
- layoutTl.marginWidth = 0;
- layoutTl.verticalSpacing = 0;
- layoutTl.horizontalSpacing = 0;
- cmpToolBar.setLayout(layoutTl);
- cmpToolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- bar.createToolBarControl(cmpToolBar);
- toolbarContainers.add(new ToolbarContainer(cmpToolBar, bar));
- }
-
- public Composite createMenuComposite(final Composite parent) {
- /*
- * Menu for the menu bar
- */
- final Menu menu = new Menu(parent.getShell(), SWT.POP_UP);
- hideMenuItem = new MenuItem(menu, SWT.PUSH);
- String hideMenuText = VpeUIMessages.HIDE_TOOLBAR;
- hideMenuItem.setText(hideMenuText);
- for(int i=0; i<toolbarContainers.size(); i++) {
- final ToolbarContainer toolbarContainer = (ToolbarContainer)toolbarContainers.get(i);
- MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
- toolbarContainer.setMenuItem(menuItem);
- menuItem.setText(toolbarContainer.getToolbar().getName());
-
- menuItem.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- showToolbar(toolbarContainer);
- parent.getParent().layout(true, true);
- }
- });
- }
-
- String defaultPreferenceValue = null;
- if(toolbarContainers.size()>0) {
- defaultPreferenceValue = ((ToolbarContainer)toolbarContainers.get(0)).getToolbar().getName();
- } else {
- defaultPreferenceValue = HIDE;
- }
- plugin.getPreferenceStore().setDefault(TOOLBAR, defaultPreferenceValue);
-
- String value = plugin.getPreferenceStore().getString(TOOLBAR);
- if (HIDE.equals(value)) {
- hideToolbars();
- } else {
-// Sets active toolbar
- for(int i = 0; i < toolbarContainers.size(); i++) {
- if( ((ToolbarContainer)toolbarContainers.get(i)).getToolbar().getName().equals(value)) {
- showToolbar((ToolbarContainer)toolbarContainers.get(i));
- }
- }
- }
-
- hideMenuItem.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- hideToolbars();
- parent.getParent().layout(true, true);
- }
- });
-
- /*
- * The menu ButtonBar
- */
- final ToolBar btnBar = new ToolBar(parent, SWT.FLAT);
- GridLayout layout = new GridLayout(1,false);
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- layout.verticalSpacing = 0;
- btnBar.setLayout(layout);
- btnBar.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
- btnBar.setSize(23,22);
- btnBar.pack();
-
- final ToolItem button = new ToolItem(btnBar, SWT.MENU);
- button.setImage(ImageDescriptor.createFromFile(MozillaEditor.class, "icons/arrow.gif").createImage()); //$NON-NLS-1$
- button.setToolTipText(VpeUIMessages.MENU);
- button.addListener(SWT.Selection, new Listener() {
- public void handleEvent(Event event) {
- Rectangle bounds = button.getBounds();
- Point point = btnBar.toDisplay( bounds.x + 15, bounds.y + 12);
- menu.setLocation(point);
- menu.setVisible(true);
- }
- });
-
- return btnBar;
- }
-
- private void showToolbar(ToolbarContainer toolbarContainer) {
- plugin.getPreferenceStore().setValue(TOOLBAR, toolbarContainer.getToolbar().getName());
- plugin.savePluginPreferences();
- hideMenuItem.setEnabled(true);
- toolbarContainer.getMenuItem().setEnabled(false);
- splitter.setVisible(toolbarContainer.getParent(), true);
- for(int i=0; i<toolbarContainers.size(); i++) {
- ToolbarContainer container = (ToolbarContainer)toolbarContainers.get(i);
- if(container != toolbarContainer) {
- splitter.setVisible(container.getParent(), false);
- container.getMenuItem().setEnabled(true);
- }
- }
- splitter.setVisible(cmpTlEmpty, false);
- }
-
- private void hideToolbars() {
- plugin.getPreferenceStore().setValue(TOOLBAR, HIDE);
- plugin.savePluginPreferences();
- hideMenuItem.setEnabled(false);
- for(int i=0; i<toolbarContainers.size(); i++) {
- ToolbarContainer container = (ToolbarContainer)toolbarContainers.get(i);
- splitter.setVisible(container.getParent(), false);
- container.getMenuItem().setEnabled(true);
- }
- splitter.setVisible(cmpTlEmpty, true);
- }
-
- /*
- * This class describe the container for toolbars
- */
- private static class ToolbarContainer {
-
- private Composite parent;
- private IVpeToolBar toolbar;
- private MenuItem menuItem;
-
- public ToolbarContainer(Composite parent, IVpeToolBar toolbar) {
- this.parent = parent;
- this.toolbar = toolbar;
- }
-
- public Composite getParent() {
- return parent;
- }
-
- public IVpeToolBar getToolbar() {
- return toolbar;
- }
-
- public MenuItem getMenuItem() {
- return menuItem;
- }
-
- public void setMenuItem(MenuItem menuItem) {
- this.menuItem = menuItem;
- }
- }
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.editor.toolbar;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.eclipse.compare.Splitter;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.SWT;
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.mozilla.MozillaEditor;
+import org.jboss.tools.vpe.messages.VpeUIMessages;
+
+/**
+ * @author Erick
+ * Created on 14.07.2005
+ * @see IVpeToolBarManager
+ */
+public class VpeToolBarManager implements IVpeToolBarManager {
+
+ static String TOOLBAR = "VPE_TOOLBAR";
+ static String HIDE = "HIDE";
+
+ private Splitter splitter;
+ private Composite cmpTlEmpty;
+ private List toolbarContainers = new ArrayList();
+ private MenuItem hideMenuItem;
+ private VpePlugin plugin = VpePlugin.getDefault();
+
+ public VpeToolBarManager() {
+ }
+
+ public Composite createToolBarComposite(Composite parent) {
+ splitter = new Splitter(parent, SWT.NONE);
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ splitter.setLayoutData(data);
+
+ /*
+ * The empty composite
+ */
+ cmpTlEmpty = new Composite(splitter, SWT.NONE) {
+ public Point computeSize (int wHint, int hHint, boolean changed) {
+ Point point = super.computeSize(wHint, hHint, changed);
+ point.y = 1;
+ return point;
+ }
+ };
+ cmpTlEmpty.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ splitter.setVisible(cmpTlEmpty, false);
+ return splitter;
+ }
+
+ public void addToolBar(IVpeToolBar bar) {
+ Composite cmpToolBar = new Composite(splitter, SWT.NONE);
+ GridLayout layoutTl = new GridLayout(2, false);
+ layoutTl.marginBottom = 0;
+ layoutTl.marginHeight = 2;
+ layoutTl.marginWidth = 0;
+ layoutTl.verticalSpacing = 0;
+ layoutTl.horizontalSpacing = 0;
+ cmpToolBar.setLayout(layoutTl);
+ cmpToolBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ bar.createToolBarControl(cmpToolBar);
+ toolbarContainers.add(new ToolbarContainer(cmpToolBar, bar));
+ }
+
+ public Composite createMenuComposite(final Composite parent) {
+ /*
+ * Menu for the menu bar
+ */
+ final Menu menu = new Menu(parent.getShell(), SWT.POP_UP);
+ hideMenuItem = new MenuItem(menu, SWT.PUSH);
+ String hideMenuText = VpeUIMessages.HIDE_TOOLBAR;
+ hideMenuItem.setText(hideMenuText);
+ for(int i=0; i<toolbarContainers.size(); i++) {
+ final ToolbarContainer toolbarContainer = (ToolbarContainer)toolbarContainers.get(i);
+ MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
+ toolbarContainer.setMenuItem(menuItem);
+ menuItem.setText(toolbarContainer.getToolbar().getName());
+
+ menuItem.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ showToolbar(toolbarContainer);
+ parent.getParent().layout(true, true);
+ }
+ });
+ }
+
+ String defaultPreferenceValue = null;
+ if(toolbarContainers.size()>0) {
+ defaultPreferenceValue = ((ToolbarContainer)toolbarContainers.get(0)).getToolbar().getName();
+ } else {
+ defaultPreferenceValue = HIDE;
+ }
+ plugin.getPreferenceStore().setDefault(TOOLBAR, defaultPreferenceValue);
+
+ String value = plugin.getPreferenceStore().getString(TOOLBAR);
+ if (HIDE.equals(value)) {
+ hideToolbars();
+ } else {
+// Sets active toolbar
+ for(int i = 0; i < toolbarContainers.size(); i++) {
+ if( ((ToolbarContainer)toolbarContainers.get(i)).getToolbar().getName().equals(value)) {
+ showToolbar((ToolbarContainer)toolbarContainers.get(i));
+ }
+ }
+ }
+
+ hideMenuItem.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ hideToolbars();
+ parent.getParent().layout(true, true);
+ }
+ });
+
+ /*
+ * The menu ButtonBar
+ */
+ final ToolBar btnBar = new ToolBar(parent, SWT.FLAT);
+ GridLayout layout = new GridLayout(1,false);
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ layout.verticalSpacing = 0;
+ btnBar.setLayout(layout);
+ btnBar.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
+ btnBar.setSize(23,22);
+ btnBar.pack();
+
+ final ToolItem button = new ToolItem(btnBar, SWT.MENU);
+ button.setImage(ImageDescriptor.createFromFile(MozillaEditor.class, "icons/arrow.gif").createImage()); //$NON-NLS-1$
+ button.setToolTipText(VpeUIMessages.MENU);
+ button.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event event) {
+ Rectangle bounds = button.getBounds();
+ Point point = btnBar.toDisplay( bounds.x + 15, bounds.y + 12);
+ menu.setLocation(point);
+ menu.setVisible(true);
+ }
+ });
+
+ return btnBar;
+ }
+
+ private void showToolbar(ToolbarContainer toolbarContainer) {
+ plugin.getPreferenceStore().setValue(TOOLBAR, toolbarContainer.getToolbar().getName());
+ plugin.savePluginPreferences();
+ hideMenuItem.setEnabled(true);
+ toolbarContainer.getMenuItem().setEnabled(false);
+ splitter.setVisible(toolbarContainer.getParent(), true);
+ for(int i=0; i<toolbarContainers.size(); i++) {
+ ToolbarContainer container = (ToolbarContainer)toolbarContainers.get(i);
+ if(container != toolbarContainer) {
+ splitter.setVisible(container.getParent(), false);
+ container.getMenuItem().setEnabled(true);
+ }
+ }
+ splitter.setVisible(cmpTlEmpty, false);
+ }
+
+ private void hideToolbars() {
+ plugin.getPreferenceStore().setValue(TOOLBAR, HIDE);
+ plugin.savePluginPreferences();
+ hideMenuItem.setEnabled(false);
+ for(int i=0; i<toolbarContainers.size(); i++) {
+ ToolbarContainer container = (ToolbarContainer)toolbarContainers.get(i);
+ splitter.setVisible(container.getParent(), false);
+ container.getMenuItem().setEnabled(true);
+ }
+ splitter.setVisible(cmpTlEmpty, true);
+ }
+
+ /*
+ * This class describe the container for toolbars
+ */
+ private static class ToolbarContainer {
+
+ private Composite parent;
+ private IVpeToolBar toolbar;
+ private MenuItem menuItem;
+
+ public ToolbarContainer(Composite parent, IVpeToolBar toolbar) {
+ this.parent = parent;
+ this.toolbar = toolbar;
+ }
+
+ public Composite getParent() {
+ return parent;
+ }
+
+ public IVpeToolBar getToolbar() {
+ return toolbar;
+ }
+
+ public MenuItem getMenuItem() {
+ return menuItem;
+ }
+
+ public void setMenuItem(MenuItem menuItem) {
+ this.menuItem = menuItem;
+ }
+ }
+
+ public void dispose() {
+ if (splitter != null) {
+ splitter.dispose();
+ splitter=null;
+ }
+ hideMenuItem.dispose();
+
+ for(int i=0; i<toolbarContainers.size(); i++) {
+ ToolbarContainer container = (ToolbarContainer)toolbarContainers.get(i);
+ container.getMenuItem().dispose();
+ }
+ toolbarContainers.clear();
+ toolbarContainers=null;
+ }
}
\ No newline at end of file
Modified: trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/selbar/SelectionBar.java
===================================================================
--- trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/selbar/SelectionBar.java 2008-02-07 09:57:05 UTC (rev 6143)
+++ trunk/vpe/plugins/org.jboss.tools.vpe/src/org/jboss/tools/vpe/selbar/SelectionBar.java 2008-02-07 09:57:22 UTC (rev 6144)
@@ -1,303 +1,311 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.vpe.selbar;
-
-import org.eclipse.compare.Splitter;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-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.Event;
-import org.eclipse.swt.widgets.Layout;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.ui.util.ModelUtilities;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.vpe.VpePlugin;
-import org.jboss.tools.vpe.editor.VpeController;
-import org.jboss.tools.vpe.editor.selection.VpeSourceSelection;
-import org.jboss.tools.vpe.editor.selection.VpeSourceSelectionBuilder;
-import org.jboss.tools.vpe.messages.VpeUIMessages;
-import org.w3c.dom.Node;
-
-/**
- * @author erick This class create and manage the Selection Bar under the VPE.
- * Entry point from the class MozilaEditor This bar can be hiden and
- * shown it uses splitter for this
- */
-
-public class SelectionBar extends Layout implements SelectionListener {
- private Splitter splitter;
-
- private VpeController vpeController = null;
-
- private ToolBar selBar = null;
- private ToolBar closeSelectionBar = null;
-
- private int itemCount = 0;
-
- private Composite cmpToolBar = null;
- private Composite cmpTlEmpty = null;
- private Composite cmpBar = null;
- private Composite closeBar = null;
-
- Listener selbarListener = null;
-
- final static String PREFERENCE_STATUS_BAR_ENABLE = "yes";
- final static String PREFERENCE_STATUS_BAR_DISABLE = "no";
-
- public Composite createToolBarComposite(Composite parent, boolean show) {
- splitter = new Splitter(parent, SWT.NONE);
- splitter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- /*
- * The empty composite
- */
- cmpTlEmpty = new Composite(splitter, SWT.NONE) {
- public Point computeSize(int wHint, int hHint, boolean changed) {
- Point point = super.computeSize(wHint, hHint, changed);
- point.y = 1;
- return point;
- }
- };
-
- cmpTlEmpty.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // Main composite of the visible splitter
- cmpToolBar = new Composite(splitter, SWT.NONE);
- cmpToolBar.setLayout(this);
-
- GridLayout layoutTl = new GridLayout(1, false);
- layoutTl.marginBottom = 0;
- layoutTl.marginHeight = 0;
- layoutTl.marginWidth = 0;
- layoutTl.verticalSpacing = 0;
- layoutTl.horizontalSpacing = 0;
-
- // Middle composite, witch contain the selectbar
- cmpBar = new Composite(cmpToolBar, SWT.NONE);
- cmpBar.setLayout(layoutTl);
- cmpBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- closeBar = new Composite(cmpToolBar, SWT.NONE);
- closeBar.setLayout(layoutTl);
- closeBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- closeSelectionBar = new ToolBar(closeBar, SWT.HORIZONTAL | SWT.FLAT);
- ToolItem closeItem = new ToolItem(closeSelectionBar, SWT.FLAT);
- closeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImage(ISharedImages.IMG_TOOL_DELETE));
- closeItem.setToolTipText(VpeUIMessages.HIDE_SELECTIONBAR);
- closeItem.addListener(SWT.Selection, new Listener() {
-
- public void handleEvent(Event event) {
- boolean toggleState = VpePreference.ALWAYS_HIDE_SELECTION_BAR_WITHOUT_PROMT
- .getValue().equals(PREFERENCE_STATUS_BAR_ENABLE);
- XModelObject optionsObject = ModelUtilities
- .getPreferenceModel().getByPath(
- VpePreference.VPE_EDITOR_PATH);
- if (!toggleState) {
- MessageDialogWithToggle dialog = MessageDialogWithToggle
- .openOkCancelConfirm(
- PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow()
- .getShell(),
- VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_TITLE,
- VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_MESSAGE,
- VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_TOGGLE_MESSAGE,
- false, null, null);
- if (dialog.getReturnCode() != IDialogConstants.OK_ID) {
- return;
- }
- if (dialog.getToggleState()) {
- optionsObject
- .setAttributeValue(
- VpePreference.ATT_ALWAYS_HIDE_SELECTION_BAR_WITHOUT_PROMT,
- PREFERENCE_STATUS_BAR_ENABLE);
- }
- }
- optionsObject.setAttributeValue(
- VpePreference.ATT_SHOW_SELECTION_TAG_BAR,
- PREFERENCE_STATUS_BAR_DISABLE);
- showBar(PREFERENCE_STATUS_BAR_DISABLE);
- }
- });
- // Create selection bar
- selBar = new ToolBar(cmpBar, SWT.HORIZONTAL | SWT.FLAT);
- if (show == true) {
- splitter.setVisible(cmpTlEmpty, false);
- splitter.setVisible(cmpToolBar, true);
- } else {
- splitter.setVisible(cmpTlEmpty, true);
- splitter.setVisible(cmpToolBar, false);
- }
-
- return splitter;
- }
-
- public void showBar(String show) {
- if (PREFERENCE_STATUS_BAR_ENABLE.equals(show)) {
- splitter.setVisible(cmpToolBar, true);
- splitter.setVisible(cmpTlEmpty, false);
- splitter.getParent().layout(true, true);
- } else {
- splitter.setVisible(cmpToolBar, false);
- splitter.setVisible(cmpTlEmpty, true);
- splitter.getParent().layout(true, true);
- }
- }
-
- public void setVpeController(VpeController vpeController) {
- this.vpeController = vpeController;
- }
-
- public void selectionChanged() {
- VpeSourceSelectionBuilder sourceSelectionBuilder = new VpeSourceSelectionBuilder(
- vpeController.getSourceEditor());
- VpeSourceSelection selection = sourceSelectionBuilder.getSelection();
- if (selection == null) {
- return;
- }
-
- // Node node = selection.getFocusNode();
- Node node = selection.getStartNode();
- if (node != null && node.getNodeType() == Node.TEXT_NODE) {
- node = node.getParentNode();
- }
-
- int elementCounter = 0;
- while (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
- ToolItem item = null;
- if (selBar.getItemCount() > elementCounter) {
- item = selBar.getItem(selBar.getItemCount() - elementCounter
- - 1);
- item.setData(node);
- } else {
- item = new ToolItem(selBar, SWT.FLAT, 0);
- item.addSelectionListener(this);
- item.setData(node);
- }
-
- item.setText(node.getNodeName());
- elementCounter++;
- node = node.getParentNode();
- }
-
- itemCount = elementCounter;
- cmpToolBar.layout();
- // bug was fixed when toolbar are not shown for resizeble components
- cmpToolBar.layout();
- }
-
- protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
- Point point = selBar.computeSize(SWT.DEFAULT, hHint);
- point.y = closeBar.getSize().y;
- return point;
- }
-
- protected void layout(Composite composite, boolean flushCache) {
- Rectangle rect = null;
- try {
- rect = composite.getBounds();
- } catch (SWTException e) {
- VpePlugin.getPluginLog().logError(e);
- }
-
- Rectangle closeBarRect = closeSelectionBar.getItem(0).getBounds();
- rect.width -= closeBarRect.width;
-
- int allItems = selBar.getItems().length;
- if (allItems == 0) {
- cmpBar.setBounds(new Rectangle(rect.x, rect.y, rect.width,
- closeBarRect.height));
- closeBar.setBounds(new Rectangle(rect.width, rect.y, rect.width
- + closeBarRect.width, closeBarRect.height));
- return;
- }
- Rectangle r = selBar.getItem(allItems - 1).getBounds();
- int width = r.x + r.width;
- int height = r.height;
-
- if (allItems >= itemCount) {
- int x = 0;
-
- if (itemCount == 0) {
- x = selBar.getBounds().width;
- } else {
- x = selBar.getItem(allItems - itemCount).getBounds().x;
- }
-
- rect.x -= x;
-
- if (rect.width < (r.x + r.width - Math.abs(rect.x) + 10)) {
- rect.x -= (r.x + r.width - Math.abs(rect.x)) - rect.width;
- }
-
- cmpBar.setBounds(new Rectangle(rect.x, 0, width, height));
- selBar.setSize(width, closeBarRect.height);
- closeBar.setBounds(new Rectangle(rect.width, rect.y, rect.width
- + closeBarRect.width, closeBarRect.height));
- }
- }
-
- public void dispose() {
- if (!selBar.isDisposed()) {
- for (int i = 0; i < selBar.getItemCount(); i++) {
- if (!selBar.getItem(i).isDisposed()) {
- selBar.getItem(i).removeSelectionListener(this);
- }
- }
- }
- if (!closeSelectionBar.isDisposed()) {
- for (int i = 0; i < closeSelectionBar.getItemCount(); i++) {
- if (!closeSelectionBar.getItem(i).isDisposed()) {
- closeSelectionBar.getItem(i).removeSelectionListener(this);
- }
- }
- }
- }
-
- public void widgetSelected(SelectionEvent e) {
- ToolItem toolItem = (ToolItem) e.widget;
- int offset = ((ElementImpl) toolItem.getData()).getStartOffset();
- setSourceFocus(offset);
- }
-
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- private void setSourceFocus(int offset) {
- vpeController.getPageContext().getSourceBuilder()
- .getStructuredTextViewer().setSelectedRange(offset, 0);
- vpeController.getPageContext().getSourceBuilder()
- .getStructuredTextViewer().revealRange(offset, 0);
- }
-
- public String toString() {
- StringBuffer st = new StringBuffer("CountItem: ");
- st.append(itemCount);
- st.append(" Parent Composite: " + cmpToolBar.getBounds().width);
- st.append(" Midle composite: " + cmpBar.getBounds().width);
- st.append(" Bar : " + selBar.getBounds().width);
- return st.toString();
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.vpe.selbar;
+
+import org.eclipse.compare.Splitter;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialogWithToggle;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+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.Event;
+import org.eclipse.swt.widgets.Layout;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.ui.util.ModelUtilities;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.vpe.VpePlugin;
+import org.jboss.tools.vpe.editor.VpeController;
+import org.jboss.tools.vpe.editor.selection.VpeSourceSelection;
+import org.jboss.tools.vpe.editor.selection.VpeSourceSelectionBuilder;
+import org.jboss.tools.vpe.messages.VpeUIMessages;
+import org.w3c.dom.Node;
+
+/**
+ * @author erick This class create and manage the Selection Bar under the VPE.
+ * Entry point from the class MozilaEditor This bar can be hiden and
+ * shown it uses splitter for this
+ */
+
+public class SelectionBar extends Layout implements SelectionListener {
+ private Splitter splitter;
+
+ private VpeController vpeController = null;
+
+ private ToolBar selBar = null;
+ private ToolBar closeSelectionBar = null;
+
+ private int itemCount = 0;
+
+ private Composite cmpToolBar = null;
+ private Composite cmpTlEmpty = null;
+ private Composite cmpBar = null;
+ private Composite closeBar = null;
+
+ //Listener selbarListener = null;
+
+ final static String PREFERENCE_STATUS_BAR_ENABLE = "yes";
+ final static String PREFERENCE_STATUS_BAR_DISABLE = "no";
+
+ public Composite createToolBarComposite(Composite parent, boolean show) {
+ splitter = new Splitter(parent, SWT.NONE);
+ splitter.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ /*
+ * The empty composite
+ */
+ cmpTlEmpty = new Composite(splitter, SWT.NONE) {
+ public Point computeSize(int wHint, int hHint, boolean changed) {
+ Point point = super.computeSize(wHint, hHint, changed);
+ point.y = 1;
+ return point;
+ }
+ };
+
+ cmpTlEmpty.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // Main composite of the visible splitter
+ cmpToolBar = new Composite(splitter, SWT.NONE);
+ cmpToolBar.setLayout(this);
+
+ GridLayout layoutTl = new GridLayout(1, false);
+ layoutTl.marginBottom = 0;
+ layoutTl.marginHeight = 0;
+ layoutTl.marginWidth = 0;
+ layoutTl.verticalSpacing = 0;
+ layoutTl.horizontalSpacing = 0;
+
+ // Middle composite, witch contain the selectbar
+ cmpBar = new Composite(cmpToolBar, SWT.NONE);
+ cmpBar.setLayout(layoutTl);
+ cmpBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ closeBar = new Composite(cmpToolBar, SWT.NONE);
+ closeBar.setLayout(layoutTl);
+ closeBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ closeSelectionBar = new ToolBar(closeBar, SWT.HORIZONTAL | SWT.FLAT);
+ ToolItem closeItem = new ToolItem(closeSelectionBar, SWT.FLAT);
+ closeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_TOOL_DELETE));
+ closeItem.setToolTipText(VpeUIMessages.HIDE_SELECTIONBAR);
+ closeItem.addListener(SWT.Selection, new Listener() {
+
+ public void handleEvent(Event event) {
+ boolean toggleState = VpePreference.ALWAYS_HIDE_SELECTION_BAR_WITHOUT_PROMT
+ .getValue().equals(PREFERENCE_STATUS_BAR_ENABLE);
+ XModelObject optionsObject = ModelUtilities
+ .getPreferenceModel().getByPath(
+ VpePreference.VPE_EDITOR_PATH);
+ if (!toggleState) {
+ MessageDialogWithToggle dialog = MessageDialogWithToggle
+ .openOkCancelConfirm(
+ PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow()
+ .getShell(),
+ VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_TITLE,
+ VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_MESSAGE,
+ VpeUIMessages.CONFIRM_SELECTION_BAR_DIALOG_TOGGLE_MESSAGE,
+ false, null, null);
+ if (dialog.getReturnCode() != IDialogConstants.OK_ID) {
+ return;
+ }
+ if (dialog.getToggleState()) {
+ optionsObject
+ .setAttributeValue(
+ VpePreference.ATT_ALWAYS_HIDE_SELECTION_BAR_WITHOUT_PROMT,
+ PREFERENCE_STATUS_BAR_ENABLE);
+ }
+ }
+ optionsObject.setAttributeValue(
+ VpePreference.ATT_SHOW_SELECTION_TAG_BAR,
+ PREFERENCE_STATUS_BAR_DISABLE);
+ showBar(PREFERENCE_STATUS_BAR_DISABLE);
+ }
+ });
+ // Create selection bar
+ selBar = new ToolBar(cmpBar, SWT.HORIZONTAL | SWT.FLAT);
+ if (show == true) {
+ splitter.setVisible(cmpTlEmpty, false);
+ splitter.setVisible(cmpToolBar, true);
+ } else {
+ splitter.setVisible(cmpTlEmpty, true);
+ splitter.setVisible(cmpToolBar, false);
+ }
+
+ return splitter;
+ }
+
+ public void showBar(String show) {
+ if (PREFERENCE_STATUS_BAR_ENABLE.equals(show)) {
+ splitter.setVisible(cmpToolBar, true);
+ splitter.setVisible(cmpTlEmpty, false);
+ splitter.getParent().layout(true, true);
+ } else {
+ splitter.setVisible(cmpToolBar, false);
+ splitter.setVisible(cmpTlEmpty, true);
+ splitter.getParent().layout(true, true);
+ }
+ }
+
+ public void setVpeController(VpeController vpeController) {
+ this.vpeController = vpeController;
+ }
+
+ public void selectionChanged() {
+ VpeSourceSelectionBuilder sourceSelectionBuilder = new VpeSourceSelectionBuilder(
+ vpeController.getSourceEditor());
+ VpeSourceSelection selection = sourceSelectionBuilder.getSelection();
+ if (selection == null) {
+ return;
+ }
+
+ // Node node = selection.getFocusNode();
+ Node node = selection.getStartNode();
+ if (node != null && node.getNodeType() == Node.TEXT_NODE) {
+ node = node.getParentNode();
+ }
+
+ int elementCounter = 0;
+ while (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
+ ToolItem item = null;
+ if (selBar.getItemCount() > elementCounter) {
+ item = selBar.getItem(selBar.getItemCount() - elementCounter
+ - 1);
+ item.setData(node);
+ } else {
+ item = new ToolItem(selBar, SWT.FLAT, 0);
+ item.addSelectionListener(this);
+ item.setData(node);
+ }
+
+ item.setText(node.getNodeName());
+ elementCounter++;
+ node = node.getParentNode();
+ }
+
+ itemCount = elementCounter;
+ cmpToolBar.layout();
+ // bug was fixed when toolbar are not shown for resizeble components
+ cmpToolBar.layout();
+ }
+
+ protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
+ Point point = selBar.computeSize(SWT.DEFAULT, hHint);
+ point.y = closeBar.getSize().y;
+ return point;
+ }
+
+ protected void layout(Composite composite, boolean flushCache) {
+ Rectangle rect = null;
+ try {
+ rect = composite.getBounds();
+ } catch (SWTException e) {
+ VpePlugin.getPluginLog().logError(e);
+ }
+
+ Rectangle closeBarRect = closeSelectionBar.getItem(0).getBounds();
+ rect.width -= closeBarRect.width;
+
+ int allItems = selBar.getItems().length;
+ if (allItems == 0) {
+ cmpBar.setBounds(new Rectangle(rect.x, rect.y, rect.width,
+ closeBarRect.height));
+ closeBar.setBounds(new Rectangle(rect.width, rect.y, rect.width
+ + closeBarRect.width, closeBarRect.height));
+ return;
+ }
+ Rectangle r = selBar.getItem(allItems - 1).getBounds();
+ int width = r.x + r.width;
+ int height = r.height;
+
+ if (allItems >= itemCount) {
+ int x = 0;
+
+ if (itemCount == 0) {
+ x = selBar.getBounds().width;
+ } else {
+ x = selBar.getItem(allItems - itemCount).getBounds().x;
+ }
+
+ rect.x -= x;
+
+ if (rect.width < (r.x + r.width - Math.abs(rect.x) + 10)) {
+ rect.x -= (r.x + r.width - Math.abs(rect.x)) - rect.width;
+ }
+
+ cmpBar.setBounds(new Rectangle(rect.x, 0, width, height));
+ selBar.setSize(width, closeBarRect.height);
+ closeBar.setBounds(new Rectangle(rect.width, rect.y, rect.width
+ + closeBarRect.width, closeBarRect.height));
+ }
+ }
+
+ public void dispose() {
+ if (!selBar.isDisposed()) {
+ for (int i = 0; i < selBar.getItemCount(); i++) {
+ if (!selBar.getItem(i).isDisposed()) {
+ selBar.getItem(i).removeSelectionListener(this);
+ }
+ }
+ selBar.dispose();
+ selBar = null;
+ }
+ if (!closeSelectionBar.isDisposed()) {
+ for (int i = 0; i < closeSelectionBar.getItemCount(); i++) {
+ if (!closeSelectionBar.getItem(i).isDisposed()) {
+ closeSelectionBar.getItem(i).removeSelectionListener(this);
+ }
+ }
+ closeSelectionBar.dispose();
+ closeSelectionBar = null;
+ }
+ if (splitter != null) {
+ splitter.dispose();
+ splitter = null;
+ }
+ }
+
+ public void widgetSelected(SelectionEvent e) {
+ ToolItem toolItem = (ToolItem) e.widget;
+ int offset = ((ElementImpl) toolItem.getData()).getStartOffset();
+ setSourceFocus(offset);
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+
+ private void setSourceFocus(int offset) {
+ vpeController.getPageContext().getSourceBuilder()
+ .getStructuredTextViewer().setSelectedRange(offset, 0);
+ vpeController.getPageContext().getSourceBuilder()
+ .getStructuredTextViewer().revealRange(offset, 0);
+ }
+
+ public String toString() {
+ StringBuffer st = new StringBuffer("CountItem: ");
+ st.append(itemCount);
+ st.append(" Parent Composite: " + cmpToolBar.getBounds().width);
+ st.append(" Midle composite: " + cmpBar.getBounds().width);
+ st.append(" Bar : " + selBar.getBounds().width);
+ return st.toString();
+ }
+}
16 years, 4 months
JBoss Tools SVN: r6143 - in trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp: jspeditor and 1 other directory.
by jbosstools-commits@lists.jboss.org
Author: mareshkau
Date: 2008-02-07 04:57:05 -0500 (Thu, 07 Feb 2008)
New Revision: 6143
Modified:
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualController.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualEditor.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageContributor.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditor.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorPart.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorSite.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditor.java
trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditorPageContext.java
Log:
http://jira.jboss.com/jira/browse/JBIDE-1105
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualController.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualController.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualController.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,27 +1,28 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.editor;
-
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Node;
-
-
-public interface IVisualController {
- public IStructuredModel getModel();
- public void drop(Node node, Node parentNode, int offset);
- public IVisualContext getPageContext();
- public void postLongOperation();
- public void preLongOperation();
- public void selectionChanged(SelectionChangedEvent event);
- public void refreshExternalLinks();
- public void visualRefresh();
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.editor;
+
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
+import org.w3c.dom.Node;
+
+
+public interface IVisualController extends SelectionListener {
+ public IStructuredModel getModel();
+ public void drop(Node node, Node parentNode, int offset);
+ public IVisualContext getPageContext();
+ public void postLongOperation();
+ public void preLongOperation();
+ public void selectionChanged(SelectionChangedEvent event);
+ public void refreshExternalLinks();
+ public void visualRefresh();
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualEditor.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualEditor.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/editor/IVisualEditor.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,27 +1,31 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.editor;
-
-import org.eclipse.ui.IReusableEditor;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-public interface IVisualEditor extends ITextEditor, IReusableEditor {
- public static final int VISUALSOURCE_MODE = 0;
- public static final int VISUAL_MODE = 1;
- public static final int SOURCE_MODE = 2;
-
- /** PREVIEW_MODE */
- public static final int PREVIEW_MODE = 3;
-
- public void setVisualMode(int mode);
- public IVisualController getController();
-
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.editor;
+
+import org.eclipse.ui.IReusableEditor;
+import org.eclipse.ui.texteditor.ITextEditor;
+
+public interface IVisualEditor extends ITextEditor, IReusableEditor {
+ public static final int VISUALSOURCE_MODE = 0;
+ public static final int VISUAL_MODE = 1;
+ public static final int SOURCE_MODE = 2;
+
+ /** PREVIEW_MODE */
+ public static final int PREVIEW_MODE = 3;
+
+ public void setVisualMode(int mode);
+ public IVisualController getController();
+ public Object getPreviewWebBrowser();
+ public void createPreviewBrowser();
+ public Object getVisualEditor();
+ public void createVisualEditor();
+
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageContributor.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageContributor.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageContributor.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,216 +1,231 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-import java.util.ResourceBundle;
-
-import org.jboss.tools.common.model.ui.texteditors.AbstractMultiPageContributor;
-import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.texteditor.IStatusField;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.ui.texteditor.RetargetTextEditorAction;
-import org.eclipse.wst.sse.ui.internal.actions.ActionDefinitionIds;
-import org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants;
-
-import org.jboss.tools.common.text.xml.xpl.ToggleOccurencesMarkUpAction;
-
-/**
- * @author Jeremy
- *
- */
-public class JSPMultiPageContributor extends AbstractMultiPageContributor {
- protected RetargetTextEditorAction fShowTooltipAction = null; // show
-
- protected RetargetTextEditorAction fContentAssist = null;
-
- public JSPMultiPageContributor() {
- fToggleOccurencesMarkUp = new ToggleOccurencesMarkUpAction();
- }
-
- public void init(IActionBars bars) {
- super.init(bars);
- initEditMenu(bars);
- ResourceBundle resourceBundle = ResourceHandler.getResourceBundle();
-
- fShowTooltipAction = new RetargetTextEditorAction(resourceBundle,
- StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION
- + StructuredTextEditorActionConstants.DOT);
- fShowTooltipAction
- .setActionDefinitionId(ActionDefinitionIds.INFORMATION);
-
- fContentAssist = new RetargetTextEditorAction(
- resourceBundle,
- StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS
- + StructuredTextEditorActionConstants.DOT);
- fContentAssist
- .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
-
- //TODO-3.3: keep checking if 'quick fix' action appears in WTP
-// fQuickFix = new RetargetTextEditorAction(resourceBundle,
-// StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX
-// + StructuredTextEditorActionConstants.DOT);
-// fQuickFix.setActionDefinitionId(ActionDefinitionIds.QUICK_FIX);
- }
-
- protected void createAssistObjects() {
- ResourceBundle resourceBundle = ResourceHandler.getResourceBundle();
-
- fContentAssistProposal = new RetargetTextEditorAction(
- resourceBundle,
- StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS
- + StructuredTextEditorActionConstants.DOT);
- fContentAssistProposal
- .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
-
- fContentAssistTip = new RetargetTextEditorAction(resourceBundle,
- StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION
- + StructuredTextEditorActionConstants.DOT);
- fContentAssistTip
- .setActionDefinitionId(ActionDefinitionIds.INFORMATION);
- }
-
- public void setActiveEditor(IEditorPart part) {
- IEditorPart activeNestedEditor = null;
- if (part instanceof JSPMultiPageEditor) {
- activeNestedEditor = ((JSPMultiPageEditor) part).getActiveEditor();
- }
- setActivePage(activeNestedEditor);
-
- mainPart = part;
-
- IActionBars actionBars = getActionBars();
-
- if (actionBars != null) {
- IStatusLineManager slm = actionBars.getStatusLineManager();
- if (slm != null) {
- slm.setErrorMessage(null);
- slm.setMessage(null);
- }
- }
- }
-
- public void setActivePage(IEditorPart part) {
- if (fActiveEditorPart == part)
- return;
- cleanStatusLine();
- fActiveEditorPart = part;
- IActionBars actionBars = getActionBars();
- if (actionBars != null) {
-
- ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part
- : null;
- if (editor != null) {
-
- actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
- getAction(editor, ITextEditorActionConstants.DELETE));
- actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(),
- getAction(editor, ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(),
- getAction(editor, ITextEditorActionConstants.REDO));
- actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(),
- getAction(editor, ITextEditorActionConstants.CUT));
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- getAction(editor, ITextEditorActionConstants.COPY));
- actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
- getAction(editor, ITextEditorActionConstants.PASTE));
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL
- .getId(), getAction(editor,
- ITextEditorActionConstants.SELECT_ALL));
- actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
- getAction(editor, ITextEditorActionConstants.FIND));
- actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK
- .getId(), getAction(editor, IDEActionFactory.BOOKMARK
- .getId()));
- actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK
- .getId(), getAction(editor, IDEActionFactory.ADD_TASK
- .getId()));
- actionBars.setGlobalActionHandler(ActionFactory.PRINT.getId(),
- getAction(editor, ITextEditorActionConstants.PRINT));
- actionBars.setGlobalActionHandler(ActionFactory.REVERT.getId(),
- getAction(editor, ITextEditorActionConstants.REVERT));
- actionBars.setGlobalActionHandler(ActionFactory.SAVE.getId(),
- getAction(editor, ITextEditorActionConstants.SAVE));
-
- fShowTooltipAction
- .setAction(getAction(
- editor,
- StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION));
- fContentAssist
- .setAction(getAction(
- editor,
- StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS));
- //TODO-3.3: keep checking if 'quick fix' action appears in WTP
- // fQuickFix
- // .setAction(getAction(
- // editor,
- // StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX));
-
-
- }
-
- // re-register action on key binding service
- IEditorPart localPart = (part != null) ? part : mainPart;
- if (localPart != null) {
- IHandlerService handler = (IHandlerService) localPart
- .getEditorSite().getService(IHandlerService.class);
- if (handler == null && mainPart != null) {
- handler = (IHandlerService) mainPart.getEditorSite()
- .getService(IHandlerService.class);
- }
- if (editor != null && handler != null) {
- // editor
- registerKeyBindings(handler, ACTIONS_2, editor);
- String[] ACTIONS_3 = {
- StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION,
- StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS,
-// TODO-3.3 StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX
- };
- registerKeyBindings(handler, ACTIONS_3, editor);
- }
- }
- cleanActionBarStatus();
- actionBars.updateActionBars();
- }
- fToggleOccurencesMarkUp.setEditor(getTextEditor(part));
- fToggleOccurencesMarkUp.update();
-
- updateStatus();
- }
-
- protected void updateStatus() {
- if (fActiveEditorPart instanceof ITextEditor) {
- ITextEditor textEditor = (ITextEditor) fActiveEditorPart;
- fContentAssistProposal
- .setAction(getAction(
- textEditor,
- StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS));
- fContentAssistTip
- .setAction(getAction(
- textEditor,
- StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION));
- }
- if (fActiveEditorPart instanceof ITextEditorExtension) {
- ITextEditorExtension extension = (ITextEditorExtension) fActiveEditorPart;
- for (int i = 0; i < STATUSFIELDS.length; i++)
- extension.setStatusField((IStatusField) fStatusFields
- .get(STATUSFIELDS[i]), STATUSFIELDS[i]);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+import java.util.ResourceBundle;
+
+import org.jboss.tools.common.model.ui.texteditors.AbstractMultiPageContributor;
+import org.eclipse.jem.internal.java.adapters.nls.ResourceHandler;
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.handlers.IHandlerService;
+import org.eclipse.ui.ide.IDEActionFactory;
+import org.eclipse.ui.texteditor.IStatusField;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorActionConstants;
+import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
+import org.eclipse.ui.texteditor.ITextEditorExtension;
+import org.eclipse.ui.texteditor.RetargetTextEditorAction;
+import org.eclipse.wst.sse.ui.internal.actions.ActionDefinitionIds;
+import org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants;
+
+import org.jboss.tools.common.text.xml.xpl.ToggleOccurencesMarkUpAction;
+
+/**
+ * @author Jeremy
+ *
+ */
+public class JSPMultiPageContributor extends AbstractMultiPageContributor {
+ protected RetargetTextEditorAction fShowTooltipAction = null; // show
+
+ protected RetargetTextEditorAction fContentAssist = null;
+
+ public JSPMultiPageContributor() {
+ fToggleOccurencesMarkUp = new ToggleOccurencesMarkUpAction();
+ }
+
+ public void init(IActionBars bars) {
+ super.init(bars);
+ initEditMenu(bars);
+ ResourceBundle resourceBundle = ResourceHandler.getResourceBundle();
+
+ fShowTooltipAction = new RetargetTextEditorAction(resourceBundle,
+ StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION
+ + StructuredTextEditorActionConstants.DOT);
+ fShowTooltipAction
+ .setActionDefinitionId(ActionDefinitionIds.INFORMATION);
+
+ fContentAssist = new RetargetTextEditorAction(
+ resourceBundle,
+ StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS
+ + StructuredTextEditorActionConstants.DOT);
+ fContentAssist
+ .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
+
+ //TODO-3.3: keep checking if 'quick fix' action appears in WTP
+// fQuickFix = new RetargetTextEditorAction(resourceBundle,
+// StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX
+// + StructuredTextEditorActionConstants.DOT);
+// fQuickFix.setActionDefinitionId(ActionDefinitionIds.QUICK_FIX);
+ }
+
+ protected void createAssistObjects() {
+ ResourceBundle resourceBundle = ResourceHandler.getResourceBundle();
+
+ fContentAssistProposal = new RetargetTextEditorAction(
+ resourceBundle,
+ StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS
+ + StructuredTextEditorActionConstants.DOT);
+ fContentAssistProposal
+ .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
+
+ fContentAssistTip = new RetargetTextEditorAction(resourceBundle,
+ StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION
+ + StructuredTextEditorActionConstants.DOT);
+ fContentAssistTip
+ .setActionDefinitionId(ActionDefinitionIds.INFORMATION);
+ }
+
+ public void setActiveEditor(IEditorPart part) {
+ IEditorPart activeNestedEditor = null;
+ if (part instanceof JSPMultiPageEditor) {
+ activeNestedEditor = ((JSPMultiPageEditor) part).getActiveEditor();
+ }
+ setActivePage(activeNestedEditor);
+
+ mainPart = part;
+
+ IActionBars actionBars = getActionBars();
+
+ if (actionBars != null) {
+ IStatusLineManager slm = actionBars.getStatusLineManager();
+ if (slm != null) {
+ slm.setErrorMessage(null);
+ slm.setMessage(null);
+ }
+ }
+ }
+
+ public void setActivePage(IEditorPart part) {
+ if (fActiveEditorPart == part)
+ return;
+ cleanStatusLine();
+ fActiveEditorPart = part;
+ IActionBars actionBars = getActionBars();
+ if (actionBars != null) {
+
+ ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part
+ : null;
+ if (editor != null) {
+
+ actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
+ getAction(editor, ITextEditorActionConstants.DELETE));
+ actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(),
+ getAction(editor, ITextEditorActionConstants.UNDO));
+ actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(),
+ getAction(editor, ITextEditorActionConstants.REDO));
+ actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(),
+ getAction(editor, ITextEditorActionConstants.CUT));
+ actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
+ getAction(editor, ITextEditorActionConstants.COPY));
+ actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
+ getAction(editor, ITextEditorActionConstants.PASTE));
+ actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL
+ .getId(), getAction(editor,
+ ITextEditorActionConstants.SELECT_ALL));
+ actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
+ getAction(editor, ITextEditorActionConstants.FIND));
+ actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK
+ .getId(), getAction(editor, IDEActionFactory.BOOKMARK
+ .getId()));
+ actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK
+ .getId(), getAction(editor, IDEActionFactory.ADD_TASK
+ .getId()));
+ actionBars.setGlobalActionHandler(ActionFactory.PRINT.getId(),
+ getAction(editor, ITextEditorActionConstants.PRINT));
+ actionBars.setGlobalActionHandler(ActionFactory.REVERT.getId(),
+ getAction(editor, ITextEditorActionConstants.REVERT));
+ actionBars.setGlobalActionHandler(ActionFactory.SAVE.getId(),
+ getAction(editor, ITextEditorActionConstants.SAVE));
+
+ fShowTooltipAction
+ .setAction(getAction(
+ editor,
+ StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION));
+ fContentAssist
+ .setAction(getAction(
+ editor,
+ StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS));
+ //TODO-3.3: keep checking if 'quick fix' action appears in WTP
+ // fQuickFix
+ // .setAction(getAction(
+ // editor,
+ // StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX));
+
+
+ }
+
+ // re-register action on key binding service
+ IEditorPart localPart = (part != null) ? part : mainPart;
+ if (localPart != null) {
+ IHandlerService handler = (IHandlerService) localPart
+ .getEditorSite().getService(IHandlerService.class);
+ if (handler == null && mainPart != null) {
+ handler = (IHandlerService) mainPart.getEditorSite()
+ .getService(IHandlerService.class);
+ }
+ if (editor != null && handler != null) {
+ // editor
+ registerKeyBindings(handler, ACTIONS_2, editor);
+ String[] ACTIONS_3 = {
+ StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION,
+ StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS,
+// TODO-3.3 StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX
+ };
+ registerKeyBindings(handler, ACTIONS_3, editor);
+ }
+ }
+ cleanActionBarStatus();
+ actionBars.updateActionBars();
+ }
+ fToggleOccurencesMarkUp.setEditor(getTextEditor(part));
+ fToggleOccurencesMarkUp.update();
+
+ updateStatus();
+ }
+
+ protected void updateStatus() {
+ if (fActiveEditorPart instanceof ITextEditor) {
+ ITextEditor textEditor = (ITextEditor) fActiveEditorPart;
+ fContentAssistProposal
+ .setAction(getAction(
+ textEditor,
+ StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS));
+ fContentAssistTip
+ .setAction(getAction(
+ textEditor,
+ StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION));
+ }
+ if (fActiveEditorPart instanceof ITextEditorExtension) {
+ ITextEditorExtension extension = (ITextEditorExtension) fActiveEditorPart;
+ for (int i = 0; i < STATUSFIELDS.length; i++)
+ extension.setStatusField((IStatusField) fStatusFields
+ .get(STATUSFIELDS[i]), STATUSFIELDS[i]);
+ }
+ }
+
+ public void dispose() {
+ if (fToggleOccurencesMarkUp != null) {
+ fToggleOccurencesMarkUp.setEditor(null);
+ fToggleOccurencesMarkUp = null;
+ }
+ super.dispose();
+ fActiveEditorPart=null;
+ mainPart=null;
+ fContentAssist=null;
+ fContentAssistProposal=null;
+ fContentAssistTip=null;
+ fShowTooltipAction=null;
+
+ }
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditor.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditor.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditor.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,835 +1,865 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-import java.util.Properties;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-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.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextSelection;
-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.SelectionChangedEvent;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorActionBarContributor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.INavigationLocation;
-import org.eclipse.ui.INavigationLocationProvider;
-import org.eclipse.ui.IPropertyListener;
-import org.eclipse.ui.IReusableEditor;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IGotoMarker;
-import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
-import org.eclipse.ui.texteditor.AbstractTextEditor;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.IStatusField;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.ui.texteditor.ITextEditorExtension2;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.ui.views.properties.IPropertySheetPage;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage;
-import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.event.XModelTreeEvent;
-import org.jboss.tools.common.model.event.XModelTreeListener;
-import org.jboss.tools.common.model.filesystems.impl.DiscardFileHandler;
-import org.jboss.tools.common.model.filesystems.impl.FolderImpl;
-import org.jboss.tools.common.model.plugin.ModelPlugin;
-import org.jboss.tools.common.model.ui.ModelUIPlugin;
-import org.jboss.tools.common.model.ui.editor.EditorDescriptor;
-import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
-import org.jboss.tools.common.model.util.EclipseResourceUtil;
-import org.jboss.tools.common.model.util.XModelTreeListenerSWTSync;
-import org.jboss.tools.common.text.ext.IMultiPageEditor;
-import org.jboss.tools.jst.jsp.JspEditorPlugin;
-import org.jboss.tools.jst.jsp.editor.IVisualContext;
-import org.jboss.tools.jst.jsp.editor.IVisualController;
-import org.jboss.tools.jst.jsp.editor.IVisualEditor;
-import org.jboss.tools.jst.jsp.editor.IVisualEditorFactory;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.jst.web.tld.VpeTaglibManager;
-import org.jboss.tools.jst.web.tld.VpeTaglibManagerProvider;
-import org.osgi.framework.Bundle;
-
-// Fix for EXIN-232: The IMultiPageEditor interface implementation is added.
-public class JSPMultiPageEditor extends JSPMultiPageEditorPart implements
- XModelTreeListener, ITextEditor, IGotoMarker, VpeTaglibManagerProvider,
- IReusableEditor, ITextEditorExtension, ITextEditorExtension2,
- ITextEditorExtension3, INavigationLocationProvider, IMultiPageEditor {
-
- private static final String VISUALSOURCE_TAB_LABEL = "JSPMultiPageEditor.TabLabel.VisualSource";
-
- private static final String VISUAL_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Visual";
-
- private static final String SOURCE_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Source";
-
- /** PREVIEW_TAB_LABEL */
- private static final String PREVIEW_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Preview";
-
- private IVisualEditor visualEditor;
-
- private int visualSourceIndex;
-
- private int visualIndex;
-
- JSPTextEditor sourceEditor;
-
- private int sourceIndex;
-
- /** composite control for default web-browser */
- private IVisualEditor previewWebBrowser;
-
- /** index of tab contain default web-browser */
- private int previewIndex;
-
- private boolean osWindows = true;
-
- protected XModelTreeListenerSWTSync syncListener = new XModelTreeListenerSWTSync(
- this);
-
- private int oldPage = -1;
-
- private ConfigurableContentOutlinePage outlinePage = null;
-
- XModelObject object;
-
- private QualifiedName persistentTabQualifiedName = new QualifiedName("",
- "Selected_tab");
-
- int selectedPageIndex = 0;
-
- static IVisualEditorFactory visualEditorFactory;
-
- static {
- try {
- Bundle b = Platform.getBundle("org.jboss.tools.vpe");
- Class cls = b
- .loadClass("org.jboss.tools.vpe.editor.VpeEditorPartFactory");
- visualEditorFactory = (IVisualEditorFactory) cls.newInstance();
- } catch (Exception e) {
- JspEditorPlugin.getPluginLog().logError("Error in loading visual editor factory", e);
- }
- }
-
- private void loadSelectedTab() {
- IFile file = getFile();
- try {
- String q = (file == null) ? null : file.getPersistentProperty(persistentTabQualifiedName);
- if (q == null) {
- if ("Source".equalsIgnoreCase(VpePreference.EDITOR_VIEW_OPTION
- .getValue()))
- selectedPageIndex = 2;
- else if ("Visual"
- .equalsIgnoreCase(VpePreference.EDITOR_VIEW_OPTION
- .getValue()))
- selectedPageIndex = 1;
- else
- selectedPageIndex = 0;
- } else {
- int qi = Integer.parseInt(q);
-
- if (qi >= 0 && qi < getTabFolder().getItemCount())
- selectedPageIndex = qi;
- }
-
- } catch (Exception e) {
- selectedPageIndex = 0;
- }
- }
-
- protected int getSourcePageIndex() {
- return sourceIndex;
- }
-
- private void saveSelectedTab() {
- IFile file = getFile();
- if(file == null) return;
- String q = "" + selectedPageIndex;
- try {
- file.setPersistentProperty(persistentTabQualifiedName, q);
- } catch (CoreException e) {
- JspEditorPlugin.getPluginLog().logWarning(e);
- }
- }
-
- public void superPageChange(int newPageIndex) {
- Control control = getControl(visualSourceIndex);
- if (control != null) {
- control.setVisible(true);
- }
- setFocus();
- IEditorPart activeEditor = getEditor(visualSourceIndex);
- IEditorActionBarContributor contributor = getEditorSite()
- .getActionBarContributor();
- if (contributor != null
- && contributor instanceof MultiPageEditorActionBarContributor) {
- ((MultiPageEditorActionBarContributor) contributor)
- .setActivePage(activeEditor);
- }
- if (activeEditor != null) {
- ISelectionProvider selectionProvider = activeEditor.getSite()
- .getSelectionProvider();
- if (selectionProvider != null) {
- SelectionChangedEvent event = new SelectionChangedEvent(
- selectionProvider, selectionProvider.getSelection());
- ((JSPMultiPageSelectionProvider) getSite()
- .getSelectionProvider()).fireSelectionChanged(event);
- }
- }
- }
-
- protected void pageChange(int newPageIndex) {
- selectedPageIndex = newPageIndex;
- if (osWindows) {
- if (newPageIndex == visualSourceIndex)
- visualEditor.setVisualMode(IVisualEditor.VISUALSOURCE_MODE);
- else if (newPageIndex == visualIndex)
- visualEditor.setVisualMode(IVisualEditor.VISUAL_MODE);
- else if (newPageIndex == sourceIndex)
- visualEditor.setVisualMode(IVisualEditor.SOURCE_MODE);
- else if (newPageIndex == previewIndex) {
- visualEditor.setVisualMode(IVisualEditor.PREVIEW_MODE);
- }
-
- superPageChange(newPageIndex);
- } else {
- super.pageChange(newPageIndex);
- }
- oldPage = newPageIndex;
- }
-
- public void setInput(IEditorInput input) {
- super.setInput(XModelObjectEditorInput.checkInput(input));
- if (getEditorInput() instanceof IModelObjectEditorInput) {
- object = ((IModelObjectEditorInput) getEditorInput())
- .getXModelObject();
- }
- if (sourceEditor != null
- && sourceEditor.getEditorInput() != getEditorInput()
- && sourceEditor.getEditorInput() != null) {
- if (sourceEditor instanceof AbstractTextEditor) {
- try {
- ((AbstractTextEditor) sourceEditor)
- .setInput(getEditorInput());
- } catch (Exception exc) {
- JspEditorPlugin.getPluginLog().logError(exc);
- }
- }
- visualEditor.setInput(getEditorInput());
- updateTitle();
- }
- updateFile();
- }
-
- private void updateFile() {
- IFile file = getFile();
- if (file == null) return;
- try {
- file.refreshLocal(0, null);
- } catch (CoreException e) {
- JspEditorPlugin.getPluginLog().logWarning(e);
- }
- }
-
- private IFile getFile() {
- IEditorInput input = getEditorInput();
- return (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
- .getFile() : null;
- }
-
- public String getContentDescription() {
- return "";
- }
-
- /**
- *
- */
- private ISelectionProvider selectionProvider = null;
-
- protected IEditorSite createSite(IEditorPart editor) {
- JSPMultiPageEditorSite site = new JSPMultiPageEditorSite(this, editor) {
- private ISelectionChangedListener postSelectionChangedListener = null;
-
- private ISelectionChangedListener getPostSelectionChangedListener() {
- if (postSelectionChangedListener == null) {
- postSelectionChangedListener = new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- handlePostSelectionChanged(event);
- }
- };
- }
- return postSelectionChangedListener;
- }
-
- protected void handlePostSelectionChanged(
- SelectionChangedEvent event) {
- ISelectionProvider parentProvider = getMultiPageEditor()
- .getSite().getSelectionProvider();
- ISelection s = event.getSelection();
- if (s == null || s.isEmpty())
- return;
- if (s instanceof ITextSelection) {
- if (parentProvider instanceof JSPMultiPageSelectionProvider) {
- ((JSPMultiPageSelectionProvider) parentProvider)
- .firePostSelectionChanged(event);
- }
- }
- }
-
- public String getId() {
- return getSite().getId(); //$NON-NLS-1$
- }
-
- /**
- *
- */
- public ISelectionProvider getSelectionProvider() {
- return selectionProvider;
- }
-
- /**
- *
- */
- public void setSelectionProvider(ISelectionProvider provider) {
- ISelectionProvider oldSelectionProvider = getSelectionProvider();
- if (oldSelectionProvider != null) {
- if (oldSelectionProvider instanceof IPostSelectionProvider) {
- ((IPostSelectionProvider) oldSelectionProvider)
- .removePostSelectionChangedListener(getPostSelectionChangedListener());
- }
- }
-
- selectionProvider = provider;
- if (oldSelectionProvider != null) {
- oldSelectionProvider
- .removeSelectionChangedListener(getSelectionChangedListener());
- }
- if (selectionProvider != null) {
- selectionProvider
- .addSelectionChangedListener(getSelectionChangedListener());
- }
-
- if (provider != null) {
- if (provider instanceof IPostSelectionProvider) {
- ((IPostSelectionProvider) provider)
- .addPostSelectionChangedListener(getPostSelectionChangedListener());
- }
- }
- }
-
- public Object getService(Class api) {
- // TODO megration to eclipse 3.2
- return null;
- }
-
- public boolean hasService(Class api) {
- // TODO megration to eclipse 3.2
- return false;
- }
- };
- return site;
- }
-
- protected void createPages() {
-
- // Sergey Vasilyev
- /*
- * TODO to author of this class VPE work on linux! this check not need
- * in future
- */
- // String os_name = System.getProperty("os.name");
- if (true) {// (os_name.startsWith("Windows")){
- osWindows = true;
- createPagesForWindows();
- } else {
- osWindows = false;
- }
- if (selectedPageIndex == sourceIndex) {
- visualEditor.setVisualMode(IVisualEditor.SOURCE_MODE);
- // switchOutlineToJSPEditor();
- }
- loadSelectedTab();
- setActivePage(selectedPageIndex);
- pageChange(selectedPageIndex);
-
- new ResourceChangeListener(this, getContainer());
- if (getModelObject() != null) {
- getModelObject().getModel().addModelTreeListener(syncListener);
- }
- }
-
- private void createPagesForWindows() {
- sourceEditor = new JSPTextEditor(this);
- visualEditor = visualEditorFactory.createVisualEditor(this,
- sourceEditor, false);
-
- try {
- visualSourceIndex = addPage(visualEditor, getEditorInput());
- setPageText(visualSourceIndex, JSPEditorMessages
- .getString(VISUALSOURCE_TAB_LABEL));
- setPartName(visualEditor.getTitle());
- } catch (PartInitException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
- try {
- visualIndex = addPage(visualEditor, getEditorInput());
- setPageText(visualIndex, JSPEditorMessages
- .getString(VISUAL_TAB_LABEL));
- setPartName(visualEditor.getTitle());
- } catch (PartInitException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
-
- try {
- sourceIndex = addPage(visualEditor, getEditorInput());
- setPageText(sourceIndex, JSPEditorMessages
- .getString(SOURCE_TAB_LABEL));
- setPartName(visualEditor.getTitle());
- } catch (PartInitException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
-
- // Add tab contain default web-browser
- try {
- previewIndex = addPage(visualEditor, getEditorInput());
- setPageText(previewIndex, JSPEditorMessages
- .getString(PREVIEW_TAB_LABEL));
- setPartName(visualEditor.getTitle());
- } catch (PartInitException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
-
- }
-
- public void doSave(IProgressMonitor monitor) {
- sourceEditor.doSave(monitor);
- }
-
- class PCL implements IPropertyListener {
- public void propertyChanged(Object source, int i) {
- firePropertyChange(i);
- if (i == IEditorPart.PROP_INPUT
- && getEditorInput() != sourceEditor.getEditorInput()) {
- setInput(sourceEditor.getEditorInput());
- setPartName(sourceEditor.getPartName());
- setTitleToolTip(sourceEditor.getTitleToolTip());
- }
- }
- }
-
- public void doSaveAs() {
- XModelObject old = getModelObject();
- PCL pcl = new PCL();
- sourceEditor.addPropertyListener(pcl);
- sourceEditor.doSaveAs();
- sourceEditor.removePropertyListener(pcl);
- try {
- if (old.isModified())
- new DiscardFileHandler().executeHandler(old, new Properties());
- } catch (Exception e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
- }
-
- public void gotoMarker(final IMarker marker) {
- setActivePage(sourceIndex);
- pageChange(sourceIndex);
- IGotoMarker adapter = (IGotoMarker) sourceEditor
- .getAdapter(IGotoMarker.class);
- if (adapter != null) {
- adapter.gotoMarker(marker);
- }
- }
-
- public boolean isSaveAsAllowed() {
- return sourceEditor.isSaveAsAllowed();
- }
-
- public JSPTextEditor getJspEditor() {
- return sourceEditor;
- }
-
- public StructuredTextEditor getSourceEditor() {
- return sourceEditor;
- }
-
- public IVisualEditor getVisualEditor() {
- return visualEditor;
- }
-
- public IEditorPart getActivePageEditor() {
- return getActiveEditor();
- }
-
- protected XModelObject getModelObject() {
- return object;
- }
-
- public void dispose() {
- saveSelectedTab();
- XModelObject o = getModelObject();
- visualEditor.dispose();
- super.dispose();
- if (o != null) {
- o.getModel().removeModelTreeListener(syncListener);
- }
- if (o != null && o.isModified() && o.isActive()) {
- try {
- ((FolderImpl) o.getParent()).discardChildFile(o);
- } catch (Exception e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
- }
- }
-
- public Object getAdapter(Class adapter) {
- if (IContentOutlinePage.class.equals(adapter)) {
- if (osWindows) {
- if (visualEditor != null) {
- if (outlinePage == null)
- outlinePage = (ConfigurableContentOutlinePage) visualEditor
- .getAdapter(adapter);
- return outlinePage;
- }
- } else {
- if (sourceEditor != null) {
- return sourceEditor.getAdapter(adapter);
- }
- }
- } else if (IPropertySheetPage.class.equals(adapter)) {
- if (sourceEditor != null)
- return sourceEditor.getAdapter(adapter);
- } else if (adapter == EditorDescriptor.class)
- return new EditorDescriptor(new String[] { "jsp", "html" });
-
- if (sourceEditor != null) {
- return sourceEditor.getAdapter(adapter);
- }
-
- return super.getAdapter(adapter);
- }
-
- public void nodeChanged(XModelTreeEvent event) {
- if (event.getModelObject() == getModelObject()) {
- setContentDescription(getEditorInput().getName());
- if (sourceEditor != null)
- sourceEditor.updateModification();
- }
- }
-
- public void structureChanged(XModelTreeEvent event) {
- }
-
- public void close(boolean save) {
- sourceEditor.close(save);
- }
-
- public void doRevertToSaved() {
- sourceEditor.doRevertToSaved();
- }
-
- public IAction getAction(String actionId) {
- return sourceEditor.getAction(actionId);
- }
-
- public IDocumentProvider getDocumentProvider() {
- return sourceEditor.getDocumentProvider();
- }
-
- public IRegion getHighlightRange() {
- return sourceEditor.getHighlightRange();
- }
-
- public ISelectionProvider getSelectionProvider() {
- return sourceEditor.getSelectionProvider();
- }
-
- public boolean isEditable() {
- return sourceEditor.isEditable();
- }
-
- public void removeActionActivationCode(String actionId) {
- sourceEditor.removeActionActivationCode(actionId);
- }
-
- public void resetHighlightRange() {
- sourceEditor.resetHighlightRange();
- }
-
- public void selectAndReveal(int offset, int length) {
- sourceEditor.selectAndReveal(offset, length);
- }
-
- public void setAction(String actionID, IAction action) {
- sourceEditor.setAction(actionID, action);
- }
-
- public void setActionActivationCode(String actionId,
- char activationCharacter, int activationKeyCode,
- int activationStateMask) {
- sourceEditor.setActionActivationCode(actionId, activationCharacter,
- activationKeyCode, activationStateMask);
- }
-
- public void setHighlightRange(int offset, int length, boolean moveCursor) {
- sourceEditor.setHighlightRange(offset, length, moveCursor);
- }
-
- public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
- sourceEditor.showHighlightRangeOnly(showHighlightRangeOnly);
- }
-
- public boolean showsHighlightRangeOnly() {
- return sourceEditor.showsHighlightRangeOnly();
- }
-
- public VpeTaglibManager getTaglibManager() {
- if (visualEditor != null) {
- IVisualController controller = visualEditor.getController();
- if (controller != null) {
- IVisualContext context = controller.getPageContext();
- if (context != null) {
- return context;
- }
- }
- }
- return null;
- }
-
- void updateTitle() {
- setPartName(getEditorInput().getName());
- }
-
- public void runDropCommand(String flavor, String data) {
- if (sourceEditor != null)
- sourceEditor.runDropCommand(flavor, data);
- }
-
- public void setStatusField(IStatusField field, String category) {
- if (sourceEditor != null)
- sourceEditor.setStatusField(field, category);
- }
-
- public boolean isEditorInputReadOnly() {
- if (sourceEditor != null) {
- return sourceEditor.isEditorInputReadOnly();
- }
- return false;
- }
-
- public void addRulerContextMenuListener(IMenuListener listener) {
- if (sourceEditor != null)
- sourceEditor.addRulerContextMenuListener(listener);
- }
-
- public void removeRulerContextMenuListener(IMenuListener listener) {
- if (sourceEditor != null)
- sourceEditor.removeRulerContextMenuListener(listener);
- }
-
- public boolean isEditorInputModifiable() {
- if (sourceEditor != null) {
- return sourceEditor.isEditorInputModifiable();
- }
- return false;
- }
-
- public boolean validateEditorInputState() {
- if (sourceEditor != null) {
- return sourceEditor.validateEditorInputState();
- }
- return false;
- }
-
- public InsertMode getInsertMode() {
- if (sourceEditor != null) {
- return sourceEditor.getInsertMode();
- }
- return null;
- }
-
- public void setInsertMode(InsertMode mode) {
- if (sourceEditor != null)
- sourceEditor.setInsertMode(mode);
- }
-
- public void showChangeInformation(boolean show) {
- if (sourceEditor != null)
- sourceEditor.showChangeInformation(show);
- }
-
- public boolean isChangeInformationShowing() {
- if (sourceEditor != null) {
- return sourceEditor.isChangeInformationShowing();
- }
- return false;
- }
-
- public INavigationLocation createEmptyNavigationLocation() {
- if (sourceEditor != null) {
- return sourceEditor.createEmptyNavigationLocation();
- }
- return null;
- }
-
- public INavigationLocation createNavigationLocation() {
- if (sourceEditor != null) {
- return sourceEditor.createNavigationLocation();
- }
- return null;
- }
-}
-
-class ResourceChangeListener implements IResourceChangeListener {
- IEditorPart editorPart;
-
- Composite container;
-
- ResourceChangeListener(IEditorPart editorPart, Composite container) {
- this.editorPart = editorPart;
- this.container = container;
- IWorkspace workspace = ModelUIPlugin.getWorkspace();
- if (workspace == null)
- return;
- workspace.addResourceChangeListener(this);
- container.addDisposeListener(new DisposeListener() {
- public void widgetDisposed(DisposeEvent e) {
- IWorkspace workspace = ModelUIPlugin.getWorkspace();
- if (workspace == null)
- return;
- workspace
- .removeResourceChangeListener(ResourceChangeListener.this);
- }
- });
- }
-
- public void resourceChanged(IResourceChangeEvent event) {
- IEditorInput ei = editorPart.getEditorInput();
- if (!(ei instanceof IFileEditorInput))
- return;
- IFileEditorInput fi = (IFileEditorInput) ei;
- IFile f = fi.getFile();
- if (f == null)
- return;
- IPath path = getPathChange(event, f);
- if (path == null) {
- if (f != null && !f.exists())
- closeEditor();
- return;
- }
- f = ModelPlugin.getWorkspace().getRoot().getFile(path);
- XModelObject p = f == null ? null : EclipseResourceUtil
- .getObjectByResource(f.getParent());
- if (p instanceof FolderImpl) {
- ((FolderImpl) p).update();
- }
- XModelObject o = EclipseResourceUtil.getObjectByResource(f);
- if (f != null && f.exists() && o != null) {
- if (editorPart instanceof JSPMultiPageEditor) {
- JSPMultiPageEditor e = (JSPMultiPageEditor) editorPart;
- if (ei instanceof XModelObjectEditorInput) {
- IEditorInput e2 = XModelObjectEditorInput.createInstance(o);
- e.setInput(e2);
- e.updateTitle();
- if (e.sourceEditor instanceof AbstractTextEditor) {
- if (e.sourceEditor != null
- && e.sourceEditor.getEditorInput() != e
- .getEditorInput()) {
- try {
- ((AbstractTextEditor) e.sourceEditor)
- .setInput(e2);
- } catch (Exception exc) {
- JspEditorPlugin.getPluginLog().logError(exc);
- }
- }
- ((XModelObjectEditorInput) ei).synchronize();
- }
- }
- }
- }
- if (f == null || f.exists())
- return;
- closeEditor();
- }
-
- private void closeEditor() {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- editorPart.getSite().getPage().closeEditor(editorPart, false);
- }
- });
- }
-
- private IPath getPathChange(IResourceChangeEvent event, IFile f) {
- return getPathChange(event.getDelta(), f.getFullPath());
- }
-
- private IPath getPathChange(IResourceDelta delta, IPath p) {
- if (delta == null || delta.getFullPath() == null)
- return null;
- if (!delta.getFullPath().isPrefixOf(p))
- return null;
- if (delta != null && delta.getKind() == IResourceDelta.CHANGED) {
- IResourceDelta[] ds = delta.getAffectedChildren();
- if (ds == null)
- return null;
- if (ds.length == 2) {
- if (ds[1].getKind() == IResourceDelta.REMOVED) {
- IPath d = ds[1].getFullPath();
- if (d.equals(p))
- return ds[0].getFullPath();
- if (d.isPrefixOf(p)) {
- return ds[0].getFullPath().append(
- p.removeFirstSegments(d.segmentCount()));
- }
- } else if (ds[0].getKind() == IResourceDelta.REMOVED) {
- IPath d = ds[0].getFullPath();
- if (d.equals(p))
- return ds[1].getFullPath();
- if (d.isPrefixOf(p)) {
- return ds[1].getFullPath().append(
- p.removeFirstSegments(d.segmentCount()));
- }
- }
- }
- for (int i = 0; i < ds.length; i++) {
- IPath ps = getPathChange(ds[i], p);
- if (ps != null)
- return ps;
- }
- }
- return null;
- }
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+import java.util.Properties;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+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.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.QualifiedName;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuListener;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextSelection;
+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.SelectionChangedEvent;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IEditorActionBarContributor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IFileEditorInput;
+import org.eclipse.ui.INavigationLocation;
+import org.eclipse.ui.INavigationLocationProvider;
+import org.eclipse.ui.IPropertyListener;
+import org.eclipse.ui.IReusableEditor;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.ide.IGotoMarker;
+import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
+import org.eclipse.ui.texteditor.AbstractTextEditor;
+import org.eclipse.ui.texteditor.IDocumentProvider;
+import org.eclipse.ui.texteditor.IStatusField;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorExtension;
+import org.eclipse.ui.texteditor.ITextEditorExtension2;
+import org.eclipse.ui.texteditor.ITextEditorExtension3;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+import org.eclipse.ui.views.properties.IPropertySheetPage;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage;
+import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.event.XModelTreeEvent;
+import org.jboss.tools.common.model.event.XModelTreeListener;
+import org.jboss.tools.common.model.filesystems.impl.DiscardFileHandler;
+import org.jboss.tools.common.model.filesystems.impl.FolderImpl;
+import org.jboss.tools.common.model.plugin.ModelPlugin;
+import org.jboss.tools.common.model.ui.ModelUIPlugin;
+import org.jboss.tools.common.model.ui.editor.EditorDescriptor;
+import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
+import org.jboss.tools.common.model.util.EclipseResourceUtil;
+import org.jboss.tools.common.model.util.XModelTreeListenerSWTSync;
+import org.jboss.tools.common.text.ext.IMultiPageEditor;
+import org.jboss.tools.jst.jsp.JspEditorPlugin;
+import org.jboss.tools.jst.jsp.editor.IVisualContext;
+import org.jboss.tools.jst.jsp.editor.IVisualController;
+import org.jboss.tools.jst.jsp.editor.IVisualEditor;
+import org.jboss.tools.jst.jsp.editor.IVisualEditorFactory;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.jst.web.tld.VpeTaglibManager;
+import org.jboss.tools.jst.web.tld.VpeTaglibManagerProvider;
+import org.osgi.framework.Bundle;
+
+// Fix for EXIN-232: The IMultiPageEditor interface implementation is added.
+public class JSPMultiPageEditor extends JSPMultiPageEditorPart implements
+ XModelTreeListener, ITextEditor, IGotoMarker, VpeTaglibManagerProvider,
+ IReusableEditor, ITextEditorExtension, ITextEditorExtension2,
+ ITextEditorExtension3, INavigationLocationProvider, IMultiPageEditor {
+
+ private static final String VISUALSOURCE_TAB_LABEL = "JSPMultiPageEditor.TabLabel.VisualSource";
+
+ private static final String VISUAL_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Visual";
+
+ private static final String SOURCE_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Source";
+
+ /** PREVIEW_TAB_LABEL */
+ private static final String PREVIEW_TAB_LABEL = "JSPMultiPageEditor.TabLabel.Preview";
+
+ private IVisualEditor visualEditor;
+
+ private int visualSourceIndex;
+
+ private int visualIndex;
+
+ JSPTextEditor sourceEditor;
+
+ private int sourceIndex;
+
+ /** composite control for default web-browser */
+ //private IVisualEditor previewWebBrowser;
+
+ /** index of tab contain default web-browser */
+ private int previewIndex;
+
+ private boolean osWindows = true;
+
+ protected XModelTreeListenerSWTSync syncListener = new XModelTreeListenerSWTSync(
+ this);
+
+ private int oldPage = -1;
+
+ private ConfigurableContentOutlinePage outlinePage = null;
+
+ XModelObject object;
+
+ private QualifiedName persistentTabQualifiedName = new QualifiedName("",
+ "Selected_tab");
+
+ int selectedPageIndex = 0;
+
+ static IVisualEditorFactory visualEditorFactory;
+
+ static {
+ try {
+ Bundle b = Platform.getBundle("org.jboss.tools.vpe");
+ Class cls = b
+ .loadClass("org.jboss.tools.vpe.editor.VpeEditorPartFactory");
+ visualEditorFactory = (IVisualEditorFactory) cls.newInstance();
+ } catch (Exception e) {
+ JspEditorPlugin.getPluginLog().logError("Error in loading visual editor factory", e);
+ }
+ }
+
+ private void loadSelectedTab() {
+ IFile file = getFile();
+ try {
+ String q = (file == null) ? null : file.getPersistentProperty(persistentTabQualifiedName);
+ if (q == null) {
+ if ("Source".equalsIgnoreCase(VpePreference.EDITOR_VIEW_OPTION
+ .getValue()))
+ selectedPageIndex = 2;
+ else if ("Visual"
+ .equalsIgnoreCase(VpePreference.EDITOR_VIEW_OPTION
+ .getValue()))
+ selectedPageIndex = 1;
+ else
+ selectedPageIndex = 0;
+ } else {
+ int qi = Integer.parseInt(q);
+
+ if (qi >= 0 && qi < getTabFolder().getItemCount())
+ selectedPageIndex = qi;
+ }
+
+ } catch (Exception e) {
+ selectedPageIndex = 0;
+ }
+ }
+
+ protected int getSourcePageIndex() {
+ return sourceIndex;
+ }
+
+ private void saveSelectedTab() {
+ IFile file = getFile();
+ if(file == null) return;
+ String q = "" + selectedPageIndex;
+ try {
+ file.setPersistentProperty(persistentTabQualifiedName, q);
+ } catch (CoreException e) {
+ JspEditorPlugin.getPluginLog().logWarning(e);
+ }
+ }
+
+ public void superPageChange(int newPageIndex) {
+ Control control = getControl(visualSourceIndex);
+ if (control != null) {
+ control.setVisible(true);
+ }
+ setFocus();
+ IEditorPart activeEditor = getEditor(visualSourceIndex);
+ IEditorActionBarContributor contributor = getEditorSite()
+ .getActionBarContributor();
+ if (contributor != null
+ && contributor instanceof MultiPageEditorActionBarContributor) {
+ ((MultiPageEditorActionBarContributor) contributor)
+ .setActivePage(activeEditor);
+ }
+ if (activeEditor != null) {
+ ISelectionProvider selectionProvider = activeEditor.getSite()
+ .getSelectionProvider();
+ if (selectionProvider != null) {
+ SelectionChangedEvent event = new SelectionChangedEvent(
+ selectionProvider, selectionProvider.getSelection());
+ ((JSPMultiPageSelectionProvider) getSite()
+ .getSelectionProvider()).fireSelectionChanged(event);
+ }
+ }
+ }
+
+ protected void pageChange(int newPageIndex) {
+ selectedPageIndex = newPageIndex;
+ if (osWindows) {
+ if (newPageIndex == visualSourceIndex) {
+ if (visualEditor.getVisualEditor() == null) {
+ visualEditor.createVisualEditor();
+ }
+ visualEditor.setVisualMode(IVisualEditor.VISUALSOURCE_MODE);
+ }
+ else if (newPageIndex == visualIndex) {
+ if (visualEditor.getVisualEditor() == null) {
+ visualEditor.createVisualEditor();
+ }
+ visualEditor.setVisualMode(IVisualEditor.VISUAL_MODE);
+ }
+ else if (newPageIndex == sourceIndex)
+ visualEditor.setVisualMode(IVisualEditor.SOURCE_MODE);
+ else if (newPageIndex == previewIndex) {
+ if (visualEditor.getPreviewWebBrowser() == null) {
+ visualEditor.createPreviewBrowser();
+ }
+ visualEditor.setVisualMode(IVisualEditor.PREVIEW_MODE);
+ }
+
+ superPageChange(newPageIndex);
+ } else {
+ super.pageChange(newPageIndex);
+ }
+ oldPage = newPageIndex;
+ }
+
+ public void setInput(IEditorInput input) {
+ super.setInput(XModelObjectEditorInput.checkInput(input));
+ if (getEditorInput() instanceof IModelObjectEditorInput) {
+ object = ((IModelObjectEditorInput) getEditorInput())
+ .getXModelObject();
+ }
+ if (sourceEditor != null
+ && sourceEditor.getEditorInput() != getEditorInput()
+ && sourceEditor.getEditorInput() != null) {
+ if (sourceEditor instanceof AbstractTextEditor) {
+ try {
+ ((AbstractTextEditor) sourceEditor)
+ .setInput(getEditorInput());
+ } catch (Exception exc) {
+ JspEditorPlugin.getPluginLog().logError(exc);
+ }
+ }
+ visualEditor.setInput(getEditorInput());
+ updateTitle();
+ }
+ updateFile();
+ }
+
+ private void updateFile() {
+ IFile file = getFile();
+ if (file == null) return;
+ try {
+ file.refreshLocal(0, null);
+ } catch (CoreException e) {
+ JspEditorPlugin.getPluginLog().logWarning(e);
+ }
+ }
+
+ private IFile getFile() {
+ IEditorInput input = getEditorInput();
+ return (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
+ .getFile() : null;
+ }
+
+ public String getContentDescription() {
+ return "";
+ }
+
+ /**
+ *
+ */
+ private ISelectionProvider selectionProvider = null;
+
+ private JSPMultiPageEditorSite site;
+
+ protected IEditorSite createSite(IEditorPart editor) {
+ site = new JSPMultiPageEditorSite(this, editor) {
+ private ISelectionChangedListener postSelectionChangedListener = null;
+
+ private ISelectionChangedListener getPostSelectionChangedListener() {
+ if (postSelectionChangedListener == null) {
+ postSelectionChangedListener = new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ handlePostSelectionChanged(event);
+ }
+ };
+ }
+ return postSelectionChangedListener;
+ }
+
+ protected void handlePostSelectionChanged(
+ SelectionChangedEvent event) {
+ ISelectionProvider parentProvider = getMultiPageEditor()
+ .getSite().getSelectionProvider();
+ ISelection s = event.getSelection();
+ if (s == null || s.isEmpty())
+ return;
+ if (s instanceof ITextSelection) {
+ if (parentProvider instanceof JSPMultiPageSelectionProvider) {
+ ((JSPMultiPageSelectionProvider) parentProvider)
+ .firePostSelectionChanged(event);
+ }
+ }
+ }
+
+ public String getId() {
+ return getSite().getId(); //$NON-NLS-1$
+ }
+
+ /**
+ *
+ */
+ public ISelectionProvider getSelectionProvider() {
+ return selectionProvider;
+ }
+
+ /**
+ *
+ */
+ public void setSelectionProvider(ISelectionProvider provider) {
+ ISelectionProvider oldSelectionProvider = getSelectionProvider();
+ if (oldSelectionProvider != null) {
+ if (oldSelectionProvider instanceof IPostSelectionProvider) {
+ ((IPostSelectionProvider) oldSelectionProvider)
+ .removePostSelectionChangedListener(getPostSelectionChangedListener());
+ }
+ }
+
+ selectionProvider = provider;
+ if (oldSelectionProvider != null) {
+ oldSelectionProvider
+ .removeSelectionChangedListener(getSelectionChangedListener());
+ }
+ if (selectionProvider != null) {
+ selectionProvider
+ .addSelectionChangedListener(getSelectionChangedListener());
+ }
+
+ if (provider != null) {
+ if (provider instanceof IPostSelectionProvider) {
+ ((IPostSelectionProvider) provider)
+ .addPostSelectionChangedListener(getPostSelectionChangedListener());
+ }
+ }
+
+
+ }
+
+ public Object getService(Class api) {
+ // TODO megration to eclipse 3.2
+ return null;
+ }
+
+ public boolean hasService(Class api) {
+ // TODO megration to eclipse 3.2
+ return false;
+ }
+
+ public void dispose() {
+ ISelectionProvider provider = getSelectionProvider();
+ if (provider instanceof IPostSelectionProvider && postSelectionChangedListener != null) {
+ ((IPostSelectionProvider) provider)
+ .removePostSelectionChangedListener(postSelectionChangedListener);
+
+ }
+ postSelectionChangedListener = null;
+ super.dispose();
+ }
+ };
+ return site;
+ }
+
+ protected void createPages() {
+
+ // Sergey Vasilyev
+ /*
+ * TODO to author of this class VPE work on linux! this check not need
+ * in future
+ */
+ // String os_name = System.getProperty("os.name");
+ if (true) {// (os_name.startsWith("Windows")){
+ osWindows = true;
+ createPagesForWindows();
+ } else {
+ osWindows = false;
+ }
+ if (selectedPageIndex == sourceIndex) {
+ visualEditor.setVisualMode(IVisualEditor.SOURCE_MODE);
+ // switchOutlineToJSPEditor();
+ }
+ loadSelectedTab();
+ setActivePage(selectedPageIndex);
+ pageChange(selectedPageIndex);
+
+ new ResourceChangeListener(this, getContainer());
+ if (getModelObject() != null) {
+ getModelObject().getModel().addModelTreeListener(syncListener);
+ }
+ }
+
+ private void createPagesForWindows() {
+ sourceEditor = new JSPTextEditor(this);
+ visualEditor = visualEditorFactory.createVisualEditor(this,
+ sourceEditor, false);
+
+ try {
+ visualSourceIndex = addPage(visualEditor, getEditorInput());
+ setPageText(visualSourceIndex, JSPEditorMessages
+ .getString(VISUALSOURCE_TAB_LABEL));
+ setPartName(visualEditor.getTitle());
+ } catch (PartInitException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ try {
+ visualIndex = addPage(visualEditor, getEditorInput());
+ setPageText(visualIndex, JSPEditorMessages
+ .getString(VISUAL_TAB_LABEL));
+ setPartName(visualEditor.getTitle());
+ } catch (PartInitException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+
+ try {
+ sourceIndex = addPage(visualEditor, getEditorInput());
+ setPageText(sourceIndex, JSPEditorMessages
+ .getString(SOURCE_TAB_LABEL));
+ setPartName(visualEditor.getTitle());
+ } catch (PartInitException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+
+ // Add tab contain default web-browser
+ try {
+ previewIndex = addPage(visualEditor, getEditorInput());
+ setPageText(previewIndex, JSPEditorMessages
+ .getString(PREVIEW_TAB_LABEL));
+ setPartName(visualEditor.getTitle());
+ } catch (PartInitException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+
+ }
+
+ public void doSave(IProgressMonitor monitor) {
+ sourceEditor.doSave(monitor);
+ }
+
+ class PCL implements IPropertyListener {
+ public void propertyChanged(Object source, int i) {
+ firePropertyChange(i);
+ if (i == IEditorPart.PROP_INPUT
+ && getEditorInput() != sourceEditor.getEditorInput()) {
+ setInput(sourceEditor.getEditorInput());
+ setPartName(sourceEditor.getPartName());
+ setTitleToolTip(sourceEditor.getTitleToolTip());
+ }
+ }
+ }
+
+ public void doSaveAs() {
+ XModelObject old = getModelObject();
+ PCL pcl = new PCL();
+ sourceEditor.addPropertyListener(pcl);
+ sourceEditor.doSaveAs();
+ sourceEditor.removePropertyListener(pcl);
+ try {
+ if (old.isModified())
+ new DiscardFileHandler().executeHandler(old, new Properties());
+ } catch (Exception e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ }
+
+ public void gotoMarker(final IMarker marker) {
+ setActivePage(sourceIndex);
+ pageChange(sourceIndex);
+ IGotoMarker adapter = (IGotoMarker) sourceEditor
+ .getAdapter(IGotoMarker.class);
+ if (adapter != null) {
+ adapter.gotoMarker(marker);
+ }
+ }
+
+ public boolean isSaveAsAllowed() {
+ return sourceEditor.isSaveAsAllowed();
+ }
+
+ public JSPTextEditor getJspEditor() {
+ return sourceEditor;
+ }
+
+ public StructuredTextEditor getSourceEditor() {
+ return sourceEditor;
+ }
+
+ public IVisualEditor getVisualEditor() {
+ return visualEditor;
+ }
+
+ public IEditorPart getActivePageEditor() {
+ return getActiveEditor();
+ }
+
+ protected XModelObject getModelObject() {
+ return object;
+ }
+
+ public void dispose() {
+ saveSelectedTab();
+ XModelObject o = getModelObject();
+ visualEditor.dispose();
+ site.dispose();
+ super.dispose();
+ if (o != null) {
+ o.getModel().removeModelTreeListener(syncListener);
+ }
+ if (syncListener != null)
+ syncListener.dispose();
+ syncListener=null;
+ if (o != null && o.isModified() && o.isActive()) {
+ try {
+ ((FolderImpl) o.getParent()).discardChildFile(o);
+ } catch (Exception e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ }
+ }
+
+ public Object getAdapter(Class adapter) {
+ if (IContentOutlinePage.class.equals(adapter)) {
+ if (osWindows) {
+ if (visualEditor != null) {
+ if (outlinePage == null)
+ outlinePage = (ConfigurableContentOutlinePage) visualEditor
+ .getAdapter(adapter);
+ return outlinePage;
+ }
+ } else {
+ if (sourceEditor != null) {
+ return sourceEditor.getAdapter(adapter);
+ }
+ }
+ } else if (IPropertySheetPage.class.equals(adapter)) {
+ if (sourceEditor != null)
+ return sourceEditor.getAdapter(adapter);
+ } else if (adapter == EditorDescriptor.class)
+ return new EditorDescriptor(new String[] { "jsp", "html" });
+
+ if (sourceEditor != null) {
+ return sourceEditor.getAdapter(adapter);
+ }
+
+ return super.getAdapter(adapter);
+ }
+
+ public void nodeChanged(XModelTreeEvent event) {
+ if (event.getModelObject() == getModelObject()) {
+ setContentDescription(getEditorInput().getName());
+ if (sourceEditor != null)
+ sourceEditor.updateModification();
+ }
+ }
+
+ public void structureChanged(XModelTreeEvent event) {
+ }
+
+ public void close(boolean save) {
+ sourceEditor.close(save);
+ }
+
+ public void doRevertToSaved() {
+ sourceEditor.doRevertToSaved();
+ }
+
+ public IAction getAction(String actionId) {
+ return sourceEditor.getAction(actionId);
+ }
+
+ public IDocumentProvider getDocumentProvider() {
+ return sourceEditor.getDocumentProvider();
+ }
+
+ public IRegion getHighlightRange() {
+ return sourceEditor.getHighlightRange();
+ }
+
+ public ISelectionProvider getSelectionProvider() {
+ return sourceEditor.getSelectionProvider();
+ }
+
+ public boolean isEditable() {
+ return sourceEditor.isEditable();
+ }
+
+ public void removeActionActivationCode(String actionId) {
+ sourceEditor.removeActionActivationCode(actionId);
+ }
+
+ public void resetHighlightRange() {
+ sourceEditor.resetHighlightRange();
+ }
+
+ public void selectAndReveal(int offset, int length) {
+ sourceEditor.selectAndReveal(offset, length);
+ }
+
+ public void setAction(String actionID, IAction action) {
+ sourceEditor.setAction(actionID, action);
+ }
+
+ public void setActionActivationCode(String actionId,
+ char activationCharacter, int activationKeyCode,
+ int activationStateMask) {
+ sourceEditor.setActionActivationCode(actionId, activationCharacter,
+ activationKeyCode, activationStateMask);
+ }
+
+ public void setHighlightRange(int offset, int length, boolean moveCursor) {
+ sourceEditor.setHighlightRange(offset, length, moveCursor);
+ }
+
+ public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
+ sourceEditor.showHighlightRangeOnly(showHighlightRangeOnly);
+ }
+
+ public boolean showsHighlightRangeOnly() {
+ return sourceEditor.showsHighlightRangeOnly();
+ }
+
+ public VpeTaglibManager getTaglibManager() {
+ if (visualEditor != null) {
+ IVisualController controller = visualEditor.getController();
+ if (controller != null) {
+ IVisualContext context = controller.getPageContext();
+ if (context != null) {
+ return context;
+ }
+ }
+ }
+ return null;
+ }
+
+ void updateTitle() {
+ setPartName(getEditorInput().getName());
+ }
+
+ public void runDropCommand(String flavor, String data) {
+ if (sourceEditor != null)
+ sourceEditor.runDropCommand(flavor, data);
+ }
+
+ public void setStatusField(IStatusField field, String category) {
+ if (sourceEditor != null)
+ sourceEditor.setStatusField(field, category);
+ }
+
+ public boolean isEditorInputReadOnly() {
+ if (sourceEditor != null) {
+ return sourceEditor.isEditorInputReadOnly();
+ }
+ return false;
+ }
+
+ public void addRulerContextMenuListener(IMenuListener listener) {
+ if (sourceEditor != null)
+ sourceEditor.addRulerContextMenuListener(listener);
+ }
+
+ public void removeRulerContextMenuListener(IMenuListener listener) {
+ if (sourceEditor != null)
+ sourceEditor.removeRulerContextMenuListener(listener);
+ }
+
+ public boolean isEditorInputModifiable() {
+ if (sourceEditor != null) {
+ return sourceEditor.isEditorInputModifiable();
+ }
+ return false;
+ }
+
+ public boolean validateEditorInputState() {
+ if (sourceEditor != null) {
+ return sourceEditor.validateEditorInputState();
+ }
+ return false;
+ }
+
+ public InsertMode getInsertMode() {
+ if (sourceEditor != null) {
+ return sourceEditor.getInsertMode();
+ }
+ return null;
+ }
+
+ public void setInsertMode(InsertMode mode) {
+ if (sourceEditor != null)
+ sourceEditor.setInsertMode(mode);
+ }
+
+ public void showChangeInformation(boolean show) {
+ if (sourceEditor != null)
+ sourceEditor.showChangeInformation(show);
+ }
+
+ public boolean isChangeInformationShowing() {
+ if (sourceEditor != null) {
+ return sourceEditor.isChangeInformationShowing();
+ }
+ return false;
+ }
+
+ public INavigationLocation createEmptyNavigationLocation() {
+ if (sourceEditor != null) {
+ return sourceEditor.createEmptyNavigationLocation();
+ }
+ return null;
+ }
+
+ public INavigationLocation createNavigationLocation() {
+ if (sourceEditor != null) {
+ return sourceEditor.createNavigationLocation();
+ }
+ return null;
+ }
+}
+
+class ResourceChangeListener implements IResourceChangeListener {
+ IEditorPart editorPart;
+
+ Composite container;
+
+ ResourceChangeListener(IEditorPart editorPart, Composite container) {
+ this.editorPart = editorPart;
+ this.container = container;
+ IWorkspace workspace = ModelUIPlugin.getWorkspace();
+ if (workspace == null)
+ return;
+ workspace.addResourceChangeListener(this);
+ container.addDisposeListener(new DisposeListener() {
+ public void widgetDisposed(DisposeEvent e) {
+ IWorkspace workspace = ModelUIPlugin.getWorkspace();
+ if (workspace == null)
+ return;
+ workspace
+ .removeResourceChangeListener(ResourceChangeListener.this);
+ }
+ });
+ }
+
+ public void resourceChanged(IResourceChangeEvent event) {
+ IEditorInput ei = editorPart.getEditorInput();
+ if (!(ei instanceof IFileEditorInput))
+ return;
+ IFileEditorInput fi = (IFileEditorInput) ei;
+ IFile f = fi.getFile();
+ if (f == null)
+ return;
+ IPath path = getPathChange(event, f);
+ if (path == null) {
+ if (f != null && !f.exists())
+ closeEditor();
+ return;
+ }
+ f = ModelPlugin.getWorkspace().getRoot().getFile(path);
+ XModelObject p = f == null ? null : EclipseResourceUtil
+ .getObjectByResource(f.getParent());
+ if (p instanceof FolderImpl) {
+ ((FolderImpl) p).update();
+ }
+ XModelObject o = EclipseResourceUtil.getObjectByResource(f);
+ if (f != null && f.exists() && o != null) {
+ if (editorPart instanceof JSPMultiPageEditor) {
+ JSPMultiPageEditor e = (JSPMultiPageEditor) editorPart;
+ if (ei instanceof XModelObjectEditorInput) {
+ IEditorInput e2 = XModelObjectEditorInput.createInstance(o);
+ e.setInput(e2);
+ e.updateTitle();
+ if (e.sourceEditor instanceof AbstractTextEditor) {
+ if (e.sourceEditor != null
+ && e.sourceEditor.getEditorInput() != e
+ .getEditorInput()) {
+ try {
+ ((AbstractTextEditor) e.sourceEditor)
+ .setInput(e2);
+ } catch (Exception exc) {
+ JspEditorPlugin.getPluginLog().logError(exc);
+ }
+ }
+ ((XModelObjectEditorInput) ei).synchronize();
+ }
+ }
+ }
+ }
+ if (f == null || f.exists())
+ return;
+ closeEditor();
+ }
+
+ private void closeEditor() {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ editorPart.getSite().getPage().closeEditor(editorPart, false);
+ }
+ });
+ }
+
+ private IPath getPathChange(IResourceChangeEvent event, IFile f) {
+ return getPathChange(event.getDelta(), f.getFullPath());
+ }
+
+ private IPath getPathChange(IResourceDelta delta, IPath p) {
+ if (delta == null || delta.getFullPath() == null)
+ return null;
+ if (!delta.getFullPath().isPrefixOf(p))
+ return null;
+ if (delta != null && delta.getKind() == IResourceDelta.CHANGED) {
+ IResourceDelta[] ds = delta.getAffectedChildren();
+ if (ds == null)
+ return null;
+ if (ds.length == 2) {
+ if (ds[1].getKind() == IResourceDelta.REMOVED) {
+ IPath d = ds[1].getFullPath();
+ if (d.equals(p))
+ return ds[0].getFullPath();
+ if (d.isPrefixOf(p)) {
+ return ds[0].getFullPath().append(
+ p.removeFirstSegments(d.segmentCount()));
+ }
+ } else if (ds[0].getKind() == IResourceDelta.REMOVED) {
+ IPath d = ds[0].getFullPath();
+ if (d.equals(p))
+ return ds[1].getFullPath();
+ if (d.isPrefixOf(p)) {
+ return ds[1].getFullPath().append(
+ p.removeFirstSegments(d.segmentCount()));
+ }
+ }
+ }
+ for (int i = 0; i < ds.length; i++) {
+ IPath ps = getPathChange(ds[i], p);
+ if (ps != null)
+ return ps;
+ }
+ }
+ return null;
+ }
}
\ No newline at end of file
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorPart.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorPart.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorPart.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,328 +1,329 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.SafeRunner;
-import org.eclipse.jface.util.Assert;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CTabFolder;
-import org.eclipse.swt.custom.CTabItem;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-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.Item;
-import org.eclipse.ui.IEditorActionBarContributor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IKeyBindingService;
-import org.eclipse.ui.INestableKeyBindingService;
-import org.eclipse.ui.IPropertyListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
-import org.eclipse.ui.part.MultiPageEditorSite;
-import org.eclipse.ui.part.MultiPageSelectionProvider;
-import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
-
-/**
- *
- */
-public abstract class JSPMultiPageEditorPart extends EditorPart {
-
- private CTabFolder container;
-
- private ArrayList nestedEditors = new ArrayList(3);
-
- protected JSPMultiPageEditorPart() {
- super();
- }
-
- public int addPage(Control control) {
- createItem(control);
- return getPageCount() - 1;
- }
-
- /**
- *
- */
-
- Composite ppp = null;
-
- public int addPage(IEditorPart editor, IEditorInput input)
- throws PartInitException {
- IEditorSite site = createSite(editor);
- editor.init(site, input);
- Composite parent2;
- if (ppp != null) {
- parent2 = ppp;
- } else {
- parent2 = new Composite(getContainer(), SWT.NONE);
- ppp = parent2;
- }
- parent2.setLayout(new FillLayout());
- editor.createPartControl(parent2);
- editor.addPropertyListener(new IPropertyListener() {
- public void propertyChanged(Object source, int propertyId) {
- JSPMultiPageEditorPart.this.handlePropertyChange(propertyId);
- }
- });
- Item item = createItem(parent2);
- item.setData(editor);
- nestedEditors.add(editor);
- return getPageCount() - 1;
- }
-
- /**
- *
- * @param parent
- * @return
- */
- private CTabFolder createContainer(Composite parent) {
- final CTabFolder newContainer = new CTabFolder(parent, SWT.BOTTOM
- | SWT.FLAT);
- newContainer.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int newPageIndex = newContainer.indexOf((CTabItem) e.item);
- pageChange(newPageIndex);
- }
- });
- return newContainer;
- }
-
- /*
- *
- */
- private CTabItem createItem(Control control) {
- CTabItem item = new CTabItem(getTabFolder(), SWT.NONE);
- item.setControl(control);
- return item;
- }
-
- protected abstract void createPages();
-
- public final void createPartControl(Composite parent) {
- this.container = createContainer(parent);
- createPages();
- // set the active page (page 0 by default), unless it has already been
- // done
- if (getActivePage() == -1)
- setActivePage(0);
- }
-
- protected abstract IEditorSite createSite(IEditorPart editor);
-
- public void dispose() {
- for (int i = 0; i < nestedEditors.size(); ++i) {
- IEditorPart editor = (IEditorPart) nestedEditors.get(i);
- disposePart(editor);
- }
- nestedEditors.clear();
- }
-
- protected IEditorPart getActiveEditor() {
- int index = getActivePage();
- if (index != -1)
- return getEditor(0);
- return null;
- }
-
- protected int getActivePage() {
- CTabFolder tabFolder = getTabFolder();
- if (tabFolder != null && !tabFolder.isDisposed())
- return tabFolder.getSelectionIndex();
- return -1;
- }
-
- protected Composite getContainer() {
- return container;
- }
-
- protected Control getControl(int pageIndex) {
- return getItem(0).getControl();
- }
-
- protected IEditorPart getEditor(int pageIndex) {
- Item item = getItem(pageIndex);
- if (item != null) {
- Object data = item.getData();
- if (data instanceof IEditorPart) {
- return (IEditorPart) data;
- }
- }
- return null;
- }
-
- private CTabItem getItem(int pageIndex) {
- return getTabFolder().getItem(pageIndex);
- }
-
- protected int getPageCount() {
- CTabFolder folder = getTabFolder();
- // May not have been created yet, or may have been disposed.
- if (folder != null && !folder.isDisposed())
- return folder.getItemCount();
- return 0;
- }
-
- protected Image getPageImage(int pageIndex) {
- return getItem(pageIndex).getImage();
- }
-
- protected String getPageText(int pageIndex) {
- return getItem(pageIndex).getText();
- }
-
- protected CTabFolder getTabFolder() {
- return container;
- }
-
- protected void handlePropertyChange(int propertyId) {
- firePropertyChange(propertyId);
- }
-
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- setSite(site);
- setInput(XModelObjectEditorInput.checkInput(input));
- site.setSelectionProvider(new JSPMultiPageSelectionProvider(this));
- }
-
- public boolean isDirty() {
- // use nestedEditors to avoid SWT requests; see bug 12996
- for (Iterator i = nestedEditors.iterator(); i.hasNext();) {
- IEditorPart editor = (IEditorPart) i.next();
- if (editor.isDirty()) {
- return true;
- }
- }
- return false;
- }
-
- protected void pageChange(int newPageIndex) {
- Control control = getControl(newPageIndex);
- if (control != null) {
- control.setVisible(true);
- }
-
- setFocus();
- IEditorPart activeEditor = getEditor(newPageIndex);
- IEditorActionBarContributor contributor = getEditorSite()
- .getActionBarContributor();
- if (contributor != null
- && contributor instanceof MultiPageEditorActionBarContributor) {
- ((MultiPageEditorActionBarContributor) contributor)
- .setActivePage(activeEditor);
- }
- if (activeEditor != null) {
- ISelectionProvider selectionProvider = activeEditor.getSite()
- .getSelectionProvider();
- if (selectionProvider != null) {
- SelectionChangedEvent event = new SelectionChangedEvent(
- selectionProvider, selectionProvider.getSelection());
- ((MultiPageSelectionProvider) getSite().getSelectionProvider())
- .fireSelectionChanged(event);
- }
- }
- }
-
- private void disposePart(final IWorkbenchPart part) {
- SafeRunner.run(new SafeRunnable() {
- public void run() {
- if (part.getSite() instanceof MultiPageEditorSite) {
- MultiPageEditorSite partSite = (MultiPageEditorSite) part
- .getSite();
- partSite.dispose();
- }
- part.dispose();
- }
-
- public void handleException(Throwable e) {
- }
- });
- }
-
- public void removePage(int pageIndex) {
- Assert.isTrue(pageIndex >= 0 && pageIndex < getPageCount());
- IEditorPart editor = getEditor(pageIndex);
- getItem(pageIndex).dispose();
- if (editor != null) {
- nestedEditors.remove(editor);
- disposePart(editor);
- }
- }
-
- protected void setActivePage(int pageIndex) {
- Assert.isTrue(pageIndex >= 0 && pageIndex < getPageCount());
- getTabFolder().setSelection(pageIndex);
- }
-
- protected void setControl(int pageIndex, Control control) {
- getItem(pageIndex).setControl(control);
- }
-
- public void setFocus() {
- setFocus(getActivePage());
- }
-
- private void setFocus(int pageIndex) {
- final IKeyBindingService service = getSite().getKeyBindingService();
- if (pageIndex < 0 || pageIndex >= getPageCount()) {
- if (service instanceof INestableKeyBindingService) {
- final INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
- nestableService.activateKeyBindingService(null);
- }
- return;
- }
-
- IEditorPart editor = getEditor(pageIndex);
- if (editor != null) {
- editor.setFocus();
- if (service instanceof INestableKeyBindingService) {
- INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
- if (editor != null) {
- nestableService.activateKeyBindingService(editor
- .getEditorSite());
- } else {
- nestableService.activateKeyBindingService(null);
- }
- }
- } else {
- if (service instanceof INestableKeyBindingService) {
- INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
- nestableService.activateKeyBindingService(null);
- }
-
- Control control = getControl(pageIndex);
- if (control != null) {
- control.setFocus();
- }
- }
- }
-
- protected void setPageImage(int pageIndex, Image image) {
- getItem(pageIndex).setImage(image);
- }
-
- protected void setPageText(int pageIndex, String text) {
- getItem(pageIndex).setText(text);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.eclipse.core.runtime.SafeRunner;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.util.SafeRunnable;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabItem;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+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.Item;
+import org.eclipse.ui.IEditorActionBarContributor;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.IKeyBindingService;
+import org.eclipse.ui.INestableKeyBindingService;
+import org.eclipse.ui.IPropertyListener;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.EditorPart;
+import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
+import org.eclipse.ui.part.MultiPageEditorSite;
+import org.eclipse.ui.part.MultiPageSelectionProvider;
+import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
+
+/**
+ *
+ */
+public abstract class JSPMultiPageEditorPart extends EditorPart {
+
+ private CTabFolder container;
+
+ private ArrayList nestedEditors = new ArrayList(3);
+
+ protected JSPMultiPageEditorPart() {
+ super();
+ }
+
+ public int addPage(Control control) {
+ createItem(control);
+ return getPageCount() - 1;
+ }
+
+ /**
+ *
+ */
+
+ Composite ppp = null;
+
+ public int addPage(IEditorPart editor, IEditorInput input)
+ throws PartInitException {
+ Composite parent2;
+ if (ppp == null) {
+ IEditorSite site = createSite(editor);
+ editor.init(site, input);
+ parent2 = new Composite(getContainer(), SWT.NONE);
+ ppp = parent2;
+ parent2.setLayout(new FillLayout());
+ editor.createPartControl(parent2);
+ editor.addPropertyListener(new IPropertyListener() {
+ public void propertyChanged(Object source, int propertyId) {
+ JSPMultiPageEditorPart.this
+ .handlePropertyChange(propertyId);
+ }
+ });
+ } else {
+ parent2 = ppp;
+ }
+ Item item = createItem(parent2);
+ item.setData(editor);
+ nestedEditors.add(editor);
+ return getPageCount() - 1;
+ }
+
+ /**
+ *
+ * @param parent
+ * @return
+ */
+ private CTabFolder createContainer(Composite parent) {
+ final CTabFolder newContainer = new CTabFolder(parent, SWT.BOTTOM
+ | SWT.FLAT);
+ newContainer.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ int newPageIndex = newContainer.indexOf((CTabItem) e.item);
+ pageChange(newPageIndex);
+ }
+ });
+ return newContainer;
+ }
+
+ /*
+ *
+ */
+ private CTabItem createItem(Control control) {
+ CTabItem item = new CTabItem(getTabFolder(), SWT.NONE);
+ item.setControl(control);
+ return item;
+ }
+
+ protected abstract void createPages();
+
+ public final void createPartControl(Composite parent) {
+ this.container = createContainer(parent);
+ createPages();
+ // set the active page (page 0 by default), unless it has already been
+ // done
+ if (getActivePage() == -1)
+ setActivePage(0);
+ }
+
+ protected abstract IEditorSite createSite(IEditorPart editor);
+
+ public void dispose() {
+ for (int i = 0; i < nestedEditors.size(); ++i) {
+ IEditorPart editor = (IEditorPart) nestedEditors.get(i);
+ disposePart(editor);
+ }
+ nestedEditors.clear();
+ }
+
+ protected IEditorPart getActiveEditor() {
+ int index = getActivePage();
+ if (index != -1)
+ return getEditor(0);
+ return null;
+ }
+
+ protected int getActivePage() {
+ CTabFolder tabFolder = getTabFolder();
+ if (tabFolder != null && !tabFolder.isDisposed())
+ return tabFolder.getSelectionIndex();
+ return -1;
+ }
+
+ protected Composite getContainer() {
+ return container;
+ }
+
+ protected Control getControl(int pageIndex) {
+ return getItem(0).getControl();
+ }
+
+ protected IEditorPart getEditor(int pageIndex) {
+ Item item = getItem(pageIndex);
+ if (item != null) {
+ Object data = item.getData();
+ if (data instanceof IEditorPart) {
+ return (IEditorPart) data;
+ }
+ }
+ return null;
+ }
+
+ private CTabItem getItem(int pageIndex) {
+ return getTabFolder().getItem(pageIndex);
+ }
+
+ protected int getPageCount() {
+ CTabFolder folder = getTabFolder();
+ // May not have been created yet, or may have been disposed.
+ if (folder != null && !folder.isDisposed())
+ return folder.getItemCount();
+ return 0;
+ }
+
+ protected Image getPageImage(int pageIndex) {
+ return getItem(pageIndex).getImage();
+ }
+
+ protected String getPageText(int pageIndex) {
+ return getItem(pageIndex).getText();
+ }
+
+ protected CTabFolder getTabFolder() {
+ return container;
+ }
+
+ protected void handlePropertyChange(int propertyId) {
+ firePropertyChange(propertyId);
+ }
+
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ setSite(site);
+ setInput(XModelObjectEditorInput.checkInput(input));
+ site.setSelectionProvider(new JSPMultiPageSelectionProvider(this));
+ }
+
+ public boolean isDirty() {
+ // use nestedEditors to avoid SWT requests; see bug 12996
+ for (Iterator i = nestedEditors.iterator(); i.hasNext();) {
+ IEditorPart editor = (IEditorPart) i.next();
+ if (editor.isDirty()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected void pageChange(int newPageIndex) {
+ Control control = getControl(newPageIndex);
+ if (control != null) {
+ control.setVisible(true);
+ }
+
+ setFocus();
+ IEditorPart activeEditor = getEditor(newPageIndex);
+ IEditorActionBarContributor contributor = getEditorSite()
+ .getActionBarContributor();
+ if (contributor != null
+ && contributor instanceof MultiPageEditorActionBarContributor) {
+ ((MultiPageEditorActionBarContributor) contributor)
+ .setActivePage(activeEditor);
+ }
+ if (activeEditor != null) {
+ ISelectionProvider selectionProvider = activeEditor.getSite()
+ .getSelectionProvider();
+ if (selectionProvider != null) {
+ SelectionChangedEvent event = new SelectionChangedEvent(
+ selectionProvider, selectionProvider.getSelection());
+ ((MultiPageSelectionProvider) getSite().getSelectionProvider())
+ .fireSelectionChanged(event);
+ }
+ }
+ }
+
+ private void disposePart(final IWorkbenchPart part) {
+ SafeRunner.run(new SafeRunnable() {
+ public void run() {
+ if (part.getSite() instanceof MultiPageEditorSite) {
+ MultiPageEditorSite partSite = (MultiPageEditorSite) part
+ .getSite();
+ partSite.dispose();
+ }
+ part.dispose();
+ }
+
+ public void handleException(Throwable e) {
+ }
+ });
+ }
+
+ public void removePage(int pageIndex) {
+ Assert.isTrue(pageIndex >= 0 && pageIndex < getPageCount());
+ IEditorPart editor = getEditor(pageIndex);
+ getItem(pageIndex).dispose();
+ if (editor != null) {
+ nestedEditors.remove(editor);
+ disposePart(editor);
+ }
+ }
+
+ protected void setActivePage(int pageIndex) {
+ Assert.isTrue(pageIndex >= 0 && pageIndex < getPageCount());
+ getTabFolder().setSelection(pageIndex);
+ }
+
+ protected void setControl(int pageIndex, Control control) {
+ getItem(pageIndex).setControl(control);
+ }
+
+ public void setFocus() {
+ setFocus(getActivePage());
+ }
+
+ private void setFocus(int pageIndex) {
+ final IKeyBindingService service = getSite().getKeyBindingService();
+ if (pageIndex < 0 || pageIndex >= getPageCount()) {
+ if (service instanceof INestableKeyBindingService) {
+ final INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
+ nestableService.activateKeyBindingService(null);
+ }
+ return;
+ }
+
+ IEditorPart editor = getEditor(pageIndex);
+ if (editor != null) {
+ editor.setFocus();
+ if (service instanceof INestableKeyBindingService) {
+ INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
+ if (editor != null) {
+ nestableService.activateKeyBindingService(editor
+ .getEditorSite());
+ } else {
+ nestableService.activateKeyBindingService(null);
+ }
+ }
+ } else {
+ if (service instanceof INestableKeyBindingService) {
+ INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
+ nestableService.activateKeyBindingService(null);
+ }
+
+ Control control = getControl(pageIndex);
+ if (control != null) {
+ control.setFocus();
+ }
+ }
+ }
+
+ protected void setPageImage(int pageIndex, Image image) {
+ getItem(pageIndex).setImage(image);
+ }
+
+ protected void setPageText(int pageIndex, String text) {
+ getItem(pageIndex).setText(text);
+ }
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorSite.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorSite.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPMultiPageEditorSite.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,216 +1,222 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-import java.util.ArrayList;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.util.Assert;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jst.jsp.core.internal.provisional.contenttype.ContentTypeIdForJSP;
-
-import org.eclipse.ui.*;
-import org.eclipse.ui.internal.PopupMenuExtender;
-import org.eclipse.ui.internal.WorkbenchPlugin;
-
-/**
- *
- * @author eskimo(dgolovin(a)exadel.com)
- *
- */
-public abstract class JSPMultiPageEditorSite implements IEditorSite {
-
- private IEditorPart fEditorPart;
-
- private JSPMultiPageEditorPart fEditor;
-
- private ISelectionChangedListener fSelChangeListener = null;
-
- private IKeyBindingService fParentService = null;
-
- private IKeyBindingService fService = null;
-
- private ArrayList fMenuExts;
-
- public JSPMultiPageEditorSite(JSPMultiPageEditorPart multiPageEditor,
- IEditorPart editor) {
- Assert.isNotNull(multiPageEditor);
- Assert.isNotNull(editor);
- this.fEditor = multiPageEditor;
- this.fEditorPart = editor;
- }
-
- public void dispose() {
- if (fMenuExts != null) {
- for (int i = 0; i < fMenuExts.size(); i++) {
- ((PopupMenuExtender) fMenuExts.get(i)).dispose();
- }
- fMenuExts = null;
- }
-
- if (fService != null) {
- IKeyBindingService parentService = getEditor().getSite()
- .getKeyBindingService();
- if (parentService instanceof INestableKeyBindingService) {
- INestableKeyBindingService nestableParent = (INestableKeyBindingService) parentService;
- nestableParent.removeKeyBindingService(this);
- }
- fService = null;
- }
- }
-
- public IEditorActionBarContributor getActionBarContributor() {
- return null;
- }
-
- public IActionBars getActionBars() {
- return fEditor.getEditorSite().getActionBars();
- }
-
- public ILabelDecorator getDecoratorManager() {
- return getWorkbenchWindow().getWorkbench().getDecoratorManager()
- .getLabelDecorator();
- }
-
- public IEditorPart getEditor() {
- return fEditorPart;
- }
-
- public String getId() {
- return ContentTypeIdForJSP.ContentTypeID_JSP + ".source"; //$NON-NLS-1$;
- }
-
- public IKeyBindingService getKeyBindingService() {
- if (fService == null) {
- fService = getMultiPageEditor().getEditorSite()
- .getKeyBindingService();
- fParentService = fService;
- if (fService instanceof INestableKeyBindingService) {
- INestableKeyBindingService nestableService = (INestableKeyBindingService) fService;
- fService = nestableService.getKeyBindingService(this);
-
- } else {
- WorkbenchPlugin
- .log("MultiPageEditorSite.getKeyBindingService() Parent key binding fService was not an instance of INestableKeyBindingService. It was an instance of " + fService.getClass().getName() + " instead."); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- return fParentService;
- }
-
- public JSPMultiPageEditorPart getMultiPageEditor() {
- return fEditor;
- }
-
- public IWorkbenchPage getPage() {
- return getMultiPageEditor().getSite().getPage();
- }
-
- public String getPluginId() {
- return "";
- }
-
- public String getRegisteredName() {
- return "";
- }
-
- protected ISelectionChangedListener getSelectionChangedListener() {
- if (fSelChangeListener == null) {
- fSelChangeListener = new ISelectionChangedListener() {
- public void selectionChanged(SelectionChangedEvent event) {
- JSPMultiPageEditorSite.this.handleSelectionChanged(event);
- }
- };
- }
- return fSelChangeListener;
- }
-
- public Shell getShell() {
- return getMultiPageEditor().getSite().getShell();
- }
-
- public IWorkbenchWindow getWorkbenchWindow() {
- return getMultiPageEditor().getSite().getWorkbenchWindow();
- }
-
- protected void handleSelectionChanged(SelectionChangedEvent event) {
- ISelectionProvider parentProvider = getMultiPageEditor().getSite()
- .getSelectionProvider();
- if (parentProvider instanceof JSPMultiPageSelectionProvider) {
- SelectionChangedEvent newEvent = new SelectionChangedEvent(
- parentProvider, event.getSelection());
- ((JSPMultiPageSelectionProvider) parentProvider)
- .fireSelectionChanged(newEvent);
- }
- }
-
- public void registerContextMenu(String menuID, MenuManager menuMgr,
- ISelectionProvider selProvider) {
- if (fMenuExts == null) {
- fMenuExts = new ArrayList(1);
- }
- if (findMenuExtender(menuMgr, selProvider) == null) {
- PopupMenuExtender extender = new PopupMenuExtender(menuID, menuMgr,
- selProvider, fEditorPart);
- fMenuExts.add(extender);
- }
- }
-
- private PopupMenuExtender findMenuExtender(MenuManager menuMgr,
- ISelectionProvider selProvider) {
- for (int i = 0; fMenuExts != null && i < fMenuExts.size(); i++) {
- PopupMenuExtender extender = (PopupMenuExtender) fMenuExts
- .get(i);
- if (extender.matches(menuMgr, selProvider, fEditorPart))
- return extender;
- }
- return null;
- }
-
- public void registerContextMenu(MenuManager menuManager,
- ISelectionProvider selProvider) {
- getMultiPageEditor().getSite().registerContextMenu(menuManager,
- selProvider);
- }
-
- public void progressEnd(Job job) {
- }
-
- public void progressStart(Job job) {
- }
-
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- public IWorkbenchPart getPart() {
- return null;
- }
-
- public final void registerContextMenu(final MenuManager menuManager,
- final ISelectionProvider selectionProvider,
- final boolean includeEditorInput) {
- registerContextMenu(getId(), menuManager, selectionProvider,
- includeEditorInput);
- }
-
- public final void registerContextMenu(final String menuId,
- final MenuManager menuManager,
- final ISelectionProvider selectionProvider,
- final boolean includeEditorInput) {
- if (fMenuExts == null) {
- fMenuExts = new ArrayList(1);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+import java.util.ArrayList;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jst.jsp.core.internal.provisional.contenttype.ContentTypeIdForJSP;
+
+import org.eclipse.ui.*;
+import org.eclipse.ui.internal.PopupMenuExtender;
+import org.eclipse.ui.internal.WorkbenchPlugin;
+
+/**
+ *
+ * @author eskimo(dgolovin(a)exadel.com)
+ *
+ */
+public abstract class JSPMultiPageEditorSite implements IEditorSite {
+
+ private IEditorPart fEditorPart;
+
+ private JSPMultiPageEditorPart fEditor;
+
+ private ISelectionChangedListener fSelChangeListener = null;
+
+ private IKeyBindingService fParentService = null;
+
+ private IKeyBindingService fService = null;
+
+ private ArrayList fMenuExts;
+
+ public JSPMultiPageEditorSite(JSPMultiPageEditorPart multiPageEditor,
+ IEditorPart editor) {
+ Assert.isNotNull(multiPageEditor);
+ Assert.isNotNull(editor);
+ this.fEditor = multiPageEditor;
+ this.fEditorPart = editor;
+ }
+
+ public void dispose() {
+ if (fMenuExts != null) {
+ for (int i = 0; i < fMenuExts.size(); i++) {
+ ((PopupMenuExtender) fMenuExts.get(i)).dispose();
+ }
+ fMenuExts = null;
+ }
+
+ if (fService != null) {
+ IKeyBindingService parentService = getEditor().getSite()
+ .getKeyBindingService();
+ if (parentService instanceof INestableKeyBindingService) {
+ INestableKeyBindingService nestableParent = (INestableKeyBindingService) parentService;
+ nestableParent.removeKeyBindingService(this);
+ }
+ fService = null;
+ }
+ fEditor = null;
+ fEditorPart = null;
+ if (fSelChangeListener != null) {
+ getSelectionProvider().removeSelectionChangedListener(fSelChangeListener);
+ fSelChangeListener = null;
+ }
+ }
+
+ public IEditorActionBarContributor getActionBarContributor() {
+ return null;
+ }
+
+ public IActionBars getActionBars() {
+ return fEditor.getEditorSite().getActionBars();
+ }
+
+ public ILabelDecorator getDecoratorManager() {
+ return getWorkbenchWindow().getWorkbench().getDecoratorManager()
+ .getLabelDecorator();
+ }
+
+ public IEditorPart getEditor() {
+ return fEditorPart;
+ }
+
+ public String getId() {
+ return ContentTypeIdForJSP.ContentTypeID_JSP + ".source"; //$NON-NLS-1$;
+ }
+
+ public IKeyBindingService getKeyBindingService() {
+ if (fService == null) {
+ fService = getMultiPageEditor().getEditorSite()
+ .getKeyBindingService();
+ fParentService = fService;
+ if (fService instanceof INestableKeyBindingService) {
+ INestableKeyBindingService nestableService = (INestableKeyBindingService) fService;
+ fService = nestableService.getKeyBindingService(this);
+
+ } else {
+ WorkbenchPlugin
+ .log("MultiPageEditorSite.getKeyBindingService() Parent key binding fService was not an instance of INestableKeyBindingService. It was an instance of " + fService.getClass().getName() + " instead."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ return fParentService;
+ }
+
+ public JSPMultiPageEditorPart getMultiPageEditor() {
+ return fEditor;
+ }
+
+ public IWorkbenchPage getPage() {
+ return getMultiPageEditor().getSite().getPage();
+ }
+
+ public String getPluginId() {
+ return "";
+ }
+
+ public String getRegisteredName() {
+ return "";
+ }
+
+ protected ISelectionChangedListener getSelectionChangedListener() {
+ if (fSelChangeListener == null) {
+ fSelChangeListener = new ISelectionChangedListener() {
+ public void selectionChanged(SelectionChangedEvent event) {
+ JSPMultiPageEditorSite.this.handleSelectionChanged(event);
+ }
+ };
+ }
+ return fSelChangeListener;
+ }
+
+ public Shell getShell() {
+ return getMultiPageEditor().getSite().getShell();
+ }
+
+ public IWorkbenchWindow getWorkbenchWindow() {
+ return getMultiPageEditor().getSite().getWorkbenchWindow();
+ }
+
+ protected void handleSelectionChanged(SelectionChangedEvent event) {
+ ISelectionProvider parentProvider = getMultiPageEditor().getSite()
+ .getSelectionProvider();
+ if (parentProvider instanceof JSPMultiPageSelectionProvider) {
+ SelectionChangedEvent newEvent = new SelectionChangedEvent(
+ parentProvider, event.getSelection());
+ ((JSPMultiPageSelectionProvider) parentProvider)
+ .fireSelectionChanged(newEvent);
+ }
+ }
+
+ public void registerContextMenu(String menuID, MenuManager menuMgr,
+ ISelectionProvider selProvider) {
+ if (fMenuExts == null) {
+ fMenuExts = new ArrayList(1);
+ }
+ if (findMenuExtender(menuMgr, selProvider) == null) {
+ PopupMenuExtender extender = new PopupMenuExtender(menuID, menuMgr,
+ selProvider, fEditorPart);
+ fMenuExts.add(extender);
+ }
+ }
+
+ private PopupMenuExtender findMenuExtender(MenuManager menuMgr,
+ ISelectionProvider selProvider) {
+ for (int i = 0; fMenuExts != null && i < fMenuExts.size(); i++) {
+ PopupMenuExtender extender = (PopupMenuExtender) fMenuExts
+ .get(i);
+ if (extender.matches(menuMgr, selProvider, fEditorPart))
+ return extender;
+ }
+ return null;
+ }
+
+ public void registerContextMenu(MenuManager menuManager,
+ ISelectionProvider selProvider) {
+ getMultiPageEditor().getSite().registerContextMenu(menuManager,
+ selProvider);
+ }
+
+ public void progressEnd(Job job) {
+ }
+
+ public void progressStart(Job job) {
+ }
+
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
+
+ public IWorkbenchPart getPart() {
+ return null;
+ }
+
+ public final void registerContextMenu(final MenuManager menuManager,
+ final ISelectionProvider selectionProvider,
+ final boolean includeEditorInput) {
+ registerContextMenu(getId(), menuManager, selectionProvider,
+ includeEditorInput);
+ }
+
+ public final void registerContextMenu(final String menuId,
+ final MenuManager menuManager,
+ final ISelectionProvider selectionProvider,
+ final boolean includeEditorInput) {
+ if (fMenuExts == null) {
+ fMenuExts = new ArrayList(1);
+ }
+ }
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditor.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditor.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditor.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,1133 +1,1158 @@
-/*******************************************************************************
- * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
- * Distributed under license by Red Hat, Inc. All rights reserved.
- * This program is 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:
- * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
- ******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Properties;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextListener;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.TextEvent;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.source.IAnnotationModel;
-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;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jst.jsp.ui.StructuredTextViewerConfigurationJSP;
-import org.eclipse.jst.jsp.ui.internal.JSPUIPlugin;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.DropTargetListener;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.HTMLTransfer;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.editors.text.ILocationProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.ui.views.properties.IPropertySheetPage;
-import org.eclipse.ui.views.properties.PropertySheetPage;
-import org.eclipse.ui.views.properties.PropertySheetSorter;
-import org.eclipse.wst.html.ui.StructuredTextViewerConfigurationHTML;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
-import org.eclipse.wst.sse.ui.internal.IModelProvider;
-import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
-import org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants;
-import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage;
-import org.eclipse.wst.sse.ui.internal.properties.ConfigurablePropertySheetPage;
-import org.eclipse.wst.sse.ui.internal.provisional.extensions.ConfigurationPointCalculator;
-import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration;
-import org.eclipse.wst.xml.core.internal.document.AttrImpl;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
-import org.jboss.tools.common.meta.action.XActionInvoker;
-import org.jboss.tools.common.model.XModelBuffer;
-import org.jboss.tools.common.model.XModelObject;
-import org.jboss.tools.common.model.XModelTransferBuffer;
-import org.jboss.tools.common.model.filesystems.impl.FileAnyImpl;
-import org.jboss.tools.common.model.filesystems.impl.FolderImpl;
-import org.jboss.tools.common.model.ui.ModelUIPlugin;
-import org.jboss.tools.common.model.ui.dnd.ModelTransfer;
-import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
-import org.jboss.tools.common.model.ui.editors.dnd.DropCommandFactory;
-import org.jboss.tools.common.model.ui.editors.dnd.DropData;
-import org.jboss.tools.common.model.ui.editors.dnd.IDropCommand;
-import org.jboss.tools.common.model.ui.editors.dnd.JSPTagProposalFactory;
-import org.jboss.tools.common.model.ui.editors.dnd.context.DropContext;
-import org.jboss.tools.common.model.ui.editors.dnd.context.InnerDragBuffer;
-import org.jboss.tools.common.model.ui.texteditors.TextMerge;
-import org.jboss.tools.common.model.ui.texteditors.dnd.TextEditorDrop;
-import org.jboss.tools.common.model.ui.texteditors.dnd.TextEditorDropProvider;
-import org.jboss.tools.common.model.ui.views.palette.IIgnoreSelection;
-import org.jboss.tools.common.model.ui.views.palette.PaletteInsertHelper;
-import org.jboss.tools.common.model.util.XModelObjectLoaderUtil;
-import org.jboss.tools.common.text.xml.IOccurrencePreferenceProvider;
-import org.jboss.tools.common.text.xml.XmlEditorPlugin;
-import org.jboss.tools.common.text.xml.ui.FreeCaretStyledText;
-import org.jboss.tools.jst.jsp.ExtendedStructuredTextViewerConfigurationHTML;
-import org.jboss.tools.jst.jsp.ExtendedStructuredTextViewerConfigurationJSP;
-import org.jboss.tools.jst.jsp.JspEditorPlugin;
-import org.jboss.tools.jst.jsp.editor.IJSPTextEditor;
-import org.jboss.tools.jst.jsp.editor.ITextFormatter;
-import org.jboss.tools.jst.jsp.editor.IVisualController;
-import org.jboss.tools.jst.jsp.outline.JSPContentOutlineConfiguration;
-import org.jboss.tools.jst.jsp.outline.JSPPropertySheetConfiguration;
-import org.jboss.tools.jst.jsp.preferences.VpePreference;
-import org.jboss.tools.jst.jsp.support.kb.WTPTextJspKbConnector;
-import org.jboss.tools.jst.jsp.text.xpl.IStructuredTextOccurrenceStructureProvider;
-import org.jboss.tools.jst.jsp.text.xpl.StructuredTextOccurrenceStructureProviderRegistry;
-import org.jboss.tools.jst.jsp.ui.action.ExtendedFormatAction;
-import org.jboss.tools.jst.jsp.ui.action.IExtendedAction;
-import org.jboss.tools.jst.web.tld.VpeTaglibManager;
-import org.jboss.tools.jst.web.tld.VpeTaglibManagerProvider;
-import org.w3c.dom.DocumentType;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-/**
- * @author Jeremy
- *
- */
-public class JSPTextEditor extends StructuredTextEditor implements
- ITextListener, IJSPTextEditor, ITextFormatter,
- IOccurrencePreferenceProvider {
- private IStructuredTextOccurrenceStructureProvider fOccurrenceModelUpdater;
-
- TextEditorDrop dnd = new TextEditorDrop();
-
- JSPMultiPageEditor parentEditor;
-
- long timeStamp = -1;
-
- long savedTimeStamp = -1;
-
- IVisualController vpeController;
-
- public JSPTextEditor(JSPMultiPageEditor parentEditor) {
- JspEditorPlugin.getDefault().initDefaultPluginPreferences();
- dnd.setTextEditorDropProvider(new TextEditorDropProviderImpl());
- this.parentEditor = parentEditor;
- super
- .setSourceViewerConfiguration(new ExtendedStructuredTextViewerConfigurationJSP());
- }
-
- protected void setSourceViewerConfiguration(SourceViewerConfiguration config) {
- if (config instanceof StructuredTextViewerConfigurationJSP) {
- if (!(config instanceof ExtendedStructuredTextViewerConfigurationJSP)) {
- config = new ExtendedStructuredTextViewerConfigurationJSP();
- }
- } else if (config instanceof StructuredTextViewerConfigurationHTML) {
- if (!(config instanceof ExtendedStructuredTextViewerConfigurationHTML)) {
- config = new ExtendedStructuredTextViewerConfigurationHTML();
- }
- } else {
- config = new ExtendedStructuredTextViewerConfigurationJSP();
- }
- super.setSourceViewerConfiguration(config);
- }
-
- protected void initializeDrop(ITextViewer textViewer) {
-
- Composite c = textViewer.getTextWidget();
- Label l = new Label(c, SWT.NONE);
- l.dispose();
- }
-
- private ConfigurableContentOutlinePage fOutlinePage = null;
-
- private OutlinePageListener fOutlinePageListener = null;
-
- private IPropertySheetPage fPropertySheetPage;
-
- public Object getAdapter(Class adapter) {
- if (ISourceViewer.class.equals(adapter)) {
- return JSPTextEditor.this.getSourceViewer();
- } else if (IContentOutlinePage.class.equals(adapter)) {
- if (fOutlinePage == null || fOutlinePage.getControl() == null
- || fOutlinePage.getControl().isDisposed()) {
- IStructuredModel internalModel = getModel();
- ContentOutlineConfiguration cfg = new JSPContentOutlineConfiguration(
- this);
- if (cfg != null) {
- ConfigurableContentOutlinePage outlinePage = new ConfigurableContentOutlinePage();
- outlinePage.setConfiguration(cfg);
- if (internalModel != null) {
- outlinePage.setInputContentTypeIdentifier(internalModel
- .getContentTypeIdentifier());
- outlinePage.setInput(internalModel);
- }
-
- if (fOutlinePageListener == null) {
- fOutlinePageListener = new OutlinePageListener();
- }
-
- outlinePage
- .addSelectionChangedListener(fOutlinePageListener);
- outlinePage.addDoubleClickListener(fOutlinePageListener);
-
- fOutlinePage = outlinePage;
- }
- }
- return fOutlinePage;
- } else if (IPropertySheetPage.class == adapter) {
- if (fPropertySheetPage == null
- || fPropertySheetPage.getControl() == null
- || fPropertySheetPage.getControl().isDisposed()) {
- JSPPropertySheetConfiguration cfg = new JSPPropertySheetConfiguration();
- if (cfg != null) {
- ConfigurablePropertySheetPage propertySheetPage = new ConfigurablePropertySheetPage();
- propertySheetPage.setConfiguration(cfg);
- fPropertySheetPage = propertySheetPage;
- setSorter(cfg.getSorter(), propertySheetPage);
- }
- }
- return fPropertySheetPage;
- }
- return super.getAdapter(adapter);
- }
-
- private void setSorter(PropertySheetSorter sorter,
- ConfigurablePropertySheetPage sheet) {
- try {
- Method method = PropertySheetPage.class.getDeclaredMethod(
- "setSorter", new Class[] { PropertySheetSorter.class });
- method.setAccessible(true);
- method.invoke(sheet, new Object[] { sorter });
- } catch (Exception e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
- }
-
- public String getEditorId() {
- return JSPUIPlugin.ID;
- }
-
- public IStructuredTextOccurrenceStructureProvider getOccurrencePreferenceProvider() {
- return fOccurrenceModelUpdater;
- }
-
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
-
- StructuredTextOccurrenceStructureProviderRegistry registry = XmlEditorPlugin
- .getDefault().getOccurrenceStructureProviderRegistry(
- JspEditorPlugin.PLUGIN_ID);
- fOccurrenceModelUpdater = registry
- .getCurrentOccurrenceProvider(JspEditorPlugin.PLUGIN_ID);
-
- if (fOccurrenceModelUpdater != null)
- fOccurrenceModelUpdater.install(this, getTextViewer());
-
- installActivePropmtSupport();
-
- createDrop();
- setModified(false);
- getSourceViewer().removeTextListener(this);
- getSourceViewer().addTextListener(this);
-
- Object dtid = getSourceViewer().getTextWidget().getData("DropTarget");
- if (dtid != null) {
- if (dtid instanceof DropTarget) {
- DropTarget dropTarget = (DropTarget) dtid;
- dropTarget.addDropListener(new DropTargetAdapter() {
- private FreeCaretStyledText getFreeCaretControl(
- Object sourceOrTarget) {
- if (sourceOrTarget == null)
- return null;
-
- Object control = null;
-
- if (sourceOrTarget instanceof DropTarget) {
- control = ((DropTarget) sourceOrTarget)
- .getControl();
- } else if (sourceOrTarget instanceof DragSource) {
- control = ((DragSource) sourceOrTarget)
- .getControl();
- } else
- return null;
-
- if (control instanceof FreeCaretStyledText)
- return (FreeCaretStyledText) control;
- return null;
- }
-
- private int getPosition(StyledText t, int x, int y) {
- try {
- Point pp = t.toControl(x, y);
- x = pp.x;
- y = pp.y;
- int lineIndex = (t.getTopPixel() + y)
- / t.getLineHeight();
- if (lineIndex >= t.getLineCount()) {
- return t.getCharCount();
- } else {
- int c = 0;
- try {
- c = t.getOffsetAtLocation(new Point(x, y));
- if (c < 0)
- c = 0;
- } catch (Exception ex) {
- c = t.getOffsetAtLine(lineIndex + 1)
- - (t.getLineDelimiter() == null ? 0
- : t.getLineDelimiter()
- .length());
- }
- return c;
- }
- } catch (Exception e) {
- return 0;
- }
- }
-
- public void dragEnter(DropTargetEvent event) {
- getFreeCaretControl(event.widget).enableFreeCaret(true);
- }
-
- public void dragLeave(DropTargetEvent event) {
- getFreeCaretControl(event.widget).enableFreeCaret(false);
- }
-
- public void dragOperationChanged(DropTargetEvent event) {
- getFreeCaretControl(event.widget).enableFreeCaret(false);
- }
-
- public void dragOver(DropTargetEvent event) {
- FreeCaretStyledText fcst = getFreeCaretControl(event.widget);
- int pos = getPosition(fcst, event.x, event.y);
- Point p = fcst.getLocationAtOffset(pos);
- fcst.myRedraw(p.x, p.y);
- }
-
- public void drop(DropTargetEvent event) {
- getFreeCaretControl(event.widget).enableFreeCaret(false);
- }
- });
- }
- }
- }
-
- protected ISourceViewer createSourceViewer(Composite parent,
- IVerticalRuler ruler, int styles) {
- ISourceViewer sv = super.createSourceViewer(parent, ruler, styles);
- sv.getTextWidget().addFocusListener(new TextFocusListener());
- return sv;
- }
-
- protected StructuredTextViewer createStructedTextViewer(Composite parent,
- IVerticalRuler verticalRuler, int styles) {
- return new JSPStructuredTextViewer(parent, verticalRuler,
- getOverviewRuler(), isOverviewRulerVisible(), styles,
- parentEditor, this);
- }
-
- class TextFocusListener extends FocusAdapter {
- public void focusLost(FocusEvent e) {
- if (JSPTextEditor.super.isDirty()) {
- Display.getDefault().syncExec(new Runnable() {
- public void run() {
- try {
- Thread.sleep(200);
- } catch (InterruptedException exc) {
- JspEditorPlugin.getPluginLog().logError(exc);
- }
- save();
- }
- });
- }
- }
- }
-
- public void save() {
- if (!lock && isModified()) {
- lock = true;
- try {
- FileAnyImpl f = (FileAnyImpl) getModelObject();
- if (f != null)
- f.edit(getSourceViewer().getDocument().get());
- } catch (Exception e) {
- JspEditorPlugin.getPluginLog().logError(e);
- } finally {
- setModified(false);
- lock = false;
- }
- }
- }
-
- boolean modified = false;
-
- public void setModified(boolean set) {
- if (this.modified != set) {
- this.modified = set;
- if (set) {
- XModelObject o = getModelObject();
- if (o != null)
- o.setModified(true);
- }
- super.firePropertyChange(IEditorPart.PROP_DIRTY);
- }
- }
-
- public void updateModification() {
- XModelObject object = getModelObject();
- if (object != null && !object.isModified() && isModified()) {
- setModified(false);
- } else {
- firePropertyChange(ITextEditor.PROP_DIRTY);
- }
- }
-
- public boolean isModified() {
- return modified;
- }
-
- protected void doSetInput(IEditorInput input) throws CoreException {
- super.doSetInput(XModelObjectEditorInput.checkInput(input));
- if (getSourceViewer() != null
- && getSourceViewer().getDocument() != null) {
- getSourceViewer().removeTextListener(this);
- getSourceViewer().addTextListener(this);
- }
- if (listener != null)
- listener.dispose();
- listener = null;
- XModelObject o = getModelObject();
- if (o instanceof FileAnyImpl) {
- listener = new BodyListenerImpl((FileAnyImpl) o);
- }
- }
-
- boolean lock = false;
-
- public boolean isDirty() {
- if (getEditorInput() instanceof IModelObjectEditorInput) {
- XModelObject o = getModelObject();
- if (o != null && o.isModified())
- return true;
- else {
- return isModified();
- }
- } else {
- return super.isDirty();
- }
- }
-
- public void doSave(IProgressMonitor monitor) {
- XModelObject o = getModelObject();
- super.doSave(monitor);
- if (o != null && (monitor == null || !monitor.isCanceled())) {
- if (o != null)
- save();
- if (getEditorInput() instanceof ILocationProvider) {
- XModelObject p = o.getParent();
- if (p instanceof FolderImpl) {
- ((FolderImpl) p).saveChild(o);
- }
- } else {
- o.setModified(false);
- XModelObjectLoaderUtil.updateModifiedOnSave(o);
- }
- super.firePropertyChange(IEditorPart.PROP_DIRTY);
- }
- }
-
- public void firePropertyChangeDirty() {
- super.firePropertyChange(IEditorPart.PROP_DIRTY);
- }
-
- public XModelObject getModelObject() {
- if (getEditorInput() instanceof IModelObjectEditorInput) {
- return ((IModelObjectEditorInput) getEditorInput())
- .getXModelObject();
- }
- return null;
- }
-
- class TextEditorDropProviderImpl implements TextEditorDropProvider {
-
- public ISourceViewer getSourceViewer() {
- return JSPTextEditor.this.getSourceViewer();
- }
-
- public XModelObject getModelObject() {
- return JSPTextEditor.this.getModelObject();
- }
-
- public void insert(Properties p) {
- PaletteInsertHelper.insertIntoEditor(getSourceViewer(), p);
- }
-
- }
-
- public void textChanged(TextEvent event) {
- if (event.getDocumentEvent() != null) {
- setModified(true);
- }
- }
-
- public void doRevertToSaved() {
- save();
- XModelObject o = getModelObject();
- if (o == null) {
- super.doRevertToSaved();
- return;
- }
- Properties p = new Properties();
- XActionInvoker.invoke("DiscardActions.Discard", o, p);
- if (!"true".equals(p.getProperty("done")))
- return;
- super.doRevertToSaved();
- if (o.isModified())
- o.setModified(false);
- modified = false;
- firePropertyChange(IEditorPart.PROP_DIRTY);
- updatePartControl(getEditorInput());
- }
-
- public IAnnotationModel getAnnotationModel() {
- return getSourceViewer().getAnnotationModel();
- }
-
- private WTPTextJspKbConnector wtpTextJspKbConnector;
-
- private void installActivePropmtSupport() {
- try {
- IDocument document = getTextViewer().getDocument();
- IStructuredModel model = null;
- if (getDocumentProvider() instanceof IModelProvider) {
- model = ((IModelProvider) getDocumentProvider())
- .getModel(getEditorInput());
- } else {
- if (document instanceof IStructuredDocument) {
- model = getModel();
- }
- }
- if (wtpTextJspKbConnector == null
- && model != null
- && (getContentType().toLowerCase().indexOf("jsp") != -1 || getContentType()
- .toLowerCase().indexOf("html") != -1)) {
- wtpTextJspKbConnector = new WTPTextJspKbConnector(
- getEditorInput(), document, model);
- wtpTextJspKbConnector.setTaglibManagerProvider(parentEditor);
- }
- } catch (Exception x) {
- JspEditorPlugin.getPluginLog().logError("Error while installing active prpmpting support", x);
- }
- }
-
- private String getContentType() {
- String type = null;
- try {
- type = getModel().getContentTypeIdentifier();
- } finally {
- if (type == null)
- type = "";
- }
- return type;
- }
-
- public WTPTextJspKbConnector getWTPTextJspKbConnector() {
- return wtpTextJspKbConnector;
- }
-
- public static class JSPStructuredTextViewer extends StructuredTextViewer
- implements VpeTaglibManagerProvider, IIgnoreSelection {
-
- boolean insertFromPallete = false;
-
- private VpeTaglibManagerProvider provider;
-
- private JSPTextEditor editor;
-
- private boolean ignore = false;
-
- public JSPStructuredTextViewer(Composite parent,
- IVerticalRuler verticalRuler, int styles) {
- super(parent, verticalRuler, null, false, styles);
- }
-
- public JSPStructuredTextViewer(Composite parent,
- IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
- boolean showAnnotationsOverview, int styles,
- VpeTaglibManagerProvider provider, JSPTextEditor editor) {
- super(parent, verticalRuler, overviewRuler,
- showAnnotationsOverview, styles);
- this.provider = provider;
- this.editor = editor;
- }
-
- protected StyledText createTextWidget(Composite parent, int styles) {
- return new FreeCaretStyledText(parent, styles);
- }
-
- public VpeTaglibManager getTaglibManager() {
- if (provider != null) {
- return provider.getTaglibManager();
- }
- return null;
- }
-
- public boolean doesIgnore() {
- return ignore;
- }
-
- public void setIgnore(boolean ignore) {
- this.ignore = ignore;
- }
-
- public void doOperation(int operation) {
- if (operation == UNDO || operation == REDO
- || operation == FORMAT_DOCUMENT
- || operation == FORMAT_ACTIVE_ELEMENTS) {
- if (editor.getVPEController() != null) {
- editor.getVPEController().preLongOperation();
- }
- }
-
- super.doOperation(operation);
-
- if (operation == UNDO || operation == REDO
- || operation == FORMAT_DOCUMENT
- || operation == FORMAT_ACTIVE_ELEMENTS) {
- if (editor.getVPEController() != null) {
- editor.getVPEController().postLongOperation();
- }
- }
- }
- }
-
- public JSPMultiPageEditor getParentEditor() {
- return parentEditor;
- }
-
- public void setVPEController(IVisualController c) {
- vpeController = c;
- }
-
- public IVisualController getVPEController() {
- return vpeController;
- }
-
- public void runDropCommand(final String flavor, final String data) {
- XModelBuffer b = XModelTransferBuffer.getInstance().getBuffer();
- final XModelObject o = b == null ? null : b.source();
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- if (parentEditor.getVisualEditor().getController() != null) {
- if(o != null && !XModelTransferBuffer.getInstance().isEnabled()) {
- XModelTransferBuffer.getInstance().enable();
- XModelTransferBuffer.getInstance().getBuffer().addSource(o);
- }
- try {
- DropData dropData = new DropData(flavor,
- data,
- parentEditor.getVisualEditor().getController()
- .getPageContext(),
- getEditorInput(), getSourceViewer(),
- getSelectionProvider());
- dropData.setAttributeName(dropContext.getAttributeName());
- IDropCommand dropCommand = DropCommandFactory.getInstance().getDropCommand(flavor, JSPTagProposalFactory.getInstance());
-
- boolean promptAttributes = "yes".equals(VpePreference.ALWAYS_REQUEST_FOR_ATTRIBUTE.getValue());
- dropCommand.getDefaultModel().setPromptForTagAttributesRequired(promptAttributes);
- dropCommand.execute(dropData);
- } finally {
- XModelTransferBuffer.getInstance().disable();
- }
- }
- }
- });
- }
-
- private void createDrop() {
- DropTarget target = new DropTarget(getSourceViewer().getTextWidget(),
- DND.DROP_MOVE | DND.DROP_COPY);
- Transfer[] types = new Transfer[] { ModelTransfer.getInstance(),
- HTMLTransfer.getInstance(), TextTransfer.getInstance(),
- FileTransfer.getInstance() };
- target.setTransfer(types);
- target.addDropListener(new DTL());
- }
-
- DropContext dropContext = new DropContext();
-
- class DTL implements DropTargetListener {
- int lastpos = -1;
-
- int lastdetail = -1;
-
- public void dragEnter(DropTargetEvent event) {
- lastpos = -1;
- }
-
- public void dragLeave(DropTargetEvent event) {
- lastpos = -1;
- }
-
- public void dragOperationChanged(DropTargetEvent event) {
- }
-
- public void dragOver(DropTargetEvent event) {
- if (!isEditable()
- || (getModelObject() != null && !getModelObject()
- .isObjectEditable())) {
- event.detail = DND.DROP_NONE;
- return;
- }
- dropContext.setDropTargetEvent(event);
- if (dropContext.getFlavor() == null) {
- event.detail = DND.DROP_NONE;
- return;
- }
- // Drop from VPE to Source is forbidden
- if (dropContext.getFlavor().equals("text/html")) {
- if (InnerDragBuffer.object != null) {
- event.detail = DND.DROP_NONE;
- }
- return;
- }
- int pos = getPosition(event.x, event.y);
- if (lastpos == pos && pos >= 0) {
- pos = lastpos;
- event.detail = lastdetail;
- return;
- }
- lastpos = pos;
- dropContext.clean();
- getSourceViewer().getDocument();
- IndexedRegion region = getModel().getIndexedRegion(pos);
- if (region instanceof ElementImpl) {
- ElementImpl jspElement = (ElementImpl) region;
- NamedNodeMap attributes = jspElement.getAttributes();
- if (pos == jspElement.getStartOffset()
- || pos == jspElement.getEndStartOffset()) {
- event.detail = lastdetail = DND.DROP_MOVE;
- return;
- }
- for (int i = 0; i < attributes.getLength(); i++) {
- Node attribute = attributes.item(i);
- if (attribute instanceof AttrImpl) {
- AttrImpl jspAttr = (AttrImpl) attribute;
- ITextRegion valueRegion = jspAttr.getValueRegion();
- if (valueRegion == null) {
- event.detail = lastdetail = DND.DROP_NONE;
- return;
- }
- int startPos = jspElement.getStartOffset()
- + valueRegion.getStart();
- int endPos = jspElement.getStartOffset()
- + valueRegion.getTextEnd();
- if (pos > startPos && pos < endPos) {
- dropContext.setOverAttributeValue(true);
- dropContext.setAttributeName(jspAttr.getNodeName());
- event.detail = lastdetail = DND.DROP_MOVE;
- return;
- }
- }
- }
- event.detail = lastdetail = DND.DROP_NONE;
- } else if (region instanceof Text
- && isInsideResponseRedirect((Text) region, pos
- - region.getStartOffset())) {
- dropContext.setOverAttributeValue(true);
- event.detail = lastdetail = DND.DROP_MOVE;
- } else if (region instanceof Text) {
- event.detail = lastdetail = DND.DROP_MOVE;
- } else if (region instanceof DocumentType) {
- event.detail = lastdetail = DND.DROP_NONE;
- } else if (region == null) {
- //new place
- event.detail = lastdetail = DND.DROP_MOVE;
- }
- }
-
- public void drop(DropTargetEvent event) {
- int offset = getPosition(event.x, event.y);
- selectAndReveal(offset, 0);
- dropContext.runDropCommand(JSPTextEditor.this, event);
- }
-
- public void dropAccept(DropTargetEvent event) {
- }
-
- }
-
- private int getPosition(int x, int y) {
- try {
- ISourceViewer v = getSourceViewer();
- StyledText t = v.getTextWidget();
- Point pp = t.toControl(x, y);
- x = pp.x;
- y = pp.y;
- int lineIndex = (t.getTopPixel() + y) / t.getLineHeight();
- if (lineIndex >= t.getLineCount()) {
- return t.getCharCount();
- } else {
- int c = 0;
- try {
- c = t.getOffsetAtLocation(new Point(x, y));
- if (c < 0)
- c = 0;
- } catch (Exception ex) {
- c = t.getOffsetAtLine(lineIndex + 1)
- - (t.getLineDelimiter() == null ? 0 : t
- .getLineDelimiter().length());
- }
- return c;
- }
- } catch (Exception e) {
- return 0;
- }
- }
-
- public String[] getConfigurationPoints() {
- String contentTypeIdentifierID = null;
- if (getModel() != null)
- contentTypeIdentifierID = getModel().getContentTypeIdentifier();
- return ConfigurationPointCalculator.getConfigurationPoints(this,
- contentTypeIdentifierID, ConfigurationPointCalculator.SOURCE,
- StructuredTextEditor.class);
- }
-
- public void formatTextRegion(IDocument document, IRegion region) {
- SourceViewerConfiguration conf = getSourceViewerConfiguration();
-
- if (conf instanceof StructuredTextViewerConfiguration) {
- StructuredTextViewerConfiguration stvc = (StructuredTextViewerConfiguration) conf;
- IContentFormatter f = stvc.getContentFormatter(getSourceViewer());
- f.format(document, region);
- }
- }
-
- Point storedSelection = new Point(0, 0);
-
- protected void handleCursorPositionChanged() {
- super.handleCursorPositionChanged();
- ISelection selection = getSelectionProvider().getSelection();
- Point p = getTextViewer().getTextWidget().getSelection();
- if (storedSelection == null || !storedSelection.equals(p)) {
- storedSelection = p;
- if (selection instanceof ITextSelection) {
- ITextSelection ts = (ITextSelection) selection;
- if (ts.getLength() == 0) {
- if (vpeController != null) {
- vpeController
- .selectionChanged(new SelectionChangedEvent(
- getSelectionProvider(),
- getSelectionProvider().getSelection()));
- }
- }
- }
- }
- }
-
- static int firingSelectionFailedCount = 0;
-
- private class OutlinePageListener implements IDoubleClickListener,
- ISelectionChangedListener {
- public void doubleClick(DoubleClickEvent event) {
- if (event.getSelection().isEmpty())
- return;
-
- int start = -1;
- int length = 0;
- if (event.getSelection() instanceof IStructuredSelection) {
- ISelection currentSelection = getSelectionProvider()
- .getSelection();
- if (currentSelection instanceof IStructuredSelection) {
- Object current = ((IStructuredSelection) currentSelection)
- .toArray();
- Object newSelection = ((IStructuredSelection) event
- .getSelection()).toArray();
- if (!current.equals(newSelection)) {
- IStructuredSelection selection = (IStructuredSelection) event
- .getSelection();
- Object o = selection.getFirstElement();
- if (o instanceof IndexedRegion) {
- start = ((IndexedRegion) o).getStartOffset();
- length = ((IndexedRegion) o).getEndOffset() - start;
- } else if (o instanceof ITextRegion) {
- start = ((ITextRegion) o).getStart();
- length = ((ITextRegion) o).getEnd() - start;
- } else if (o instanceof IRegion) {
- start = ((ITextRegion) o).getStart();
- length = ((ITextRegion) o).getLength();
- }
- }
- }
- } else if (event.getSelection() instanceof ITextSelection) {
- start = ((ITextSelection) event.getSelection()).getOffset();
- length = ((ITextSelection) event.getSelection()).getLength();
- }
- if (start > -1) {
- getSourceViewer().setRangeIndication(start, length, false);
- selectAndReveal(start, length);
- }
- }
-
- public void selectionChanged(SelectionChangedEvent event) {
- if (event.getSelection().isEmpty() || isFiringSelection())
- return;
-
- boolean ignoreSelection = false;
- if (getSourceViewer() != null
- && getSourceViewer() instanceof IIgnoreSelection) {
- IIgnoreSelection is = ((IIgnoreSelection) getSourceViewer());
- ignoreSelection = is.doesIgnore();
- }
- if (getSourceViewer() != null
- && getSourceViewer().getTextWidget() != null
- && !getSourceViewer().getTextWidget().isDisposed()
- && !getSourceViewer().getTextWidget().isFocusControl()
- && !ignoreSelection) {
- int start = -1;
- int length = 0;
- if (event.getSelection() instanceof IStructuredSelection) {
- ISelection current = getSelectionProvider().getSelection();
- if (current instanceof IStructuredSelection) {
- Object[] currentSelection = ((IStructuredSelection) current)
- .toArray();
- Object[] newSelection = ((IStructuredSelection) event
- .getSelection()).toArray();
- if (!Arrays.equals(currentSelection, newSelection)) {
- if (newSelection.length > 0) {
- /*
- * No ordering is guaranteed for multiple
- * selection
- */
- Object o = newSelection[0];
- if (o instanceof IndexedRegion) {
- start = ((IndexedRegion) o)
- .getStartOffset();
- int end = ((IndexedRegion) o)
- .getEndOffset();
- if (newSelection.length > 1) {
- for (int i = 1; i < newSelection.length; i++) {
- start = Math
- .min(
- start,
- ((IndexedRegion) newSelection[i])
- .getStartOffset());
- end = Math
- .max(
- end,
- ((IndexedRegion) newSelection[i])
- .getEndOffset());
- }
- length = end - start;
- }
- } else if (o instanceof ITextRegion) {
- start = ((ITextRegion) o).getStart();
- int end = ((ITextRegion) o).getEnd();
- if (newSelection.length > 1) {
- for (int i = 1; i < newSelection.length; i++) {
- start = Math
- .min(
- start,
- ((ITextRegion) newSelection[i])
- .getStart());
- end = Math
- .max(
- end,
- ((ITextRegion) newSelection[i])
- .getEnd());
- }
- length = end - start;
- }
- } else if (o instanceof IRegion) {
- start = ((IRegion) o).getOffset();
- int end = start + ((IRegion) o).getLength();
- if (newSelection.length > 1) {
- for (int i = 1; i < newSelection.length; i++) {
- start = Math.min(start,
- ((IRegion) newSelection[i])
- .getOffset());
- end = Math
- .max(
- end,
- ((IRegion) newSelection[i])
- .getOffset()
- + ((IRegion) newSelection[i])
- .getLength());
- }
- length = end - start;
- }
- }
- }
- }
- }
- } else if (event.getSelection() instanceof ITextSelection) {
- start = ((ITextSelection) event.getSelection()).getOffset();
- }
- if (start > -1) {
- updateRangeIndication0(event.getSelection());
- selectAndReveal(start, length);
- }
- }
- }
-
- Method m = null;
-
- private boolean isFiringSelection() {
- if (getSelectionProvider() == null)
- return false;
- if (firingSelectionFailedCount > 0)
- return false;
- try {
- if (m == null) {
- Class c = getSelectionProvider().getClass();
- m = c.getDeclaredMethod("isFiringSelection", new Class[0]);
- m.setAccessible(true);
- }
- Boolean b = (Boolean) m.invoke(getSelectionProvider(),
- new Object[0]);
- return b.booleanValue();
- } catch (Exception e) {
- firingSelectionFailedCount++;
- JspEditorPlugin.getPluginLog().logError(e);
- }
- return false;
- }
- }
-
- private void updateRangeIndication0(ISelection selection) {
- if (selection instanceof IStructuredSelection
- && !((IStructuredSelection) selection).isEmpty()) {
- Object[] objects = ((IStructuredSelection) selection).toArray();
- if (objects.length > 0) {
- int start = ((IndexedRegion) objects[0]).getStartOffset();
- int end = ((IndexedRegion) objects[objects.length - 1])
- .getEndOffset();
- getSourceViewer().setRangeIndication(start, end - start, false);
- } else {
- getSourceViewer().removeRangeIndication();
- }
- } else {
- if (selection instanceof ITextSelection) {
- getSourceViewer().setRangeIndication(
- ((ITextSelection) selection).getOffset(),
- ((ITextSelection) selection).getLength(), false);
- } else {
- getSourceViewer().removeRangeIndication();
- }
- }
- }
-
- protected IExtendedAction createExtendedAction(String actionID) {
- if (StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT
- .equals(actionID)
- || ITextEditorActionConstants.UNDO.equals(actionID)
- || ITextEditorActionConstants.REDO.equals(actionID)) {
- return new ExtendedFormatAction(this, actionID);
- }
- return null;
- }
-
- protected void initializeEditor() {
- super.initializeEditor();
- getPreferenceStore();
- }
-
- public void dispose() {
- if (fOccurrenceModelUpdater != null) {
- fOccurrenceModelUpdater.uninstall();
- fOccurrenceModelUpdater = null;
- }
- super.dispose();
- if (listener != null)
- listener.dispose();
- listener = null;
- }
-
- BodyListenerImpl listener = null;
-
- class BodyListenerImpl implements FileAnyImpl.BodyListener {
- FileAnyImpl file;
-
- BodyListenerImpl(FileAnyImpl file) {
- this.file = file;
- file.addListener(this);
- }
-
- public void bodyChanged(String body) {
- setText(body);
- }
-
- public void dispose() {
- file.removeListener(this);
- }
- }
-
- public void setText(String text) {
- if (getSourceViewer() == null
- || getSourceViewer().getDocument() == null)
- return;
- String txt = getSourceViewer().getDocument().get();
- if (txt != null && txt.length() > 0) {
- if (!TextMerge.replace(getSourceViewer().getDocument(), text)) {
- getSourceViewer().getDocument().set(text);
- }
- } else {
- getSourceViewer().getDocument().set(text);
- }
- }
-
- boolean isInsideResponseRedirect(Text textNode, int off) {
- if (off < 0)
- return false;
- String START = "response.sendRedirect(\"";
- String END = "\")";
- String text = textNode.getNodeValue();
- int i = 0;
- while (i < text.length() && i < off) {
- int i1 = text.indexOf(START, i);
- if (i1 < 0 || i1 + START.length() > off)
- return false;
- int i2 = text.indexOf(END, i1 + START.length());
- if (i2 < 0 || i2 >= off)
- return true;
- i = i2 + END.length();
- }
- return false;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is 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:
+ * Exadel, Inc. and Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Properties;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextListener;
+import org.eclipse.jface.text.ITextSelection;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.TextEvent;
+import org.eclipse.jface.text.formatter.IContentFormatter;
+import org.eclipse.jface.text.source.IAnnotationModel;
+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;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jst.jsp.ui.StructuredTextViewerConfigurationJSP;
+import org.eclipse.jst.jsp.ui.internal.JSPUIPlugin;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.DropTargetListener;
+import org.eclipse.swt.dnd.FileTransfer;
+import org.eclipse.swt.dnd.HTMLTransfer;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.editors.text.ILocationProvider;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.ui.texteditor.ITextEditorActionConstants;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
+import org.eclipse.ui.views.properties.IPropertySheetPage;
+import org.eclipse.ui.views.properties.PropertySheetPage;
+import org.eclipse.ui.views.properties.PropertySheetSorter;
+import org.eclipse.wst.html.ui.StructuredTextViewerConfigurationHTML;
+import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
+import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
+import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
+import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
+import org.eclipse.wst.sse.ui.StructuredTextEditor;
+import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
+import org.eclipse.wst.sse.ui.internal.IModelProvider;
+import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
+import org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants;
+import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage;
+import org.eclipse.wst.sse.ui.internal.properties.ConfigurablePropertySheetPage;
+import org.eclipse.wst.sse.ui.internal.provisional.extensions.ConfigurationPointCalculator;
+import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration;
+import org.eclipse.wst.xml.core.internal.document.AttrImpl;
+import org.eclipse.wst.xml.core.internal.document.ElementImpl;
+import org.jboss.tools.common.core.resources.XModelObjectEditorInput;
+import org.jboss.tools.common.meta.action.XActionInvoker;
+import org.jboss.tools.common.model.XModelBuffer;
+import org.jboss.tools.common.model.XModelObject;
+import org.jboss.tools.common.model.XModelTransferBuffer;
+import org.jboss.tools.common.model.filesystems.impl.FileAnyImpl;
+import org.jboss.tools.common.model.filesystems.impl.FolderImpl;
+import org.jboss.tools.common.model.ui.ModelUIPlugin;
+import org.jboss.tools.common.model.ui.dnd.ModelTransfer;
+import org.jboss.tools.common.model.ui.editor.IModelObjectEditorInput;
+import org.jboss.tools.common.model.ui.editors.dnd.DropCommandFactory;
+import org.jboss.tools.common.model.ui.editors.dnd.DropData;
+import org.jboss.tools.common.model.ui.editors.dnd.IDropCommand;
+import org.jboss.tools.common.model.ui.editors.dnd.JSPTagProposalFactory;
+import org.jboss.tools.common.model.ui.editors.dnd.context.DropContext;
+import org.jboss.tools.common.model.ui.editors.dnd.context.InnerDragBuffer;
+import org.jboss.tools.common.model.ui.texteditors.TextMerge;
+import org.jboss.tools.common.model.ui.texteditors.dnd.TextEditorDrop;
+import org.jboss.tools.common.model.ui.texteditors.dnd.TextEditorDropProvider;
+import org.jboss.tools.common.model.ui.views.palette.IIgnoreSelection;
+import org.jboss.tools.common.model.ui.views.palette.PaletteInsertHelper;
+import org.jboss.tools.common.model.util.XModelObjectLoaderUtil;
+import org.jboss.tools.common.text.xml.IOccurrencePreferenceProvider;
+import org.jboss.tools.common.text.xml.XmlEditorPlugin;
+import org.jboss.tools.common.text.xml.ui.FreeCaretStyledText;
+import org.jboss.tools.jst.jsp.ExtendedStructuredTextViewerConfigurationHTML;
+import org.jboss.tools.jst.jsp.ExtendedStructuredTextViewerConfigurationJSP;
+import org.jboss.tools.jst.jsp.JspEditorPlugin;
+import org.jboss.tools.jst.jsp.editor.IJSPTextEditor;
+import org.jboss.tools.jst.jsp.editor.ITextFormatter;
+import org.jboss.tools.jst.jsp.editor.IVisualController;
+import org.jboss.tools.jst.jsp.outline.JSPContentOutlineConfiguration;
+import org.jboss.tools.jst.jsp.outline.JSPPropertySheetConfiguration;
+import org.jboss.tools.jst.jsp.preferences.VpePreference;
+import org.jboss.tools.jst.jsp.support.kb.WTPTextJspKbConnector;
+import org.jboss.tools.jst.jsp.text.xpl.IStructuredTextOccurrenceStructureProvider;
+import org.jboss.tools.jst.jsp.text.xpl.StructuredTextOccurrenceStructureProviderRegistry;
+import org.jboss.tools.jst.jsp.ui.action.ExtendedFormatAction;
+import org.jboss.tools.jst.jsp.ui.action.IExtendedAction;
+import org.jboss.tools.jst.web.tld.VpeTaglibManager;
+import org.jboss.tools.jst.web.tld.VpeTaglibManagerProvider;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+/**
+ * @author Jeremy
+ *
+ */
+public class JSPTextEditor extends StructuredTextEditor implements
+ ITextListener, IJSPTextEditor, ITextFormatter,
+ IOccurrencePreferenceProvider {
+ private IStructuredTextOccurrenceStructureProvider fOccurrenceModelUpdater;
+
+ TextEditorDrop dnd = new TextEditorDrop();
+
+ JSPMultiPageEditor parentEditor;
+
+ long timeStamp = -1;
+
+ long savedTimeStamp = -1;
+
+ IVisualController vpeController;
+
+ public JSPTextEditor(JSPMultiPageEditor parentEditor) {
+ JspEditorPlugin.getDefault().initDefaultPluginPreferences();
+ dnd.setTextEditorDropProvider(new TextEditorDropProviderImpl());
+ this.parentEditor = parentEditor;
+ super
+ .setSourceViewerConfiguration(new ExtendedStructuredTextViewerConfigurationJSP());
+ }
+
+ protected void setSourceViewerConfiguration(SourceViewerConfiguration config) {
+ if (config instanceof StructuredTextViewerConfigurationJSP) {
+ if (!(config instanceof ExtendedStructuredTextViewerConfigurationJSP)) {
+ config = new ExtendedStructuredTextViewerConfigurationJSP();
+ }
+ } else if (config instanceof StructuredTextViewerConfigurationHTML) {
+ if (!(config instanceof ExtendedStructuredTextViewerConfigurationHTML)) {
+ config = new ExtendedStructuredTextViewerConfigurationHTML();
+ }
+ } else {
+ config = new ExtendedStructuredTextViewerConfigurationJSP();
+ }
+ super.setSourceViewerConfiguration(config);
+ }
+
+ protected void initializeDrop(ITextViewer textViewer) {
+
+ Composite c = textViewer.getTextWidget();
+ Label l = new Label(c, SWT.NONE);
+ l.dispose();
+ }
+
+ private ConfigurableContentOutlinePage fOutlinePage = null;
+
+ private OutlinePageListener fOutlinePageListener = null;
+
+ private IPropertySheetPage fPropertySheetPage;
+
+ public Object getAdapter(Class adapter) {
+ if (ISourceViewer.class.equals(adapter)) {
+ return JSPTextEditor.this.getSourceViewer();
+ } else if (IContentOutlinePage.class.equals(adapter)) {
+ if (fOutlinePage == null || fOutlinePage.getControl() == null
+ || fOutlinePage.getControl().isDisposed()) {
+ IStructuredModel internalModel = getModel();
+ ContentOutlineConfiguration cfg = new JSPContentOutlineConfiguration(
+ this);
+ if (cfg != null) {
+ ConfigurableContentOutlinePage outlinePage = new ConfigurableContentOutlinePage();
+ outlinePage.setConfiguration(cfg);
+ if (internalModel != null) {
+ outlinePage.setInputContentTypeIdentifier(internalModel
+ .getContentTypeIdentifier());
+ outlinePage.setInput(internalModel);
+ }
+
+ if (fOutlinePageListener == null) {
+ fOutlinePageListener = new OutlinePageListener();
+ }
+
+ outlinePage
+ .addSelectionChangedListener(fOutlinePageListener);
+ outlinePage.addDoubleClickListener(fOutlinePageListener);
+
+ fOutlinePage = outlinePage;
+ }
+ }
+ return fOutlinePage;
+ } else if (IPropertySheetPage.class == adapter) {
+ if (fPropertySheetPage == null
+ || fPropertySheetPage.getControl() == null
+ || fPropertySheetPage.getControl().isDisposed()) {
+ JSPPropertySheetConfiguration cfg = new JSPPropertySheetConfiguration();
+ if (cfg != null) {
+ ConfigurablePropertySheetPage propertySheetPage = new ConfigurablePropertySheetPage();
+ propertySheetPage.setConfiguration(cfg);
+ fPropertySheetPage = propertySheetPage;
+ setSorter(cfg.getSorter(), propertySheetPage);
+ }
+ }
+ return fPropertySheetPage;
+ }
+ return super.getAdapter(adapter);
+ }
+
+ private void setSorter(PropertySheetSorter sorter,
+ ConfigurablePropertySheetPage sheet) {
+ try {
+ Method method = PropertySheetPage.class.getDeclaredMethod(
+ "setSorter", new Class[] { PropertySheetSorter.class });
+ method.setAccessible(true);
+ method.invoke(sheet, new Object[] { sorter });
+ } catch (Exception e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ }
+
+ public String getEditorId() {
+ return JSPUIPlugin.ID;
+ }
+
+ public IStructuredTextOccurrenceStructureProvider getOccurrencePreferenceProvider() {
+ return fOccurrenceModelUpdater;
+ }
+
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+
+ StructuredTextOccurrenceStructureProviderRegistry registry = XmlEditorPlugin
+ .getDefault().getOccurrenceStructureProviderRegistry(
+ JspEditorPlugin.PLUGIN_ID);
+ fOccurrenceModelUpdater = registry
+ .getCurrentOccurrenceProvider(JspEditorPlugin.PLUGIN_ID);
+
+ if (fOccurrenceModelUpdater != null)
+ fOccurrenceModelUpdater.install(this, getTextViewer());
+
+ installActivePropmtSupport();
+
+ createDrop();
+ setModified(false);
+ getSourceViewer().removeTextListener(this);
+ getSourceViewer().addTextListener(this);
+
+ Object dtid = getSourceViewer().getTextWidget().getData("DropTarget");
+ if (dtid != null) {
+ if (dtid instanceof DropTarget) {
+ DropTarget dropTarget = (DropTarget) dtid;
+ dropTarget.addDropListener(new DropTargetAdapter() {
+ private FreeCaretStyledText getFreeCaretControl(
+ Object sourceOrTarget) {
+ if (sourceOrTarget == null)
+ return null;
+
+ Object control = null;
+
+ if (sourceOrTarget instanceof DropTarget) {
+ control = ((DropTarget) sourceOrTarget)
+ .getControl();
+ } else if (sourceOrTarget instanceof DragSource) {
+ control = ((DragSource) sourceOrTarget)
+ .getControl();
+ } else
+ return null;
+
+ if (control instanceof FreeCaretStyledText)
+ return (FreeCaretStyledText) control;
+ return null;
+ }
+
+ private int getPosition(StyledText t, int x, int y) {
+ try {
+ Point pp = t.toControl(x, y);
+ x = pp.x;
+ y = pp.y;
+ int lineIndex = (t.getTopPixel() + y)
+ / t.getLineHeight();
+ if (lineIndex >= t.getLineCount()) {
+ return t.getCharCount();
+ } else {
+ int c = 0;
+ try {
+ c = t.getOffsetAtLocation(new Point(x, y));
+ if (c < 0)
+ c = 0;
+ } catch (Exception ex) {
+ c = t.getOffsetAtLine(lineIndex + 1)
+ - (t.getLineDelimiter() == null ? 0
+ : t.getLineDelimiter()
+ .length());
+ }
+ return c;
+ }
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+ public void dragEnter(DropTargetEvent event) {
+ getFreeCaretControl(event.widget).enableFreeCaret(true);
+ }
+
+ public void dragLeave(DropTargetEvent event) {
+ getFreeCaretControl(event.widget).enableFreeCaret(false);
+ }
+
+ public void dragOperationChanged(DropTargetEvent event) {
+ getFreeCaretControl(event.widget).enableFreeCaret(false);
+ }
+
+ public void dragOver(DropTargetEvent event) {
+ FreeCaretStyledText fcst = getFreeCaretControl(event.widget);
+ int pos = getPosition(fcst, event.x, event.y);
+ Point p = fcst.getLocationAtOffset(pos);
+ fcst.myRedraw(p.x, p.y);
+ }
+
+ public void drop(DropTargetEvent event) {
+ getFreeCaretControl(event.widget).enableFreeCaret(false);
+ }
+ });
+ }
+ }
+ }
+
+ protected ISourceViewer createSourceViewer(Composite parent,
+ IVerticalRuler ruler, int styles) {
+ ISourceViewer sv = super.createSourceViewer(parent, ruler, styles);
+ sv.getTextWidget().addFocusListener(new TextFocusListener());
+ return sv;
+ }
+
+ protected StructuredTextViewer createStructedTextViewer(Composite parent,
+ IVerticalRuler verticalRuler, int styles) {
+ return new JSPStructuredTextViewer(parent, verticalRuler,
+ getOverviewRuler(), isOverviewRulerVisible(), styles,
+ parentEditor, this);
+ }
+
+ class TextFocusListener extends FocusAdapter {
+ public void focusLost(FocusEvent e) {
+ if (JSPTextEditor.super.isDirty()) {
+ Display.getDefault().syncExec(new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(200);
+ } catch (InterruptedException exc) {
+ JspEditorPlugin.getPluginLog().logError(exc);
+ }
+ save();
+ }
+ });
+ }
+ }
+ }
+
+ public void save() {
+ if (!lock && isModified()) {
+ lock = true;
+ try {
+ FileAnyImpl f = (FileAnyImpl) getModelObject();
+ if (f != null)
+ f.edit(getSourceViewer().getDocument().get());
+ } catch (Exception e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ } finally {
+ setModified(false);
+ lock = false;
+ }
+ }
+ }
+
+ boolean modified = false;
+
+ public void setModified(boolean set) {
+ if (this.modified != set) {
+ this.modified = set;
+ if (set) {
+ XModelObject o = getModelObject();
+ if (o != null)
+ o.setModified(true);
+ }
+ super.firePropertyChange(IEditorPart.PROP_DIRTY);
+ }
+ }
+
+ public void updateModification() {
+ XModelObject object = getModelObject();
+ if (object != null && !object.isModified() && isModified()) {
+ setModified(false);
+ } else {
+ firePropertyChange(ITextEditor.PROP_DIRTY);
+ }
+ }
+
+ public boolean isModified() {
+ return modified;
+ }
+
+ protected void doSetInput(IEditorInput input) throws CoreException {
+ super.doSetInput(XModelObjectEditorInput.checkInput(input));
+ if (getSourceViewer() != null
+ && getSourceViewer().getDocument() != null) {
+ getSourceViewer().removeTextListener(this);
+ getSourceViewer().addTextListener(this);
+ }
+ if (listener != null)
+ listener.dispose();
+ listener = null;
+ XModelObject o = getModelObject();
+ if (o instanceof FileAnyImpl) {
+ listener = new BodyListenerImpl((FileAnyImpl) o);
+ }
+ }
+
+ boolean lock = false;
+
+ public boolean isDirty() {
+ if (getEditorInput() instanceof IModelObjectEditorInput) {
+ XModelObject o = getModelObject();
+ if (o != null && o.isModified())
+ return true;
+ else {
+ return isModified();
+ }
+ } else {
+ return super.isDirty();
+ }
+ }
+
+ public void doSave(IProgressMonitor monitor) {
+ XModelObject o = getModelObject();
+ super.doSave(monitor);
+ if (o != null && (monitor == null || !monitor.isCanceled())) {
+ if (o != null)
+ save();
+ if (getEditorInput() instanceof ILocationProvider) {
+ XModelObject p = o.getParent();
+ if (p instanceof FolderImpl) {
+ ((FolderImpl) p).saveChild(o);
+ }
+ } else {
+ o.setModified(false);
+ XModelObjectLoaderUtil.updateModifiedOnSave(o);
+ }
+ super.firePropertyChange(IEditorPart.PROP_DIRTY);
+ }
+ }
+
+ public void firePropertyChangeDirty() {
+ super.firePropertyChange(IEditorPart.PROP_DIRTY);
+ }
+
+ public XModelObject getModelObject() {
+ if (getEditorInput() instanceof IModelObjectEditorInput) {
+ return ((IModelObjectEditorInput) getEditorInput())
+ .getXModelObject();
+ }
+ return null;
+ }
+
+ class TextEditorDropProviderImpl implements TextEditorDropProvider {
+
+ public ISourceViewer getSourceViewer() {
+ return JSPTextEditor.this.getSourceViewer();
+ }
+
+ public XModelObject getModelObject() {
+ return JSPTextEditor.this.getModelObject();
+ }
+
+ public void insert(Properties p) {
+ PaletteInsertHelper.insertIntoEditor(getSourceViewer(), p);
+ }
+
+ }
+
+ public void textChanged(TextEvent event) {
+ if (event.getDocumentEvent() != null) {
+ setModified(true);
+ }
+ }
+
+ public void doRevertToSaved() {
+ save();
+ XModelObject o = getModelObject();
+ if (o == null) {
+ super.doRevertToSaved();
+ return;
+ }
+ Properties p = new Properties();
+ XActionInvoker.invoke("DiscardActions.Discard", o, p);
+ if (!"true".equals(p.getProperty("done")))
+ return;
+ super.doRevertToSaved();
+ if (o.isModified())
+ o.setModified(false);
+ modified = false;
+ firePropertyChange(IEditorPart.PROP_DIRTY);
+ updatePartControl(getEditorInput());
+ }
+
+ public IAnnotationModel getAnnotationModel() {
+ return getSourceViewer().getAnnotationModel();
+ }
+
+ private WTPTextJspKbConnector wtpTextJspKbConnector;
+
+ private void installActivePropmtSupport() {
+ try {
+ IDocument document = getTextViewer().getDocument();
+ IStructuredModel model = null;
+ if (getDocumentProvider() instanceof IModelProvider) {
+ model = ((IModelProvider) getDocumentProvider())
+ .getModel(getEditorInput());
+ } else {
+ if (document instanceof IStructuredDocument) {
+ model = getModel();
+ }
+ }
+ if (wtpTextJspKbConnector == null
+ && model != null
+ && (getContentType().toLowerCase().indexOf("jsp") != -1 || getContentType()
+ .toLowerCase().indexOf("html") != -1)) {
+ wtpTextJspKbConnector = new WTPTextJspKbConnector(
+ getEditorInput(), document, model);
+ wtpTextJspKbConnector.setTaglibManagerProvider(parentEditor);
+ }
+ } catch (Exception x) {
+ JspEditorPlugin.getPluginLog().logError("Error while installing active prpmpting support", x);
+ }
+ }
+
+ private String getContentType() {
+ String type = null;
+ try {
+ type = getModel().getContentTypeIdentifier();
+ } finally {
+ if (type == null)
+ type = "";
+ }
+ return type;
+ }
+
+ public WTPTextJspKbConnector getWTPTextJspKbConnector() {
+ return wtpTextJspKbConnector;
+ }
+
+ public static class JSPStructuredTextViewer extends StructuredTextViewer
+ implements VpeTaglibManagerProvider, IIgnoreSelection {
+
+ boolean insertFromPallete = false;
+
+ private VpeTaglibManagerProvider provider;
+
+ private JSPTextEditor editor;
+
+ private boolean ignore = false;
+
+ public JSPStructuredTextViewer(Composite parent,
+ IVerticalRuler verticalRuler, int styles) {
+ super(parent, verticalRuler, null, false, styles);
+ }
+
+ public JSPStructuredTextViewer(Composite parent,
+ IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
+ boolean showAnnotationsOverview, int styles,
+ VpeTaglibManagerProvider provider, JSPTextEditor editor) {
+ super(parent, verticalRuler, overviewRuler,
+ showAnnotationsOverview, styles);
+ this.provider = provider;
+ this.editor = editor;
+ }
+
+ protected StyledText createTextWidget(Composite parent, int styles) {
+ return new FreeCaretStyledText(parent, styles);
+ }
+
+ public VpeTaglibManager getTaglibManager() {
+ if (provider != null) {
+ return provider.getTaglibManager();
+ }
+ return null;
+ }
+
+ public boolean doesIgnore() {
+ return ignore;
+ }
+
+ public void setIgnore(boolean ignore) {
+ this.ignore = ignore;
+ }
+
+ public void doOperation(int operation) {
+ if (operation == UNDO || operation == REDO
+ || operation == FORMAT_DOCUMENT
+ || operation == FORMAT_ACTIVE_ELEMENTS) {
+ if (editor.getVPEController() != null) {
+ editor.getVPEController().preLongOperation();
+ }
+ }
+
+ super.doOperation(operation);
+
+ if (operation == UNDO || operation == REDO
+ || operation == FORMAT_DOCUMENT
+ || operation == FORMAT_ACTIVE_ELEMENTS) {
+ if (editor.getVPEController() != null) {
+ editor.getVPEController().postLongOperation();
+ }
+ }
+ }
+
+ protected void handleDispose() {
+ if (editor != null && editor.getSourceViewer() != null && editor.getSourceViewer().getTextWidget() != null && editor.getVPEController() != null) {
+ StyledText widget = editor.getSourceViewer().getTextWidget();
+ widget.removeSelectionListener(editor.getVPEController());
+ }
+ super.handleDispose();
+ }
+ }
+
+ public JSPMultiPageEditor getParentEditor() {
+ return parentEditor;
+ }
+
+ public void setVPEController(IVisualController c) {
+ vpeController = c;
+ }
+
+ public IVisualController getVPEController() {
+ return vpeController;
+ }
+
+ public void runDropCommand(final String flavor, final String data) {
+ XModelBuffer b = XModelTransferBuffer.getInstance().getBuffer();
+ final XModelObject o = b == null ? null : b.source();
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ if (parentEditor.getVisualEditor().getController() != null) {
+ if(o != null && !XModelTransferBuffer.getInstance().isEnabled()) {
+ XModelTransferBuffer.getInstance().enable();
+ XModelTransferBuffer.getInstance().getBuffer().addSource(o);
+ }
+ try {
+ DropData dropData = new DropData(flavor,
+ data,
+ parentEditor.getVisualEditor().getController()
+ .getPageContext(),
+ getEditorInput(), getSourceViewer(),
+ getSelectionProvider());
+ dropData.setAttributeName(dropContext.getAttributeName());
+ IDropCommand dropCommand = DropCommandFactory.getInstance().getDropCommand(flavor, JSPTagProposalFactory.getInstance());
+
+ boolean promptAttributes = "yes".equals(VpePreference.ALWAYS_REQUEST_FOR_ATTRIBUTE.getValue());
+ dropCommand.getDefaultModel().setPromptForTagAttributesRequired(promptAttributes);
+ dropCommand.execute(dropData);
+ } finally {
+ XModelTransferBuffer.getInstance().disable();
+ }
+ }
+ }
+ });
+ }
+
+ private void createDrop() {
+ DropTarget target = new DropTarget(getSourceViewer().getTextWidget(),
+ DND.DROP_MOVE | DND.DROP_COPY);
+ Transfer[] types = new Transfer[] { ModelTransfer.getInstance(),
+ HTMLTransfer.getInstance(), TextTransfer.getInstance(),
+ FileTransfer.getInstance() };
+ target.setTransfer(types);
+ target.addDropListener(new DTL());
+ }
+
+ DropContext dropContext = new DropContext();
+
+ class DTL implements DropTargetListener {
+ int lastpos = -1;
+
+ int lastdetail = -1;
+
+ public void dragEnter(DropTargetEvent event) {
+ lastpos = -1;
+ }
+
+ public void dragLeave(DropTargetEvent event) {
+ lastpos = -1;
+ }
+
+ public void dragOperationChanged(DropTargetEvent event) {
+ }
+
+ public void dragOver(DropTargetEvent event) {
+ if (!isEditable()
+ || (getModelObject() != null && !getModelObject()
+ .isObjectEditable())) {
+ event.detail = DND.DROP_NONE;
+ return;
+ }
+ dropContext.setDropTargetEvent(event);
+ if (dropContext.getFlavor() == null) {
+ event.detail = DND.DROP_NONE;
+ return;
+ }
+ // Drop from VPE to Source is forbidden
+ if (dropContext.getFlavor().equals("text/html")) {
+ if (InnerDragBuffer.object != null) {
+ event.detail = DND.DROP_NONE;
+ }
+ return;
+ }
+ int pos = getPosition(event.x, event.y);
+ if (lastpos == pos && pos >= 0) {
+ pos = lastpos;
+ event.detail = lastdetail;
+ return;
+ }
+ lastpos = pos;
+ dropContext.clean();
+ getSourceViewer().getDocument();
+ IndexedRegion region = getModel().getIndexedRegion(pos);
+ if (region instanceof ElementImpl) {
+ ElementImpl jspElement = (ElementImpl) region;
+ NamedNodeMap attributes = jspElement.getAttributes();
+ if (pos == jspElement.getStartOffset()
+ || pos == jspElement.getEndStartOffset()) {
+ event.detail = lastdetail = DND.DROP_MOVE;
+ return;
+ }
+ for (int i = 0; i < attributes.getLength(); i++) {
+ Node attribute = attributes.item(i);
+ if (attribute instanceof AttrImpl) {
+ AttrImpl jspAttr = (AttrImpl) attribute;
+ ITextRegion valueRegion = jspAttr.getValueRegion();
+ if (valueRegion == null) {
+ event.detail = lastdetail = DND.DROP_NONE;
+ return;
+ }
+ int startPos = jspElement.getStartOffset()
+ + valueRegion.getStart();
+ int endPos = jspElement.getStartOffset()
+ + valueRegion.getTextEnd();
+ if (pos > startPos && pos < endPos) {
+ dropContext.setOverAttributeValue(true);
+ dropContext.setAttributeName(jspAttr.getNodeName());
+ event.detail = lastdetail = DND.DROP_MOVE;
+ return;
+ }
+ }
+ }
+ event.detail = lastdetail = DND.DROP_NONE;
+ } else if (region instanceof Text
+ && isInsideResponseRedirect((Text) region, pos
+ - region.getStartOffset())) {
+ dropContext.setOverAttributeValue(true);
+ event.detail = lastdetail = DND.DROP_MOVE;
+ } else if (region instanceof Text) {
+ event.detail = lastdetail = DND.DROP_MOVE;
+ } else if (region instanceof DocumentType) {
+ event.detail = lastdetail = DND.DROP_NONE;
+ } else if (region == null) {
+ //new place
+ event.detail = lastdetail = DND.DROP_MOVE;
+ }
+ }
+
+ public void drop(DropTargetEvent event) {
+ int offset = getPosition(event.x, event.y);
+ selectAndReveal(offset, 0);
+ dropContext.runDropCommand(JSPTextEditor.this, event);
+ }
+
+ public void dropAccept(DropTargetEvent event) {
+ }
+
+ }
+
+ private int getPosition(int x, int y) {
+ try {
+ ISourceViewer v = getSourceViewer();
+ StyledText t = v.getTextWidget();
+ Point pp = t.toControl(x, y);
+ x = pp.x;
+ y = pp.y;
+ int lineIndex = (t.getTopPixel() + y) / t.getLineHeight();
+ if (lineIndex >= t.getLineCount()) {
+ return t.getCharCount();
+ } else {
+ int c = 0;
+ try {
+ c = t.getOffsetAtLocation(new Point(x, y));
+ if (c < 0)
+ c = 0;
+ } catch (Exception ex) {
+ c = t.getOffsetAtLine(lineIndex + 1)
+ - (t.getLineDelimiter() == null ? 0 : t
+ .getLineDelimiter().length());
+ }
+ return c;
+ }
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+ public String[] getConfigurationPoints() {
+ String contentTypeIdentifierID = null;
+ if (getModel() != null)
+ contentTypeIdentifierID = getModel().getContentTypeIdentifier();
+ return ConfigurationPointCalculator.getConfigurationPoints(this,
+ contentTypeIdentifierID, ConfigurationPointCalculator.SOURCE,
+ StructuredTextEditor.class);
+ }
+
+ public void formatTextRegion(IDocument document, IRegion region) {
+ SourceViewerConfiguration conf = getSourceViewerConfiguration();
+
+ if (conf instanceof StructuredTextViewerConfiguration) {
+ StructuredTextViewerConfiguration stvc = (StructuredTextViewerConfiguration) conf;
+ IContentFormatter f = stvc.getContentFormatter(getSourceViewer());
+ f.format(document, region);
+ }
+ }
+
+ Point storedSelection = new Point(0, 0);
+
+ protected void handleCursorPositionChanged() {
+ super.handleCursorPositionChanged();
+ ISelection selection = getSelectionProvider().getSelection();
+ Point p = getTextViewer().getTextWidget().getSelection();
+ if (storedSelection == null || !storedSelection.equals(p)) {
+ storedSelection = p;
+ if (selection instanceof ITextSelection) {
+ ITextSelection ts = (ITextSelection) selection;
+ if (ts.getLength() == 0) {
+ if (vpeController != null) {
+ vpeController
+ .selectionChanged(new SelectionChangedEvent(
+ getSelectionProvider(),
+ getSelectionProvider().getSelection()));
+ }
+ }
+ }
+ }
+ }
+
+ static int firingSelectionFailedCount = 0;
+
+ private class OutlinePageListener implements IDoubleClickListener,
+ ISelectionChangedListener {
+ public void doubleClick(DoubleClickEvent event) {
+ if (event.getSelection().isEmpty())
+ return;
+
+ int start = -1;
+ int length = 0;
+ if (event.getSelection() instanceof IStructuredSelection) {
+ ISelection currentSelection = getSelectionProvider()
+ .getSelection();
+ if (currentSelection instanceof IStructuredSelection) {
+ Object current = ((IStructuredSelection) currentSelection)
+ .toArray();
+ Object newSelection = ((IStructuredSelection) event
+ .getSelection()).toArray();
+ if (!current.equals(newSelection)) {
+ IStructuredSelection selection = (IStructuredSelection) event
+ .getSelection();
+ Object o = selection.getFirstElement();
+ if (o instanceof IndexedRegion) {
+ start = ((IndexedRegion) o).getStartOffset();
+ length = ((IndexedRegion) o).getEndOffset() - start;
+ } else if (o instanceof ITextRegion) {
+ start = ((ITextRegion) o).getStart();
+ length = ((ITextRegion) o).getEnd() - start;
+ } else if (o instanceof IRegion) {
+ start = ((ITextRegion) o).getStart();
+ length = ((ITextRegion) o).getLength();
+ }
+ }
+ }
+ } else if (event.getSelection() instanceof ITextSelection) {
+ start = ((ITextSelection) event.getSelection()).getOffset();
+ length = ((ITextSelection) event.getSelection()).getLength();
+ }
+ if (start > -1) {
+ getSourceViewer().setRangeIndication(start, length, false);
+ selectAndReveal(start, length);
+ }
+ }
+
+ public void selectionChanged(SelectionChangedEvent event) {
+ if (event.getSelection().isEmpty() || isFiringSelection())
+ return;
+
+ boolean ignoreSelection = false;
+ if (getSourceViewer() != null
+ && getSourceViewer() instanceof IIgnoreSelection) {
+ IIgnoreSelection is = ((IIgnoreSelection) getSourceViewer());
+ ignoreSelection = is.doesIgnore();
+ }
+ if (getSourceViewer() != null
+ && getSourceViewer().getTextWidget() != null
+ && !getSourceViewer().getTextWidget().isDisposed()
+ && !getSourceViewer().getTextWidget().isFocusControl()
+ && !ignoreSelection) {
+ int start = -1;
+ int length = 0;
+ if (event.getSelection() instanceof IStructuredSelection) {
+ ISelection current = getSelectionProvider().getSelection();
+ if (current instanceof IStructuredSelection) {
+ Object[] currentSelection = ((IStructuredSelection) current)
+ .toArray();
+ Object[] newSelection = ((IStructuredSelection) event
+ .getSelection()).toArray();
+ if (!Arrays.equals(currentSelection, newSelection)) {
+ if (newSelection.length > 0) {
+ /*
+ * No ordering is guaranteed for multiple
+ * selection
+ */
+ Object o = newSelection[0];
+ if (o instanceof IndexedRegion) {
+ start = ((IndexedRegion) o)
+ .getStartOffset();
+ int end = ((IndexedRegion) o)
+ .getEndOffset();
+ if (newSelection.length > 1) {
+ for (int i = 1; i < newSelection.length; i++) {
+ start = Math
+ .min(
+ start,
+ ((IndexedRegion) newSelection[i])
+ .getStartOffset());
+ end = Math
+ .max(
+ end,
+ ((IndexedRegion) newSelection[i])
+ .getEndOffset());
+ }
+ length = end - start;
+ }
+ } else if (o instanceof ITextRegion) {
+ start = ((ITextRegion) o).getStart();
+ int end = ((ITextRegion) o).getEnd();
+ if (newSelection.length > 1) {
+ for (int i = 1; i < newSelection.length; i++) {
+ start = Math
+ .min(
+ start,
+ ((ITextRegion) newSelection[i])
+ .getStart());
+ end = Math
+ .max(
+ end,
+ ((ITextRegion) newSelection[i])
+ .getEnd());
+ }
+ length = end - start;
+ }
+ } else if (o instanceof IRegion) {
+ start = ((IRegion) o).getOffset();
+ int end = start + ((IRegion) o).getLength();
+ if (newSelection.length > 1) {
+ for (int i = 1; i < newSelection.length; i++) {
+ start = Math.min(start,
+ ((IRegion) newSelection[i])
+ .getOffset());
+ end = Math
+ .max(
+ end,
+ ((IRegion) newSelection[i])
+ .getOffset()
+ + ((IRegion) newSelection[i])
+ .getLength());
+ }
+ length = end - start;
+ }
+ }
+ }
+ }
+ }
+ } else if (event.getSelection() instanceof ITextSelection) {
+ start = ((ITextSelection) event.getSelection()).getOffset();
+ }
+ if (start > -1) {
+ updateRangeIndication0(event.getSelection());
+ selectAndReveal(start, length);
+ }
+ }
+ }
+
+ Method m = null;
+
+ private boolean isFiringSelection() {
+ if (getSelectionProvider() == null)
+ return false;
+ if (firingSelectionFailedCount > 0)
+ return false;
+ try {
+ if (m == null) {
+ Class c = getSelectionProvider().getClass();
+ m = c.getDeclaredMethod("isFiringSelection", new Class[0]);
+ m.setAccessible(true);
+ }
+ Boolean b = (Boolean) m.invoke(getSelectionProvider(),
+ new Object[0]);
+ return b.booleanValue();
+ } catch (Exception e) {
+ firingSelectionFailedCount++;
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ return false;
+ }
+ }
+
+ private void updateRangeIndication0(ISelection selection) {
+ if (selection instanceof IStructuredSelection
+ && !((IStructuredSelection) selection).isEmpty()) {
+ Object[] objects = ((IStructuredSelection) selection).toArray();
+ if (objects.length > 0) {
+ int start = ((IndexedRegion) objects[0]).getStartOffset();
+ int end = ((IndexedRegion) objects[objects.length - 1])
+ .getEndOffset();
+ getSourceViewer().setRangeIndication(start, end - start, false);
+ } else {
+ getSourceViewer().removeRangeIndication();
+ }
+ } else {
+ if (selection instanceof ITextSelection) {
+ getSourceViewer().setRangeIndication(
+ ((ITextSelection) selection).getOffset(),
+ ((ITextSelection) selection).getLength(), false);
+ } else {
+ getSourceViewer().removeRangeIndication();
+ }
+ }
+ }
+
+ protected IExtendedAction createExtendedAction(String actionID) {
+ if (StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT
+ .equals(actionID)
+ || ITextEditorActionConstants.UNDO.equals(actionID)
+ || ITextEditorActionConstants.REDO.equals(actionID)) {
+ return new ExtendedFormatAction(this, actionID);
+ }
+ return null;
+ }
+
+ protected void initializeEditor() {
+ super.initializeEditor();
+ getPreferenceStore();
+ }
+
+ public void dispose() {
+ // some things in the configuration need to clean
+ // up after themselves
+ getSourceViewer().removeTextListener(this);
+ if (fOutlinePage != null) {
+ if (fOutlinePage instanceof ConfigurableContentOutlinePage && fOutlinePageListener != null) {
+ ((ConfigurableContentOutlinePage) fOutlinePage).removeDoubleClickListener(fOutlinePageListener);
+ }
+ if (fOutlinePageListener != null) {
+ fOutlinePage.removeSelectionChangedListener(fOutlinePageListener);
+ }
+ }
+ fOutlinePage=null;
+ fOutlinePageListener=null;
+ if (fOccurrenceModelUpdater != null) {
+ fOccurrenceModelUpdater.uninstall();
+ fOccurrenceModelUpdater = null;
+ }
+ super.dispose();
+ if (wtpTextJspKbConnector != null) {
+ wtpTextJspKbConnector.setTaglibManagerProvider(null);
+ wtpTextJspKbConnector = null;
+ }
+ if (listener != null)
+ listener.dispose();
+ listener = null;
+ }
+
+ BodyListenerImpl listener = null;
+
+ class BodyListenerImpl implements FileAnyImpl.BodyListener {
+ FileAnyImpl file;
+
+ BodyListenerImpl(FileAnyImpl file) {
+ this.file = file;
+ file.addListener(this);
+ }
+
+ public void bodyChanged(String body) {
+ setText(body);
+ }
+
+ public void dispose() {
+ file.removeListener(this);
+ }
+ }
+
+ public void setText(String text) {
+ if (getSourceViewer() == null
+ || getSourceViewer().getDocument() == null)
+ return;
+ String txt = getSourceViewer().getDocument().get();
+ if (txt != null && txt.length() > 0) {
+ if (!TextMerge.replace(getSourceViewer().getDocument(), text)) {
+ getSourceViewer().getDocument().set(text);
+ }
+ } else {
+ getSourceViewer().getDocument().set(text);
+ }
+ }
+
+ boolean isInsideResponseRedirect(Text textNode, int off) {
+ if (off < 0)
+ return false;
+ String START = "response.sendRedirect(\"";
+ String END = "\")";
+ String text = textNode.getNodeValue();
+ int i = 0;
+ while (i < text.length() && i < off) {
+ int i1 = text.indexOf(START, i);
+ if (i1 < 0 || i1 + START.length() > off)
+ return false;
+ int i2 = text.indexOf(END, i1 + START.length());
+ if (i2 < 0 || i2 >= off)
+ return true;
+ i = i2 + END.length();
+ }
+ return false;
+ }
+}
Modified: trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditorPageContext.java
===================================================================
--- trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditorPageContext.java 2008-02-07 06:15:54 UTC (rev 6142)
+++ trunk/jst/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/jspeditor/JSPTextEditorPageContext.java 2008-02-07 09:57:05 UTC (rev 6143)
@@ -1,298 +1,299 @@
-/*******************************************************************************
-
-* Copyright (c) 2007 Red Hat, Inc.
-* Distributed under license by Red Hat, Inc. All rights reserved.
-* This program is 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:
-* Red Hat, Inc. - initial API and implementation
-******************************************************************************/
-package org.jboss.tools.jst.jsp.jspeditor;
-
-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 org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.jboss.tools.common.kb.KbConnectorFactory;
-import org.jboss.tools.common.kb.KbConnectorType;
-import org.jboss.tools.common.kb.wtp.WtpKbConnector;
-import org.jboss.tools.jst.jsp.JspEditorPlugin;
-import org.jboss.tools.jst.jsp.editor.IVisualContext;
-import org.jboss.tools.jst.web.tld.TaglibData;
-import org.jboss.tools.jst.web.tld.VpeTaglibListener;
-import org.w3c.dom.Attr;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * @author Vitali (vyemialyanchyk(a)exadel.com)
- *
- * Class responsible to register TagLib data suitable for the current context
- */
-public class JSPTextEditorPageContext implements IVisualContext {
-
- protected ArrayList<TaglibData> taglibs = new ArrayList<TaglibData>();
- protected Map<String, String> taglibMap = new HashMap<String, String>();
- // this is just reference to VpeTemplateManager.templateTaglibs
- private Map<String,String> templateTaglibs = null;
- protected WtpKbConnector connector = null;
- //protected IDocument document = null;
- protected IDOMDocument document = null;
- protected Node referenceNode = null;
- protected int freeID = 0;
- protected ArrayList<VpeTaglibListener> taglibListeners = new ArrayList<VpeTaglibListener>();
-
- public JSPTextEditorPageContext() {
- // simple tests
- //addTaglib(123, "vitaliNewUri", "vitaliNewPrefix", true);
- //addTaglib(123, "http://java.sun.com/jsf/facelets", "1xmlns:ui11", true);
- //addTaglib(234, "http://java.sun.com/jsf/html", "2xmlns:ui22", true);
- //addTaglib(345, "http://richfaces.org/rich", "3xmlns:ui33", true);
- }
-
- public void clearAll() {
- taglibs.clear();
- taglibMap.clear();
- templateTaglibs = null;
- }
-
- public void dispose() {
- clearAll();
- connector = null;
- document = null;
- referenceNode = null;
- taglibListeners = null;
- }
-
- public void setReferenceNode(Node refNode) {
- if (referenceNode == refNode) {
- return;
- }
- referenceNode = refNode;
- updateTagLibs();
- }
-
- //public void setDocument(IDocument doc) {
- public void setDocument(IDOMDocument doc) {
- if (document == doc) {
- return;
- }
- document = doc;
- setReferenceNode(document);
- try {
- connector = (WtpKbConnector)KbConnectorFactory.getIntstance().createConnector(KbConnectorType.JSP_WTP_KB_CONNECTOR, document);
- } catch (InstantiationException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- } catch (IllegalAccessException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- } catch (ClassNotFoundException e) {
- JspEditorPlugin.getPluginLog().logError(e);
- }
- updateTagLibs();
- }
-
- public boolean processAttribute(Attr attr, boolean bScopePrefix) {
- if (null == attr) {
- return false;
- }
- String startStr = "xmlns:";
- String name = attr.getName();
- if (!name.startsWith(startStr)) {
- return false;
- }
- name = name.substring(startStr.length());
- addTaglib(freeID++, attr.getValue(), name, true, bScopePrefix);
- return true;
- }
-
- public boolean processNode(Node node) {
- if (null == node) {
- return false;
- }
- String nodeName = node.getNodeName();
- // example: add some filter here
- //if (!"ui:composition".equalsIgnoreCase(nodeName)) {
- // return false;
- //}
- boolean bTestRes = false;
- NamedNodeMap attribList = node.getAttributes();
- if (null != attribList) {
- for (int i = 0; i < attribList.getLength(); i++) {
- Node tmp = attribList.item(i);
- bTestRes = processAttribute((Attr)tmp, false);
- }
- }
- NodeList nodeList = node.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node tmp = nodeList.item(i);
- bTestRes = processNode(tmp);
- }
- return true;
- }
-
- public void collectDocumentTagLibs() {
- if (null == document) {
- return;
- }
- NodeList nodeList = document.getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- Node node = nodeList.item(i);
- processNode(node);
- }
- }
-
- public boolean processNodeUp(Node node) {
- if (null == node) {
- return false;
- }
- boolean bTestRes = false;
- NamedNodeMap attribList = node.getAttributes();
- if (null != attribList) {
- for (int i = 0; i < attribList.getLength(); i++) {
- Node tmp = attribList.item(i);
- bTestRes = processAttribute((Attr)tmp, true);
- }
- }
- bTestRes = processNodeUp(node.getParentNode());
- return true;
- }
-
- public void collectRefNodeTagLibs() {
- processNodeUp(referenceNode);
- }
-
- public void updateTagLibs() {
- taglibs.clear();
- freeID = 0;
- // collect all taglibs for the document - from top tree node to leafs
- //collectDocumentTagLibs();
- // collect all taglibs starting from reference node through its parents to the top node
- // parent's taglibs has lower priority then child taglibs
- collectRefNodeTagLibs();
- //
- for (Iterator<VpeTaglibListener> it = taglibListeners.iterator(); it.hasNext(); ) {
- it.next().taglibPrefixChanged(null);
- }
- rebuildTaglibMap();
- }
-
- private boolean rebuildTaglibMap() {
- taglibMap.clear();
- if (null == templateTaglibs) {
- return false;
- }
- Set<String> prefixSet = new HashSet<String>();
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- String prefix = taglib.getPrefix();
- if (!prefixSet.contains(prefix)) {
- String templatePrefix = templateTaglibs.get(taglib.getUri());
- if (templatePrefix != null) {
- taglibMap.put(prefix, templatePrefix);
- }
- prefixSet.add(prefix);
- }
- }
- return true;
- }
-
- /**
- * This is a way to use templateTaglibs from
- * org.jboss.tools.vpe.editor.template.VpeTemplateManager;
- * this is just reference to VpeTemplateManager.templateTaglibs
- * getter is prohibited here
- **/
- public void setTemplateTaglibs(Map<String,String> templateTaglibs) {
- this.templateTaglibs = templateTaglibs;
- rebuildTaglibMap();
- }
-
- /**
- * Return template taglib prefix using prefix as a key.
- * @return
- */
- public String getTemplateTaglibPrefix(String sourceTaglibPrefix) {
- return taglibMap.get(sourceTaglibPrefix);
- }
-
- // adds new tag library
- // removes tag library with id - if newUri or newPrefix is null
- public void addTaglib(int id, String newUri, String newPrefix, boolean ns, boolean bScopePrefix) {
- if (newUri == null || newPrefix == null) {
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- if (taglib.getId() == id) {
- taglibs.remove(i);
- break;
- }
- }
- return;
- }
- boolean bHasSame = false;
- for (int i = 0; i < taglibs.size(); i++) {
- TaglibData taglib = (TaglibData)taglibs.get(i);
- if (taglib.getId() == id) {
- if (!newUri.equals(taglib.getUri()) || !newPrefix.equals(taglib.getPrefix())) {
- taglibs.set(i, new TaglibData(id, newUri, newPrefix, ns));
- }
- return;
- }
- if (bScopePrefix && newPrefix.equals(taglib.getPrefix())) {
- return;
- }
- if (newUri.equals(taglib.getUri()) && newPrefix.equals(taglib.getPrefix()) && ns == taglib.isNs()) {
- bHasSame = true;
- break;
- }
- }
- if (!bHasSame) {
- taglibs.add(new TaglibData(id, newUri, newPrefix, ns));
- }
- }
-
- // implements IVisualContext
- public WtpKbConnector getConnector() {
- return connector;
- }
-
- // implements IVisualContext
- public void refreshBundleValues() {
- updateTagLibs();
- }
-
- // implements IVisualContext
- public List<TaglibData> getTagLibs() {
- List<TaglibData> clone = new ArrayList<TaglibData>();
- Iterator<TaglibData> iter = taglibs.iterator();
- while (iter.hasNext()) {
- TaglibData taglib = (TaglibData)iter.next();
- if (!taglib.inList(clone)) {
- clone.add(taglib);
- }
- }
- return clone;
- }
-
- // implements IVisualContext
- public void addTaglibListener(VpeTaglibListener listener) {
- if (taglibListeners.contains(listener)) {
- return;
- }
- taglibListeners.add(listener);
- }
-
- // implements IVisualContext
- public void removeTaglibListener(VpeTaglibListener listener) {
- taglibListeners.remove(listener);
- }
-
-}
+/*******************************************************************************
+
+* Copyright (c) 2007 Red Hat, Inc.
+* Distributed under license by Red Hat, Inc. All rights reserved.
+* This program is 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:
+* Red Hat, Inc. - initial API and implementation
+******************************************************************************/
+package org.jboss.tools.jst.jsp.jspeditor;
+
+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 org.eclipse.jface.text.IDocument;
+import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
+import org.jboss.tools.common.kb.KbConnectorFactory;
+import org.jboss.tools.common.kb.KbConnectorType;
+import org.jboss.tools.common.kb.wtp.WtpKbConnector;
+import org.jboss.tools.jst.jsp.JspEditorPlugin;
+import org.jboss.tools.jst.jsp.editor.IVisualContext;
+import org.jboss.tools.jst.web.tld.TaglibData;
+import org.jboss.tools.jst.web.tld.VpeTaglibListener;
+import org.w3c.dom.Attr;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author Vitali (vyemialyanchyk(a)exadel.com)
+ *
+ * Class responsible to register TagLib data suitable for the current context
+ */
+public class JSPTextEditorPageContext implements IVisualContext {
+
+ protected ArrayList<TaglibData> taglibs = new ArrayList<TaglibData>();
+ protected Map<String, String> taglibMap = new HashMap<String, String>();
+ // this is just reference to VpeTemplateManager.templateTaglibs
+ private Map<String,String> templateTaglibs = null;
+ protected WtpKbConnector connector = null;
+ //protected IDocument document = null;
+ protected IDOMDocument document = null;
+ protected Node referenceNode = null;
+ protected int freeID = 0;
+ protected ArrayList<VpeTaglibListener> taglibListeners = new ArrayList<VpeTaglibListener>();
+
+ public JSPTextEditorPageContext() {
+ // simple tests
+ //addTaglib(123, "vitaliNewUri", "vitaliNewPrefix", true);
+ //addTaglib(123, "http://java.sun.com/jsf/facelets", "1xmlns:ui11", true);
+ //addTaglib(234, "http://java.sun.com/jsf/html", "2xmlns:ui22", true);
+ //addTaglib(345, "http://richfaces.org/rich", "3xmlns:ui33", true);
+ }
+
+ public void clearAll() {
+ taglibs.clear();
+ taglibMap.clear();
+ templateTaglibs = null;
+ }
+
+ public void dispose() {
+ clearAll();
+ connector = null;
+ document = null;
+ referenceNode = null;
+ taglibListeners = null;
+ }
+
+ public void setReferenceNode(Node refNode) {
+ if (referenceNode == refNode) {
+ return;
+ }
+ referenceNode = refNode;
+ updateTagLibs();
+ }
+
+ //public void setDocument(IDocument doc) {
+ public void setDocument(IDOMDocument doc) {
+ if (document == doc) {
+ return;
+ }
+ document = doc;
+ setReferenceNode(document);
+ try {
+ connector = (WtpKbConnector)KbConnectorFactory.getIntstance().createConnector(KbConnectorType.JSP_WTP_KB_CONNECTOR, document);
+ } catch (InstantiationException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ } catch (IllegalAccessException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ } catch (ClassNotFoundException e) {
+ JspEditorPlugin.getPluginLog().logError(e);
+ }
+ updateTagLibs();
+ }
+
+ public boolean processAttribute(Attr attr, boolean bScopePrefix) {
+ if (null == attr) {
+ return false;
+ }
+ String startStr = "xmlns:";
+ String name = attr.getName();
+ if (!name.startsWith(startStr)) {
+ return false;
+ }
+ name = name.substring(startStr.length());
+ addTaglib(freeID++, attr.getValue(), name, true, bScopePrefix);
+ return true;
+ }
+
+ public boolean processNode(Node node) {
+ if (null == node) {
+ return false;
+ }
+ String nodeName = node.getNodeName();
+ // example: add some filter here
+ //if (!"ui:composition".equalsIgnoreCase(nodeName)) {
+ // return false;
+ //}
+ boolean bTestRes = false;
+ NamedNodeMap attribList = node.getAttributes();
+ if (null != attribList) {
+ for (int i = 0; i < attribList.getLength(); i++) {
+ Node tmp = attribList.item(i);
+ bTestRes = processAttribute((Attr)tmp, false);
+ }
+ }
+ NodeList nodeList = node.getChildNodes();
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node tmp = nodeList.item(i);
+ bTestRes = processNode(tmp);
+ }
+ return true;
+ }
+
+ public void collectDocumentTagLibs() {
+ if (null == document) {
+ return;
+ }
+ NodeList nodeList = document.getChildNodes();
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node node = nodeList.item(i);
+ processNode(node);
+ }
+ }
+
+ public boolean processNodeUp(Node node) {
+ if (null == node) {
+ return false;
+ }
+ boolean bTestRes = false;
+ NamedNodeMap attribList = node.getAttributes();
+ if (null != attribList) {
+ for (int i = 0; i < attribList.getLength(); i++) {
+ Node tmp = attribList.item(i);
+ bTestRes = processAttribute((Attr)tmp, true);
+ }
+ }
+ bTestRes = processNodeUp(node.getParentNode());
+ return true;
+ }
+
+ public void collectRefNodeTagLibs() {
+ processNodeUp(referenceNode);
+ }
+
+ public void updateTagLibs() {
+ taglibs.clear();
+ freeID = 0;
+ // collect all taglibs for the document - from top tree node to leafs
+ //collectDocumentTagLibs();
+ // collect all taglibs starting from reference node through its parents to the top node
+ // parent's taglibs has lower priority then child taglibs
+ collectRefNodeTagLibs();
+ //
+ for (Iterator<VpeTaglibListener> it = taglibListeners.iterator(); it.hasNext(); ) {
+ it.next().taglibPrefixChanged(null);
+ }
+ rebuildTaglibMap();
+ }
+
+ private boolean rebuildTaglibMap() {
+ taglibMap.clear();
+ if (null == templateTaglibs) {
+ return false;
+ }
+ Set<String> prefixSet = new HashSet<String>();
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ String prefix = taglib.getPrefix();
+ if (!prefixSet.contains(prefix)) {
+ String templatePrefix = templateTaglibs.get(taglib.getUri());
+ if (templatePrefix != null) {
+ taglibMap.put(prefix, templatePrefix);
+ }
+ prefixSet.add(prefix);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * This is a way to use templateTaglibs from
+ * org.jboss.tools.vpe.editor.template.VpeTemplateManager;
+ * this is just reference to VpeTemplateManager.templateTaglibs
+ * getter is prohibited here
+ **/
+ public void setTemplateTaglibs(Map<String,String> templateTaglibs) {
+ this.templateTaglibs = templateTaglibs;
+ rebuildTaglibMap();
+ }
+
+ /**
+ * Return template taglib prefix using prefix as a key.
+ * @return
+ */
+ public String getTemplateTaglibPrefix(String sourceTaglibPrefix) {
+ return taglibMap.get(sourceTaglibPrefix);
+ }
+
+ // adds new tag library
+ // removes tag library with id - if newUri or newPrefix is null
+ public void addTaglib(int id, String newUri, String newPrefix, boolean ns, boolean bScopePrefix) {
+ if (newUri == null || newPrefix == null) {
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ if (taglib.getId() == id) {
+ taglibs.remove(i);
+ break;
+ }
+ }
+ return;
+ }
+ boolean bHasSame = false;
+ for (int i = 0; i < taglibs.size(); i++) {
+ TaglibData taglib = (TaglibData)taglibs.get(i);
+ if (taglib.getId() == id) {
+ if (!newUri.equals(taglib.getUri()) || !newPrefix.equals(taglib.getPrefix())) {
+ taglibs.set(i, new TaglibData(id, newUri, newPrefix, ns));
+ }
+ return;
+ }
+ if (bScopePrefix && newPrefix.equals(taglib.getPrefix())) {
+ return;
+ }
+ if (newUri.equals(taglib.getUri()) && newPrefix.equals(taglib.getPrefix()) && ns == taglib.isNs()) {
+ bHasSame = true;
+ break;
+ }
+ }
+ if (!bHasSame) {
+ taglibs.add(new TaglibData(id, newUri, newPrefix, ns));
+ }
+ }
+
+ // implements IVisualContext
+ public WtpKbConnector getConnector() {
+ return connector;
+ }
+
+ // implements IVisualContext
+ public void refreshBundleValues() {
+ updateTagLibs();
+ }
+
+ // implements IVisualContext
+ public List<TaglibData> getTagLibs() {
+ List<TaglibData> clone = new ArrayList<TaglibData>();
+ Iterator<TaglibData> iter = taglibs.iterator();
+ while (iter.hasNext()) {
+ TaglibData taglib = (TaglibData)iter.next();
+ //if (!taglib.inList(clone)) {
+ if (!clone.contains(taglib)) {
+ clone.add(taglib);
+ }
+ }
+ return clone;
+ }
+
+ // implements IVisualContext
+ public void addTaglibListener(VpeTaglibListener listener) {
+ if (taglibListeners.contains(listener)) {
+ return;
+ }
+ taglibListeners.add(listener);
+ }
+
+ // implements IVisualContext
+ public void removeTaglibListener(VpeTaglibListener listener) {
+ taglibListeners.remove(listener);
+ }
+
+}
16 years, 4 months